var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name"),_a,_b,_c,__spreadArray$1=globalThis&&globalThis.__spreadArray||function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i=0;i--)if(indexed?fn(array[i],i,array):fn(array[i]))return array[i]}},"_findLast");(function(findLast2){function indexed(){return purry(_findLast(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),findLast2.indexed=indexed})(findLast||(findLast={}));function fromPairs(entries){for(var out={},_i=0,entries_1=entries;_iretMax)&&(ret=item,retMax=max)}),ret}},"_maxBy");function maxBy(){return purry(_maxBy(!1),arguments)}__name(maxBy,"maxBy"),__name2(maxBy,"maxBy"),function(maxBy2){function indexed(){return purry(_maxBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),maxBy2.indexed=indexed}(maxBy||(maxBy={}));var _meanBy=__name2(function(indexed){return function(array,fn){if(array.length===0)return NaN;var sum=0;return array.forEach(function(item,i){sum+=indexed?fn(item,i,array):fn(item)}),sum/array.length}},"_meanBy");function meanBy(){return purry(_meanBy(!1),arguments)}__name(meanBy,"meanBy"),__name2(meanBy,"meanBy"),function(meanBy2){function indexed(){return purry(_meanBy(!0),arguments)}__name(indexed,"indexed"),__name2(indexed,"indexed"),meanBy2.indexed=indexed}(meanBy||(meanBy={}));var __assign$1=globalThis&&globalThis.__assign||function(){return __assign$1=Object.assign||function(t2){for(var s2,i=1,n2=arguments.length;iy},desc:function(x,y){return x0?!1:typeof maybeProjection=="function"&&ALL_DIRECTIONS.indexOf(maybeDirection)!==-1}__name(isSortRule,"isSortRule"),__name2(isSortRule,"isSortRule");var _sortBy=__name2(function(array,sorts){return __spreadArray([],array,!0).sort(comparer.apply(void 0,sorts))},"_sortBy");function comparer(primaryRule,secondaryRule){for(var otherRules=[],_i=2;_i(t3=""+t3,e2=""+e2,s3&&(t3=t3.trim(),e2=e2.trim()),i2?t3==e2:t3.toLowerCase()==e2.toLowerCase()),"s"),a=__name2((t3,e2)=>t3&&Array.isArray(t3)&&t3.map(t4=>n2(t4,e2)),"a");function n2(t3,e2){var i2,s3={};for(i2 in t3)e2.indexOf(i2)<0&&(s3[i2]=t3[i2]);return s3}__name(n2,"n2"),__name2(n2,"n");function o(t3){var e2=document.createElement("div");return t3.replace(/\&#?[0-9a-z]+;/gi,function(t4){return e2.innerHTML=t4,e2.innerText})}__name(o,"o"),__name2(o,"o");function r(t3){return new DOMParser().parseFromString(t3.trim(),"text/html").body.firstElementChild}__name(r,"r"),__name2(r,"r");function l2(t3,e2){for(e2=e2||"previous";t3=t3[e2+"Sibling"];)if(t3.nodeType==3)return t3}__name(l2,"l2"),__name2(l2,"l");function d(t3){return typeof t3=="string"?t3.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/`|'/g,"'"):t3}__name(d,"d"),__name2(d,"d");function h(t3){var e2=Object.prototype.toString.call(t3).split(" ")[1].slice(0,-1);return t3===Object(t3)&&e2!="Array"&&e2!="Function"&&e2!="RegExp"&&e2!="HTMLUnknownElement"}__name(h,"h"),__name2(h,"h");function g(t3,e2,i2){function s3(t4,e3){for(var i3 in e3)if(e3.hasOwnProperty(i3)){if(h(e3[i3])){h(t4[i3])?s3(t4[i3],e3[i3]):t4[i3]=Object.assign({},e3[i3]);continue}if(Array.isArray(e3[i3])){t4[i3]=Object.assign([],e3[i3]);continue}t4[i3]=e3[i3]}}return __name(s3,"s3"),__name2(s3,"s"),t3 instanceof Object||(t3={}),s3(t3,e2),i2&&s3(t3,i2),t3}__name(g,"g"),__name2(g,"g");function p(){const t3=[],e2={};for(let i2 of arguments)for(let s3 of i2)h(s3)?e2[s3.value]||(t3.push(s3),e2[s3.value]=1):t3.includes(s3)||t3.push(s3);return t3}__name(p,"p"),__name2(p,"p");function c(t3){return String.prototype.normalize?typeof t3=="string"?t3.normalize("NFD").replace(/[\u0300-\u036f]/g,""):void 0:t3}__name(c,"c"),__name2(c,"c");var u=__name2(()=>/(?=.*chrome)(?=.*android)/i.test(navigator.userAgent),"u");function m(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,t3=>(t3^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t3/4).toString(16))}__name(m,"m"),__name2(m,"m");function v(t3){return t3&&t3.classList&&t3.classList.contains(this.settings.classNames.tag)}__name(v,"v"),__name2(v,"v");var f={delimiters:",",pattern:null,tagTextProp:"value",maxTags:1/0,callbacks:{},addTagOnBlur:!0,onChangeAfterBlur:!0,duplicates:!1,whitelist:[],blacklist:[],enforceWhitelist:!1,userInput:!0,keepInvalidTags:!1,createInvalidTags:!0,mixTagsAllowedAfter:/,|\.|\:|\s/,mixTagsInterpolator:["[[","]]"],backspace:!0,skipInvalid:!1,pasteAsTags:!0,editTags:{clicks:2,keepInvalid:!0},transformTag:()=>{},trim:!0,a11y:{focusableTags:!1},mixMode:{insertAfterTag:"\xA0"},autoComplete:{enabled:!0,rightKey:!1},classNames:{namespace:"tagify",mixMode:"tagify--mix",selectMode:"tagify--select",input:"tagify__input",focus:"tagify--focus",tagNoAnimation:"tagify--noAnim",tagInvalid:"tagify--invalid",tagNotAllowed:"tagify--notAllowed",scopeLoading:"tagify--loading",hasMaxTags:"tagify--hasMaxTags",hasNoTags:"tagify--noTags",empty:"tagify--empty",inputInvalid:"tagify__input--invalid",dropdown:"tagify__dropdown",dropdownWrapper:"tagify__dropdown__wrapper",dropdownHeader:"tagify__dropdown__header",dropdownFooter:"tagify__dropdown__footer",dropdownItem:"tagify__dropdown__item",dropdownItemActive:"tagify__dropdown__item--active",dropdownItemHidden:"tagify__dropdown__item--hidden",dropdownInital:"tagify__dropdown--initial",tag:"tagify__tag",tagText:"tagify__tag-text",tagX:"tagify__tag__removeBtn",tagLoading:"tagify__tag--loading",tagEditing:"tagify__tag--editable",tagFlash:"tagify__tag--flash",tagHide:"tagify__tag--hide"},dropdown:{classname:"",enabled:2,maxItems:10,searchKeys:["value","searchBy"],fuzzySearch:!0,caseSensitive:!1,accentedSearch:!0,includeSelectedTags:!1,highlightFirst:!1,closeOnSelect:!0,clearOnSelect:!0,position:"all",appendTarget:null},hooks:{beforeRemoveTag:()=>Promise.resolve(),beforePaste:()=>Promise.resolve(),suggestionClick:()=>Promise.resolve()}};function T(){this.dropdown={};for(let t3 in this._dropdown)this.dropdown[t3]=typeof this._dropdown[t3]=="function"?this._dropdown[t3].bind(this):this._dropdown[t3];this.dropdown.refs()}__name(T,"T"),__name2(T,"T");var w={refs(){this.DOM.dropdown=this.parseTemplate("dropdown",[this.settings]),this.DOM.dropdown.content=this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-wrapper']")},getHeaderRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-header']")},getFooterRef(){return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-footer']")},getAllSuggestionsRefs(){return[...this.DOM.dropdown.content.querySelectorAll(this.settings.classNames.dropdownItemSelector)]},show(t3){var e2,i2,a2,n3=this.settings,o2=n3.mode=="mix"&&!n3.enforceWhitelist,r2=!n3.whitelist||!n3.whitelist.length,l3=n3.dropdown.position=="manual";if(t3=t3===void 0?this.state.inputText:t3,!(r2&&!o2&&!n3.templates.dropdownItemNoMatch||n3.dropdown.enable===!1||this.state.isLoading||this.settings.readonly)){if(clearTimeout(this.dropdownHide__bindEventsTimeout),this.suggestedListItems=this.dropdown.filterListItems(t3),t3&&!this.suggestedListItems.length&&(this.trigger("dropdown:noMatch",t3),n3.templates.dropdownItemNoMatch&&(a2=n3.templates.dropdownItemNoMatch.call(this,{value:t3}))),!a2){if(this.suggestedListItems.length)t3&&o2&&!this.state.editing.scope&&!s2(this.suggestedListItems[0].value,t3)&&this.suggestedListItems.unshift({value:t3});else{if(!t3||!o2||this.state.editing.scope)return this.input.autocomplete.suggest.call(this),void this.dropdown.hide();this.suggestedListItems=[{value:t3}]}i2=""+(h(e2=this.suggestedListItems[0])?e2.value:e2),n3.autoComplete&&i2&&i2.indexOf(t3)==0&&this.input.autocomplete.suggest.call(this,e2)}this.dropdown.fill(a2),n3.dropdown.highlightFirst&&this.dropdown.highlightOption(this.DOM.dropdown.content.querySelector(n3.classNames.dropdownItemSelector)),this.state.dropdown.visible||setTimeout(this.dropdown.events.binding.bind(this)),this.state.dropdown.visible=t3||!0,this.state.dropdown.query=t3,this.setStateSelection(),l3||setTimeout(()=>{this.dropdown.position(),this.dropdown.render()}),setTimeout(()=>{this.trigger("dropdown:show",this.DOM.dropdown)})}},hide(t3){var e2=this.DOM,i2=e2.scope,s3=e2.dropdown,a2=this.settings.dropdown.position=="manual"&&!t3;if(s3&&document.body.contains(s3)&&!a2)return window.removeEventListener("resize",this.dropdown.position),this.dropdown.events.binding.call(this,!1),i2.setAttribute("aria-expanded",!1),s3.parentNode.removeChild(s3),setTimeout(()=>{this.state.dropdown.visible=!1},100),this.state.dropdown.query=this.state.ddItemData=this.state.ddItemElm=this.state.selection=null,this.state.tag&&this.state.tag.value.length&&(this.state.flaggedTags[this.state.tag.baseOffset]=this.state.tag),this.trigger("dropdown:hide",s3),this},toggle(t3){this.dropdown[this.state.dropdown.visible&&!t3?"hide":"show"]()},render(){var t3,e2,i2,s3=(t3=this.DOM.dropdown,(i2=t3.cloneNode(!0)).style.cssText="position:fixed; top:-9999px; opacity:0",document.body.appendChild(i2),e2=i2.clientHeight,i2.parentNode.removeChild(i2),e2),a2=this.settings;return typeof a2.dropdown.enabled=="number"&&a2.dropdown.enabled>=0?(this.DOM.scope.setAttribute("aria-expanded",!0),document.body.contains(this.DOM.dropdown)||(this.DOM.dropdown.classList.add(a2.classNames.dropdownInital),this.dropdown.position(s3),a2.dropdown.appendTarget.appendChild(this.DOM.dropdown),setTimeout(()=>this.DOM.dropdown.classList.remove(a2.classNames.dropdownInital))),this):this},fill(t3){t3=typeof t3=="string"?t3:this.dropdown.createListHTML(t3||this.suggestedListItems);var e2,i2=this.settings.templates.dropdownContent.call(this,t3);this.DOM.dropdown.content.innerHTML=(e2=i2)?e2.replace(/\>[\r\n ]+\<").replace(/(<.*?>)|\s+/g,(t4,e3)=>e3||" "):""},fillHeaderFooter(){this.settings.templates;var t3=this.dropdown.filterListItems(this.state.dropdown.query),e2=this.parseTemplate("dropdownHeader",[t3]),i2=this.parseTemplate("dropdownFooter",[t3]),s3=this.dropdown.getHeaderRef(),a2=this.dropdown.getFooterRef();e2&&s3?.parentNode.replaceChild(e2,s3),i2&&a2?.parentNode.replaceChild(i2,a2)},refilter(t3){t3=t3||this.state.dropdown.query||"",this.suggestedListItems=this.dropdown.filterListItems(t3),this.dropdown.fill(),this.suggestedListItems.length||this.dropdown.hide(),this.trigger("dropdown:updated",this.DOM.dropdown)},position(t3){var e2=this.settings.dropdown;if(e2.position!="manual"){var i2,s3,a2,n3,o2,r2,l3=this.DOM.dropdown,d2=e2.placeAbove,h2=e2.appendTarget===document.body,g2=h2?window.pageYOffset:e2.appendTarget.scrollTop,p2=document.fullscreenElement||document.webkitFullscreenElement||document.documentElement,c2=p2.clientHeight,u2=Math.max(p2.clientWidth||0,window.innerWidth||0)>480?e2.position:"all",m2=this.DOM[u2=="input"?"input":"scope"];if(t3=t3||l3.clientHeight,this.state.dropdown.visible){if(u2=="text"?(a2=(i2=this.getCaretGlobalPosition()).bottom,s3=i2.top,n3=i2.left,o2="auto"):(r2=function(t4){for(var e3=0,i3=0;t4&&t4!=p2;)e3+=t4.offsetLeft||0,i3+=t4.offsetTop||0,t4=t4.parentNode;return{left:e3,top:i3}}(e2.appendTarget),s3=(i2=m2.getBoundingClientRect()).top-r2.top,a2=i2.bottom-1-r2.top,n3=i2.left-r2.left,o2=i2.width+"px"),!h2){let t4=function(){for(var t5=0,i3=e2.appendTarget.parentNode;i3;)t5+=i3.scrollTop||0,i3=i3.parentNode;return t5}();s3+=t4,a2+=t4}s3=Math.floor(s3),a2=Math.ceil(a2),d2=d2===void 0?c2-i2.bottom0&&arguments[0]!==void 0)||arguments[0];var e2=this.dropdown.events.callbacks,i2=this.listeners.dropdown=this.listeners.dropdown||{position:this.dropdown.position.bind(this,null),onKeyDown:e2.onKeyDown.bind(this),onMouseOver:e2.onMouseOver.bind(this),onMouseLeave:e2.onMouseLeave.bind(this),onClick:e2.onClick.bind(this),onScroll:e2.onScroll.bind(this)},s3=t3?"addEventListener":"removeEventListener";this.settings.dropdown.position!="manual"&&(document[s3]("scroll",i2.position,!0),window[s3]("resize",i2.position),window[s3]("keydown",i2.onKeyDown)),this.DOM.dropdown[s3]("mouseover",i2.onMouseOver),this.DOM.dropdown[s3]("mouseleave",i2.onMouseLeave),this.DOM.dropdown[s3]("mousedown",i2.onClick),this.DOM.dropdown.content[s3]("scroll",i2.onScroll)},callbacks:{onKeyDown(t3){if(this.state.hasFocus&&!this.state.composing){var e2=this.DOM.dropdown.querySelector(this.settings.classNames.dropdownItemActiveSelector),i2=this.dropdown.getSuggestionDataByNode(e2);switch(t3.key){case"ArrowDown":case"ArrowUp":case"Down":case"Up":t3.preventDefault();var s3=this.dropdown.getAllSuggestionsRefs(),a2=t3.key=="ArrowUp"||t3.key=="Up";e2&&(e2=this.dropdown.getNextOrPrevOption(e2,!a2)),e2&&e2.matches(this.settings.classNames.dropdownItemSelector)||(e2=s3[a2?s3.length-1:0]),i2=this.dropdown.getSuggestionDataByNode(e2),this.dropdown.highlightOption(e2,!0);break;case"Escape":case"Esc":this.dropdown.hide();break;case"ArrowRight":if(this.state.actions.ArrowLeft)return;case"Tab":if(this.settings.mode!="mix"&&e2&&!this.settings.autoComplete.rightKey&&!this.state.editing){t3.preventDefault();var n3=this.dropdown.getMappedValue(i2);return this.input.autocomplete.set.call(this,n3),!1}return!0;case"Enter":t3.preventDefault(),this.settings.hooks.suggestionClick(t3,{tagify:this,tagData:i2,suggestionElm:e2}).then(()=>{if(e2)return this.dropdown.selectOption(e2),e2=this.dropdown.getNextOrPrevOption(e2,!a2),void this.dropdown.highlightOption(e2);this.dropdown.hide(),this.settings.mode!="mix"&&this.addTags(this.state.inputText.trim(),!0)}).catch(t4=>t4);break;case"Backspace":{if(this.settings.mode=="mix"||this.state.editing.scope)return;const t4=this.input.raw.call(this);t4!=""&&t4.charCodeAt(0)!=8203||(this.settings.backspace===!0?this.removeTags():this.settings.backspace=="edit"&&setTimeout(this.editTag.bind(this),0))}}}},onMouseOver(t3){var e2=t3.target.closest(this.settings.classNames.dropdownItemSelector);e2&&this.dropdown.highlightOption(e2)},onMouseLeave(t3){this.dropdown.highlightOption()},onClick(t3){if(t3.button==0&&t3.target!=this.DOM.dropdown&&t3.target!=this.DOM.dropdown.content){var e2=t3.target.closest(this.settings.classNames.dropdownItemSelector),i2=this.dropdown.getSuggestionDataByNode(e2);this.state.actions.selectOption=!0,setTimeout(()=>this.state.actions.selectOption=!1,50),this.settings.hooks.suggestionClick(t3,{tagify:this,tagData:i2,suggestionElm:e2}).then(()=>{e2?this.dropdown.selectOption(e2,t3):this.dropdown.hide()}).catch(t4=>console.warn(t4))}},onScroll(t3){var e2=t3.target,i2=e2.scrollTop/(e2.scrollHeight-e2.parentNode.clientHeight)*100;this.trigger("dropdown:scroll",{percentage:Math.round(i2)})}}},getSuggestionDataByNode(t3){var e2=t3&&t3.getAttribute("value");return this.suggestedListItems.find(t4=>t4.value==e2)||null},getNextOrPrevOption(t3){let e2=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];var i2=this.dropdown.getAllSuggestionsRefs(),s3=i2.findIndex(e3=>e3===t3);return e2?i2[s3+1]:i2[s3-1]},highlightOption(t3,e2){var i2,s3=this.settings.classNames.dropdownItemActive;if(this.state.ddItemElm&&(this.state.ddItemElm.classList.remove(s3),this.state.ddItemElm.removeAttribute("aria-selected")),!t3)return this.state.ddItemData=null,this.state.ddItemElm=null,void this.input.autocomplete.suggest.call(this);i2=this.dropdown.getSuggestionDataByNode(t3),this.state.ddItemData=i2,this.state.ddItemElm=t3,t3.classList.add(s3),t3.setAttribute("aria-selected",!0),e2&&(t3.parentNode.scrollTop=t3.clientHeight+t3.offsetTop-t3.parentNode.clientHeight),this.settings.autoComplete&&(this.input.autocomplete.suggest.call(this,i2),this.dropdown.position())},selectOption(t3,e2){var i2=this.settings.dropdown,s3=i2.clearOnSelect,a2=i2.closeOnSelect;if(!t3)return this.addTags(this.state.inputText,!0),void(a2&&this.dropdown.hide());e2=e2||{};var n3=t3.getAttribute("value"),o2=n3=="noMatch",r2=this.suggestedListItems.find(t4=>(t4.value||t4)==n3);this.trigger("dropdown:select",{data:r2,elm:t3,event:e2}),n3&&(r2||o2)?(this.state.editing?this.onEditTagDone(null,g({__isValid:!0},this.normalizeTags([r2])[0])):this[this.settings.mode=="mix"?"addMixTags":"addTags"]([r2||this.input.raw.call(this)],s3),this.DOM.input.parentNode&&(setTimeout(()=>{this.DOM.input.focus(),this.toggleFocusClass(!0),this.setRangeAtStartEnd(!1)}),a2&&setTimeout(this.dropdown.hide.bind(this)),t3.addEventListener("transitionend",()=>{this.dropdown.fillHeaderFooter(),setTimeout(()=>t3.remove(),100)},{once:!0}),t3.classList.add(this.settings.classNames.dropdownItemHidden))):a2&&setTimeout(this.dropdown.hide.bind(this))},selectAll(t3){this.suggestedListItems.length=0,this.dropdown.hide(),this.dropdown.filterListItems("");var e2=this.dropdown.filterListItems("");return t3||(e2=this.state.dropdown.suggestions),this.addTags(e2,!0),this},filterListItems(t3,e2){var i2,s3,a2,n3,o2,r2=this.settings,l3=r2.dropdown,d2=(e2=e2||{},[]),g2=[],p2=r2.whitelist,u2=l3.maxItems>=0?l3.maxItems:1/0,m2=l3.searchKeys,v2=0;if(!(t3=r2.mode=="select"&&this.value.length&&this.value[0][r2.tagTextProp]==t3?"":t3)||!m2.length)return d2=l3.includeSelectedTags?p2:p2.filter(t4=>!this.isTagDuplicate(h(t4)?t4.value:t4)),this.state.dropdown.suggestions=d2,d2.slice(0,u2);function f2(t4,e3){return e3.toLowerCase().split(" ").every(e4=>t4.includes(e4.toLowerCase()))}for(__name(f2,"f2"),__name2(f2,"f"),o2=l3.caseSensitive?""+t3:(""+t3).toLowerCase();v2m2.includes(t5))?m2:["value"];l3.fuzzySearch&&!e2.exact?(a2=u3.reduce((t5,e3)=>t5+" "+(i2[e3]||""),"").toLowerCase().trim(),l3.accentedSearch&&(a2=c(a2),o2=c(o2)),t4=a2.indexOf(o2)==0,r3=a2===o2,s3=f2(a2,o2)):(t4=!0,s3=u3.some(t5=>{var s4=""+(i2[t5]||"");return l3.accentedSearch&&(s4=c(s4),o2=c(o2)),l3.caseSensitive||(s4=s4.toLowerCase()),r3=s4===o2,e2.exact?s4===o2:s4.indexOf(o2)==0})),n3=!l3.includeSelectedTags&&this.isTagDuplicate(h(i2)?i2.value:i2),s3&&!n3&&(r3&&t4?g2.push(i2):l3.sortby=="startsWith"&&t4?d2.unshift(i2):d2.push(i2))}return this.state.dropdown.suggestions=g2.concat(d2),typeof l3.sortby=="function"?l3.sortby(g2.concat(d2),o2):g2.concat(d2).slice(0,u2)},getMappedValue(t3){var e2=this.settings.dropdown.mapValueTo;return e2?typeof e2=="function"?e2(t3):t3[e2]||t3.value:t3.value},createListHTML(t3){return g([],t3).map((t4,i2)=>{typeof t4!="string"&&typeof t4!="number"||(t4={value:t4});var s3=this.dropdown.getMappedValue(t4);return s3=typeof s3=="string"?d(s3):s3,this.settings.templates.dropdownItem.apply(this,[e(e({},t4),{},{mappedValue:s3}),this])}).join("")}};const b="@yaireo/tagify/";var y,x={empty:"empty",exceed:"number of tags exceeded",pattern:"pattern mismatch",duplicate:"already exists",notAllowed:"not allowed"},D={wrapper:(t3,e2)=>` `,tag(t3,e2){let i2=e2.settings;return`
${t3[i2.tagTextProp]||t3.value}
`},dropdown(t3){var e2=t3.dropdown,i2=e2.position=="manual",s3=`${t3.classNames.dropdown}`;return`
`},dropdownContent(t3){var e2=this.settings,i2=this.state.dropdown.suggestions;return` ${e2.templates.dropdownHeader.call(this,i2)} ${t3} ${e2.templates.dropdownFooter.call(this,i2)} `},dropdownItem(t3){return`
${t3.mappedValue||t3.value}
`},dropdownHeader(t3){return`
`},dropdownFooter(t3){var e2=t3.length-this.settings.dropdown.maxItems;return e2>0?`
${e2} more items. Refine your search.
`:""},dropdownItemNoMatch:null},O={customBinding(){this.customEventsList.forEach(t3=>{this.on(t3,this.settings.callbacks[t3])})},binding(){let t3=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];var e2,i2=this.events.callbacks,s3=t3?"addEventListener":"removeEventListener";if(!this.state.mainEvents||!t3){for(var a2 in this.state.mainEvents=t3,t3&&!this.listeners.main&&(this.events.bindGlobal.call(this),this.settings.isJQueryPlugin&&jQuery(this.DOM.originalInput).on("tagify.removeAllTags",this.removeAllTags.bind(this))),e2=this.listeners.main=this.listeners.main||{focus:["input",i2.onFocusBlur.bind(this)],keydown:["input",i2.onKeydown.bind(this)],click:["scope",i2.onClickScope.bind(this)],dblclick:["scope",i2.onDoubleClickScope.bind(this)],paste:["input",i2.onPaste.bind(this)],drop:["input",i2.onDrop.bind(this)],compositionstart:["input",i2.onCompositionStart.bind(this)],compositionend:["input",i2.onCompositionEnd.bind(this)]})this.DOM[e2[a2][0]][s3](a2,e2[a2][1]);clearInterval(this.listeners.main.originalInputValueObserverInterval),this.listeners.main.originalInputValueObserverInterval=setInterval(i2.observeOriginalInputValue.bind(this),500);var n3=this.listeners.main.inputMutationObserver||new MutationObserver(i2.onInputDOMChange.bind(this));n3&&n3.disconnect(),this.settings.mode=="mix"&&n3.observe(this.DOM.input,{childList:!0})}},bindGlobal(t3){var e2,i2=this.events.callbacks,s3=t3?"removeEventListener":"addEventListener";if(t3||!this.listeners.global)for(e2 of(this.listeners.global=this.listeners&&this.listeners.global||[{type:this.isIE?"keydown":"input",target:this.DOM.input,cb:i2[this.isIE?"onInputIE":"onInput"].bind(this)},{type:"keydown",target:window,cb:i2.onWindowKeyDown.bind(this)},{type:"blur",target:this.DOM.input,cb:i2.onFocusBlur.bind(this)}],this.listeners.global))e2.target[s3](e2.type,e2.cb)},unbindGlobal(){this.events.bindGlobal.call(this,!0)},callbacks:{onFocusBlur(t3){var e2=this.settings,i2=t3.target?this.trim(t3.target.textContent):"",s3=this.value?.[0]?.[e2.tagTextProp],a2=t3.type,n3=e2.dropdown.enabled>=0,o2={relatedTarget:t3.relatedTarget},r2=this.state.actions.selectOption&&(n3||!e2.dropdown.closeOnSelect),l3=this.state.actions.addNew&&n3,d2=t3.relatedTarget&&v.call(this,t3.relatedTarget)&&this.DOM.scope.contains(t3.relatedTarget);if(a2=="blur"){if(t3.relatedTarget===this.DOM.scope)return this.dropdown.hide(),void this.DOM.input.focus();this.postUpdate(),e2.onChangeAfterBlur&&this.triggerChangeEvent()}if(!r2&&!l3)if(this.state.hasFocus=a2=="focus"&&+new Date,this.toggleFocusClass(this.state.hasFocus),e2.mode!="mix"){if(a2=="focus")return this.trigger("focus",o2),void(e2.dropdown.enabled!==0&&e2.userInput||this.dropdown.show(this.value.length?"":void 0));a2=="blur"&&(this.trigger("blur",o2),this.loading(!1),e2.mode=="select"&&(d2&&(this.removeTags(),i2=""),s3===i2&&(i2="")),i2&&!this.state.actions.selectOption&&e2.addTagOnBlur&&this.addTags(i2,!0)),this.DOM.input.removeAttribute("style"),this.dropdown.hide()}else a2=="focus"?this.trigger("focus",o2):t3.type=="blur"&&(this.trigger("blur",o2),this.loading(!1),this.dropdown.hide(),this.state.dropdown.visible=void 0,this.setStateSelection())},onCompositionStart(t3){this.state.composing=!0},onCompositionEnd(t3){this.state.composing=!1},onWindowKeyDown(t3){var e2,i2=document.activeElement;if(v.call(this,i2)&&this.DOM.scope.contains(document.activeElement))switch(e2=i2.nextElementSibling,t3.key){case"Backspace":this.settings.readonly||(this.removeTags(i2),(e2||this.DOM.input).focus());break;case"Enter":setTimeout(this.editTag.bind(this),0,i2)}},onKeydown(t3){var e2=this.settings;if(!this.state.composing&&e2.userInput){e2.mode=="select"&&e2.enforceWhitelist&&this.value.length&&t3.key!="Tab"&&t3.preventDefault();var i2=this.trim(t3.target.textContent);if(this.trigger("keydown",{event:t3}),e2.mode=="mix"){switch(t3.key){case"Left":case"ArrowLeft":this.state.actions.ArrowLeft=!0;break;case"Delete":case"Backspace":if(this.state.editing)return;var s3,a2,n3,r2=document.getSelection(),d2=t3.key=="Delete"&&r2.anchorOffset==(r2.anchorNode.length||0),h2=r2.anchorNode.previousSibling,g2=r2.anchorNode.nodeType==1||!r2.anchorOffset&&h2&&h2.nodeType==1&&r2.anchorNode.previousSibling,p2=o(this.DOM.input.innerHTML),c2=this.getTagElms();if(e2.backspace=="edit"&&g2)return s3=r2.anchorNode.nodeType==1?null:r2.anchorNode.previousElementSibling,setTimeout(this.editTag.bind(this),0,s3),void t3.preventDefault();if(u()&&g2)return n3=l2(g2),g2.hasAttribute("readonly")||g2.remove(),this.DOM.input.focus(),void setTimeout(()=>{this.placeCaretAfterNode(n3),this.DOM.input.click()});if(r2.anchorNode.nodeName=="BR")return;if((d2||g2)&&r2.anchorNode.nodeType==1?a2=r2.anchorOffset==0?d2?c2[0]:null:c2[Math.min(c2.length,r2.anchorOffset)-1]:d2?a2=r2.anchorNode.nextElementSibling:g2&&(a2=g2),r2.anchorNode.nodeType==3&&!r2.anchorNode.nodeValue&&r2.anchorNode.previousElementSibling&&t3.preventDefault(),(g2||d2)&&!e2.backspace||r2.type!="Range"&&!r2.anchorOffset&&r2.anchorNode==this.DOM.input&&t3.key!="Delete")return void t3.preventDefault();if(r2.type!="Range"&&a2&&a2.hasAttribute("readonly"))return void this.placeCaretAfterNode(l2(a2));clearTimeout(y),y=setTimeout(()=>{var t4=document.getSelection(),e3=o(this.DOM.input.innerHTML),i3=!d2&&t4.anchorNode.previousSibling;if(e3.length>=p2.length&&i3)if(v.call(this,i3)&&!i3.hasAttribute("readonly")){if(this.removeTags(i3),this.fixFirefoxLastTagNoCaret(),this.DOM.input.children.length==2&&this.DOM.input.children[1].tagName=="BR")return this.DOM.input.innerHTML="",this.value.length=0,!0}else i3.remove();this.value=[].map.call(c2,(t5,e4)=>{var i4=this.tagData(t5);if(t5.parentNode||i4.readonly)return i4;this.trigger("remove",{tag:t5,index:e4,data:i4})}).filter(t5=>t5)},20)}return!0}switch(t3.key){case"Backspace":e2.mode=="select"&&e2.enforceWhitelist&&this.value.length?this.removeTags():this.state.dropdown.visible&&e2.dropdown.position!="manual"||t3.target.textContent!=""&&i2.charCodeAt(0)!=8203||(e2.backspace===!0?this.removeTags():e2.backspace=="edit"&&setTimeout(this.editTag.bind(this),0));break;case"Esc":case"Escape":if(this.state.dropdown.visible)return;t3.target.blur();break;case"Down":case"ArrowDown":this.state.dropdown.visible||this.dropdown.show();break;case"ArrowRight":{let t4=this.state.inputSuggestion||this.state.ddItemData;if(t4&&e2.autoComplete.rightKey)return void this.addTags([t4],!0);break}case"Tab":{let s4=e2.mode=="select";if(!i2||s4)return!0;t3.preventDefault()}case"Enter":if(this.state.dropdown.visible&&e2.dropdown.position!="manual")return;t3.preventDefault(),setTimeout(()=>{this.state.actions.selectOption||this.addTags(i2,!0)})}}},onInput(t3){this.postUpdate();var e2=this.settings;if(e2.mode=="mix")return this.events.callbacks.onMixTagsInput.call(this,t3);var i2=this.input.normalize.call(this),s3=i2.length>=e2.dropdown.enabled,a2={value:i2,inputElm:this.DOM.input},n3=this.validateTag({value:i2});e2.mode=="select"&&this.toggleScopeValidation(n3),a2.isValid=n3,this.state.inputText!=i2&&(this.input.set.call(this,i2,!1),i2.search(e2.delimiters)!=-1?this.addTags(i2)&&this.input.set.call(this):e2.dropdown.enabled>=0&&this.dropdown[s3?"show":"hide"](i2),this.trigger("input",a2))},onMixTagsInput(t3){var e2,i2,s3,a2,n3,o2,r2,l3,d2=this.settings,h2=this.value.length,p2=this.getTagElms(),c2=document.createDocumentFragment(),m2=window.getSelection().getRangeAt(0),v2=[].map.call(p2,t4=>this.tagData(t4).value);if(t3.inputType=="deleteContentBackward"&&u()&&this.events.callbacks.onKeydown.call(this,{target:t3.target,key:"Backspace"}),this.value.slice().forEach(t4=>{t4.readonly&&!v2.includes(t4.value)&&c2.appendChild(this.createTagElem(t4))}),c2.childNodes.length&&(m2.insertNode(c2),this.setRangeAtStartEnd(!1,c2.lastChild)),p2.length!=h2)return this.value=[].map.call(this.getTagElms(),t4=>this.tagData(t4)),void this.update({withoutChangeEvent:!0});if(this.hasMaxTags())return!0;if(window.getSelection&&(o2=window.getSelection()).rangeCount>0&&o2.anchorNode.nodeType==3){if((m2=o2.getRangeAt(0).cloneRange()).collapse(!0),m2.setStart(o2.focusNode,0),s3=(e2=m2.toString().slice(0,m2.endOffset)).split(d2.pattern).length-1,(i2=e2.match(d2.pattern))&&(a2=e2.slice(e2.lastIndexOf(i2[i2.length-1]))),a2){if(this.state.actions.ArrowLeft=!1,this.state.tag={prefix:a2.match(d2.pattern)[0],value:a2.replace(d2.pattern,"")},this.state.tag.baseOffset=o2.baseOffset-this.state.tag.value.length,l3=this.state.tag.value.match(d2.delimiters))return this.state.tag.value=this.state.tag.value.replace(d2.delimiters,""),this.state.tag.delimiters=l3[0],this.addTags(this.state.tag.value,d2.dropdown.clearOnSelect),void this.dropdown.hide();n3=this.state.tag.value.length>=d2.dropdown.enabled;try{r2=(r2=this.state.flaggedTags[this.state.tag.baseOffset]).prefix==this.state.tag.prefix&&r2.value[0]==this.state.tag.value[0],this.state.flaggedTags[this.state.tag.baseOffset]&&!this.state.tag.value&&delete this.state.flaggedTags[this.state.tag.baseOffset]}catch{}(r2||s3{this.update({withoutChangeEvent:!0}),this.trigger("input",g({},this.state.tag,{textContent:this.DOM.input.textContent})),this.state.tag&&this.dropdown[n3?"show":"hide"](this.state.tag.value)},10)},onInputIE(t3){var e2=this;setTimeout(function(){e2.events.callbacks.onInput.call(e2,t3)})},observeOriginalInputValue(){this.DOM.originalInput.parentNode||this.destroy(),this.DOM.originalInput.value!=this.DOM.originalInput.tagifyValue&&this.loadOriginalValues()},onClickScope(t3){var e2=this.settings,i2=t3.target.closest("."+e2.classNames.tag),s3=+new Date-this.state.hasFocus;if(t3.target!=this.DOM.scope){if(!t3.target.classList.contains(e2.classNames.tagX))return i2?(this.trigger("click",{tag:i2,index:this.getNodeIndex(i2),data:this.tagData(i2),event:t3}),void(e2.editTags!==1&&e2.editTags.clicks!==1||this.events.callbacks.onDoubleClickScope.call(this,t3))):void(t3.target==this.DOM.input&&(e2.mode=="mix"&&this.fixFirefoxLastTagNoCaret(),s3>500)?this.state.dropdown.visible?this.dropdown.hide():e2.dropdown.enabled===0&&e2.mode!="mix"&&this.dropdown.show(this.value.length?"":void 0):e2.mode=="select"&&!this.state.dropdown.visible&&this.dropdown.show());this.removeTags(t3.target.parentNode)}else this.state.hasFocus||this.DOM.input.focus()},onPaste(t3){t3.preventDefault();var e2,i2,s3=this.settings;if(s3.mode=="select"&&s3.enforceWhitelist||!s3.userInput)return!1;s3.readonly||(e2=t3.clipboardData||window.clipboardData,i2=e2.getData("Text"),s3.hooks.beforePaste(t3,{tagify:this,pastedText:i2,clipboardData:e2}).then(e3=>{e3===void 0&&(e3=i2),e3&&(this.injectAtCaret(e3,window.getSelection().getRangeAt(0)),this.settings.mode=="mix"?this.events.callbacks.onMixTagsInput.call(this,t3):this.settings.pasteAsTags?this.addTags(this.state.inputText+e3,!0):this.state.inputText=e3)}).catch(t4=>t4))},onDrop(t3){t3.preventDefault()},onEditTagInput(t3,e2){var i2=t3.closest("."+this.settings.classNames.tag),s3=this.getNodeIndex(i2),a2=this.tagData(i2),n3=this.input.normalize.call(this,t3),o2={[this.settings.tagTextProp]:n3,__tagId:a2.__tagId},r2=this.validateTag(o2);this.editTagChangeDetected(g(a2,o2))||t3.originalIsValid!==!0||(r2=!0),i2.classList.toggle(this.settings.classNames.tagInvalid,r2!==!0),a2.__isValid=r2,i2.title=r2===!0?a2.title||a2.value:r2,n3.length>=this.settings.dropdown.enabled&&(this.state.editing&&(this.state.editing.value=n3),this.dropdown.show(n3)),this.trigger("edit:input",{tag:i2,index:s3,data:g({},this.value[s3],{newValue:n3}),event:e2})},onEditTagFocus(t3){this.state.editing={scope:t3,input:t3.querySelector("[contenteditable]")}},onEditTagBlur(t3){if(this.state.hasFocus||this.toggleFocusClass(),this.DOM.scope.contains(t3)){var e2,i2,s3=this.settings,a2=t3.closest("."+s3.classNames.tag),n3=this.input.normalize.call(this,t3),o2=this.tagData(a2),r2=o2.__originalData,l3=this.editTagChangeDetected(o2),d2=this.validateTag({[s3.tagTextProp]:n3,__tagId:o2.__tagId});if(n3)if(l3){if(e2=this.hasMaxTags(),i2=g({},r2,{[s3.tagTextProp]:this.trim(n3),__isValid:d2}),s3.transformTag.call(this,i2,r2),(d2=(!e2||r2.__isValid===!0)&&this.validateTag(i2))!==!0){if(this.trigger("invalid",{data:i2,tag:a2,message:d2}),s3.editTags.keepInvalid)return;s3.keepInvalidTags?i2.__isValid=d2:i2=r2}else s3.keepInvalidTags&&(delete i2.title,delete i2["aria-invalid"],delete i2.class);this.onEditTagDone(a2,i2)}else this.onEditTagDone(a2,r2);else this.onEditTagDone(a2)}},onEditTagkeydown(t3,e2){if(!this.state.composing)switch(this.trigger("edit:keydown",{event:t3}),t3.key){case"Esc":case"Escape":e2.parentNode.replaceChild(e2.__tagifyTagData.__originalHTML,e2),this.state.editing=!1;case"Enter":case"Tab":t3.preventDefault(),t3.target.blur()}},onDoubleClickScope(t3){var e2,i2,s3=t3.target.closest("."+this.settings.classNames.tag),a2=this.tagData(s3),n3=this.settings;s3&&n3.userInput&&a2.editable!==!1&&(e2=s3.classList.contains(this.settings.classNames.tagEditing),i2=s3.hasAttribute("readonly"),n3.mode=="select"||n3.readonly||e2||i2||!this.settings.editTags||this.editTag(s3),this.toggleFocusClass(!0),this.trigger("dblclick",{tag:s3,index:this.getNodeIndex(s3),data:this.tagData(s3)}))},onInputDOMChange(t3){t3.forEach(t4=>{t4.addedNodes.forEach(t5=>{if(t5.outerHTML=="

")t5.replaceWith(document.createElement("br"));else if(t5.nodeType==1&&t5.querySelector(this.settings.classNames.tagSelector)){let e3=document.createTextNode("");t5.childNodes[0].nodeType==3&&t5.previousSibling.nodeName!="BR"&&(e3=document.createTextNode(` `)),t5.replaceWith(e3,...[...t5.childNodes].slice(0,-1)),this.placeCaretAfterNode(e3)}else if(v.call(this,t5)&&(t5.previousSibling?.nodeType!=3||t5.previousSibling.textContent||t5.previousSibling.remove(),t5.previousSibling&&t5.previousSibling.nodeName=="BR")){t5.previousSibling.replaceWith(` \u200B`);let e3=t5.nextSibling,i2="";for(;e3;)i2+=e3.textContent,e3=e3.nextSibling;i2.trim()&&this.placeCaretAfterNode(t5.previousSibling)}}),t4.removedNodes.forEach(t5=>{t5&&t5.nodeName=="BR"&&v.call(this,e2)&&(this.removeTags(e2),this.fixFirefoxLastTagNoCaret())})});var e2=this.DOM.input.lastChild;e2&&e2.nodeValue==""&&e2.remove(),e2&&e2.nodeName=="BR"||this.DOM.input.appendChild(document.createElement("br"))}}};function M(t3,e2){if(!t3){console.warn("Tagify:","input element not found",t3);const e3=new Proxy(this,{get:()=>()=>e3});return e3}if(t3.__tagify)return console.warn("Tagify: ","input element is already Tagified - Same instance is returned.",t3),t3.__tagify;var i2;g(this,function(t4){var e3=document.createTextNode("");function i3(t5,i4,s3){s3&&i4.split(/\s+/g).forEach(i5=>e3[t5+"EventListener"].call(e3,i5,s3))}return __name(i3,"i3"),__name2(i3,"i"),{off(t5,e4){return i3("remove",t5,e4),this},on(t5,e4){return e4&&typeof e4=="function"&&i3("add",t5,e4),this},trigger(i4,s3,a2){var n3;if(a2=a2||{cloneData:!0},i4)if(t4.settings.isJQueryPlugin)i4=="remove"&&(i4="removeTag"),jQuery(t4.DOM.originalInput).triggerHandler(i4,[s3]);else{try{var o2=typeof s3=="object"?s3:{value:s3};if((o2=a2.cloneData?g({},o2):o2).tagify=this,s3.event&&(o2.event=this.cloneEvent(s3.event)),s3 instanceof Object)for(var r2 in s3)s3[r2]instanceof HTMLElement&&(o2[r2]=s3[r2]);n3=new CustomEvent(i4,{detail:o2})}catch(t5){console.warn(t5)}e3.dispatchEvent(n3)}}}}(this)),this.isFirefox=typeof InstallTrigger<"u",this.isIE=window.document.documentMode,e2=e2||{},this.getPersistedData=(i2=e2.id,t4=>{let e3,s3="/"+t4;if(localStorage.getItem(b+i2+"/v",1)==1)try{e3=JSON.parse(localStorage[b+i2+s3])}catch{}return e3}),this.setPersistedData=(t4=>t4?(localStorage.setItem(b+t4+"/v",1),(e3,i3)=>{let s3="/"+i3,a2=JSON.stringify(e3);e3&&i3&&(localStorage.setItem(b+t4+s3,a2),dispatchEvent(new Event("storage")))}):()=>{})(e2.id),this.clearPersistedData=(t4=>e3=>{const i3=b+"/"+t4+"/";if(e3)localStorage.removeItem(i3+e3);else for(let t5 in localStorage)t5.includes(i3)&&localStorage.removeItem(t5)})(e2.id),this.applySettings(t3,e2),this.state={inputText:"",editing:!1,composing:!1,actions:{},mixMode:{},dropdown:{},flaggedTags:{}},this.value=[],this.listeners={},this.DOM={},this.build(t3),T.call(this),this.getCSSVars(),this.loadOriginalValues(),this.events.customBinding.call(this),this.events.binding.call(this),t3.autofocus&&this.DOM.input.focus(),t3.__tagify=this}return __name(M,"M"),__name2(M,"M"),M.prototype={_dropdown:w,helpers:{sameStr:s2,removeCollectionProp:a,omit:n2,isObject:h,parseHTML:r,escapeHTML:d,extend:g,concatWithoutDups:p,getUID:m,isNodeTag:v},customEventsList:["change","add","remove","invalid","input","click","keydown","focus","blur","edit:input","edit:beforeUpdate","edit:updated","edit:start","edit:keydown","dropdown:show","dropdown:hide","dropdown:select","dropdown:updated","dropdown:noMatch","dropdown:scroll"],dataProps:["__isValid","__removed","__originalData","__originalHTML","__tagId"],trim(t3){return this.settings.trim&&t3&&typeof t3=="string"?t3.trim():t3},parseHTML:r,templates:D,parseTemplate(t3,e2){return t3=this.settings.templates[t3]||t3,this.parseHTML(t3.apply(this,e2))},set whitelist(t3){const e2=t3&&Array.isArray(t3);this.settings.whitelist=e2?t3:[],this.setPersistedData(e2?t3:[],"whitelist")},get whitelist(){return this.settings.whitelist},generateClassSelectors(t3){for(let e2 in t3){let i2=e2;Object.defineProperty(t3,i2+"Selector",{get(){return"."+this[i2].split(" ")[0]}})}},applySettings(t3,i2){f.templates=this.templates;var s3=this.settings=g({},f,i2);if(s3.disabled=t3.hasAttribute("disabled"),s3.readonly=s3.readonly||t3.hasAttribute("readonly"),s3.placeholder=d(t3.getAttribute("placeholder")||s3.placeholder||""),s3.required=t3.hasAttribute("required"),this.generateClassSelectors(s3.classNames),s3.dropdown.includeSelectedTags===void 0&&(s3.dropdown.includeSelectedTags=s3.duplicates),this.isIE&&(s3.autoComplete=!1),["whitelist","blacklist"].forEach(e2=>{var i3=t3.getAttribute("data-"+e2);i3&&(i3=i3.split(s3.delimiters))instanceof Array&&(s3[e2]=i3)}),"autoComplete"in i2&&!h(i2.autoComplete)&&(s3.autoComplete=f.autoComplete,s3.autoComplete.enabled=i2.autoComplete),s3.mode=="mix"&&(s3.autoComplete.rightKey=!0,s3.delimiters=i2.delimiters||null,s3.tagTextProp&&!s3.dropdown.searchKeys.includes(s3.tagTextProp)&&s3.dropdown.searchKeys.push(s3.tagTextProp)),t3.pattern)try{s3.pattern=new RegExp(t3.pattern)}catch{}if(s3.delimiters){s3._delimiters=s3.delimiters;try{s3.delimiters=new RegExp(this.settings.delimiters,"g")}catch{}}s3.disabled&&(s3.userInput=!1),this.TEXTS=e(e({},x),s3.texts||{}),s3.mode!="select"&&s3.userInput||(s3.dropdown.enabled=0),s3.dropdown.appendTarget=i2.dropdown&&i2.dropdown.appendTarget?i2.dropdown.appendTarget:document.body;let a2=this.getPersistedData("whitelist");Array.isArray(a2)&&(this.whitelist=Array.isArray(s3.whitelist)?p(s3.whitelist,a2):a2)},getAttributes(t3){var e2,i2=this.getCustomAttributes(t3),s3="";for(e2 in i2)s3+=" "+e2+(t3[e2]!==void 0?`="${i2[e2]}"`:"");return s3},getCustomAttributes(t3){if(!h(t3))return"";var e2,i2={};for(e2 in t3)e2.slice(0,2)!="__"&&e2!="class"&&t3.hasOwnProperty(e2)&&t3[e2]!==void 0&&(i2[e2]=d(t3[e2]));return i2},setStateSelection(){var t3=window.getSelection(),e2={anchorOffset:t3.anchorOffset,anchorNode:t3.anchorNode,range:t3.getRangeAt&&t3.rangeCount&&t3.getRangeAt(0)};return this.state.selection=e2,e2},getCaretGlobalPosition(){const t3=document.getSelection();if(t3.rangeCount){const e2=t3.getRangeAt(0),i2=e2.startContainer,s3=e2.startOffset;let a2,n3;if(s3>0)return n3=document.createRange(),n3.setStart(i2,s3-1),n3.setEnd(i2,s3),a2=n3.getBoundingClientRect(),{left:a2.right,top:a2.top,bottom:a2.bottom};if(i2.getBoundingClientRect)return i2.getBoundingClientRect()}return{left:-9999,top:-9999}},getCSSVars(){var t3=getComputedStyle(this.DOM.scope,null),e2;this.CSSVars={tagHideTransition:(t4=>{let e3=t4.value;return t4.unit=="s"?1e3*e3:e3})(function(t4){if(!t4)return{};var e3=(t4=t4.trim().split(" ")[0]).split(/\d+/g).filter(t5=>t5).pop().trim();return{value:+t4.split(e3).filter(t5=>t5)[0].trim(),unit:e3}}((e2="tag-hide-transition",t3.getPropertyValue("--"+e2))))}},build(t3){var e2=this.DOM;this.settings.mixMode.integrated?(e2.originalInput=null,e2.scope=t3,e2.input=t3):(e2.originalInput=t3,e2.originalInput_tabIndex=t3.tabIndex,e2.scope=this.parseTemplate("wrapper",[t3,this.settings]),e2.input=e2.scope.querySelector(this.settings.classNames.inputSelector),t3.parentNode.insertBefore(e2.scope,t3),t3.tabIndex=-1)},destroy(){this.events.unbindGlobal.call(this),this.DOM.scope.parentNode.removeChild(this.DOM.scope),this.DOM.originalInput.tabIndex=this.DOM.originalInput_tabIndex,delete this.DOM.originalInput.__tagify,this.dropdown.hide(!0),clearTimeout(this.dropdownHide__bindEventsTimeout),clearInterval(this.listeners.main.originalInputValueObserverInterval)},loadOriginalValues(t3){var e2,i2=this.settings;if(this.state.blockChangeEvent=!0,t3===void 0){const e3=this.getPersistedData("value");t3=e3&&!this.DOM.originalInput.value?e3:i2.mixMode.integrated?this.DOM.input.textContent:this.DOM.originalInput.value}if(this.removeAllTags(),t3)if(i2.mode=="mix")this.parseMixTags(this.trim(t3)),(e2=this.DOM.input.lastChild)&&e2.tagName=="BR"||this.DOM.input.insertAdjacentHTML("beforeend","
");else{try{JSON.parse(t3)instanceof Array&&(t3=JSON.parse(t3))}catch{}this.addTags(t3,!0).forEach(t4=>t4&&t4.classList.add(i2.classNames.tagNoAnimation))}else this.postUpdate();this.state.lastOriginalValueReported=i2.mixMode.integrated?"":this.DOM.originalInput.value,this.state.blockChangeEvent=!1},cloneEvent(t3){var e2={};for(var i2 in t3)i2!="path"&&(e2[i2]=t3[i2]);return e2},loading(t3){return this.state.isLoading=t3,this.DOM.scope.classList[t3?"add":"remove"](this.settings.classNames.scopeLoading),this},tagLoading(t3,e2){return t3&&t3.classList[e2?"add":"remove"](this.settings.classNames.tagLoading),this},toggleClass(t3,e2){typeof t3=="string"&&this.DOM.scope.classList.toggle(t3,e2)},toggleScopeValidation(t3){var e2=t3===!0||t3===void 0;!this.settings.required&&t3&&t3===this.TEXTS.empty&&(e2=!0),this.toggleClass(this.settings.classNames.tagInvalid,!e2),this.DOM.scope.title=e2?"":t3},toggleFocusClass(t3){this.toggleClass(this.settings.classNames.focus,!!t3)},triggerChangeEvent:function(){if(!this.settings.mixMode.integrated){var t3=this.DOM.originalInput,e2=this.state.lastOriginalValueReported!==t3.value,i2=new CustomEvent("change",{bubbles:!0});e2&&(this.state.lastOriginalValueReported=t3.value,i2.simulated=!0,t3._valueTracker&&t3._valueTracker.setValue(Math.random()),t3.dispatchEvent(i2),this.trigger("change",this.state.lastOriginalValueReported),t3.value=this.state.lastOriginalValueReported)}},events:O,fixFirefoxLastTagNoCaret(){},placeCaretAfterNode(t3){if(t3&&t3.parentNode){var e2=t3,i2=window.getSelection(),s3=i2.getRangeAt(0);i2.rangeCount&&(s3.setStartAfter(e2||t3),s3.collapse(!0),i2.removeAllRanges(),i2.addRange(s3))}},insertAfterTag(t3,e2){if(e2=e2||this.settings.mixMode.insertAfterTag,t3&&t3.parentNode&&e2)return e2=typeof e2=="string"?document.createTextNode(e2):e2,t3.parentNode.insertBefore(e2,t3.nextSibling),e2},editTagChangeDetected(t3){var e2=t3.__originalData;for(var i2 in e2)if(!this.dataProps.includes(i2)&&t3[i2]!=e2[i2])return!0;return!1},getTagTextNode(t3){return t3.querySelector(this.settings.classNames.tagTextSelector)},setTagTextNode(t3,e2){this.getTagTextNode(t3).innerHTML=d(e2)},editTag(t3,e2){t3=t3||this.getLastTag(),e2=e2||{},this.dropdown.hide();var i2=this.settings,s3=this.getTagTextNode(t3),a2=this.getNodeIndex(t3),n3=this.tagData(t3),o2=this.events.callbacks,r2=this,l3=!0;if(s3){if(!(n3 instanceof Object&&"editable"in n3)||n3.editable)return n3=this.tagData(t3,{__originalData:g({},n3),__originalHTML:t3.cloneNode(!0)}),this.tagData(n3.__originalHTML,n3.__originalData),s3.setAttribute("contenteditable",!0),t3.classList.add(i2.classNames.tagEditing),s3.addEventListener("focus",o2.onEditTagFocus.bind(this,t3)),s3.addEventListener("blur",function(){setTimeout(()=>o2.onEditTagBlur.call(r2,r2.getTagTextNode(t3)))}),s3.addEventListener("input",o2.onEditTagInput.bind(this,s3)),s3.addEventListener("keydown",e3=>o2.onEditTagkeydown.call(this,e3,t3)),s3.addEventListener("compositionstart",o2.onCompositionStart.bind(this)),s3.addEventListener("compositionend",o2.onCompositionEnd.bind(this)),e2.skipValidation||(l3=this.editTagToggleValidity(t3)),s3.originalIsValid=l3,this.trigger("edit:start",{tag:t3,index:a2,data:n3,isValid:l3}),s3.focus(),this.setRangeAtStartEnd(!1,s3),this}else console.warn("Cannot find element in Tag template: .",i2.classNames.tagTextSelector)},editTagToggleValidity(t3,e2){var i2;if(e2=e2||this.tagData(t3))return(i2=!("__isValid"in e2)||e2.__isValid===!0)||this.removeTagsFromValue(t3),this.update(),t3.classList.toggle(this.settings.classNames.tagNotAllowed,!i2),e2.__isValid;console.warn("tag has no data: ",t3,e2)},onEditTagDone(t3,e2){e2=e2||{};var i2={tag:t3=t3||this.state.editing.scope,index:this.getNodeIndex(t3),previousData:this.tagData(t3),data:e2};this.trigger("edit:beforeUpdate",i2,{cloneData:!1}),this.state.editing=!1,delete e2.__originalData,delete e2.__originalHTML,t3&&e2[this.settings.tagTextProp]?(t3=this.replaceTag(t3,e2),this.editTagToggleValidity(t3,e2),this.settings.a11y.focusableTags?t3.focus():this.placeCaretAfterNode(t3)):t3&&this.removeTags(t3),this.trigger("edit:updated",i2),this.dropdown.hide(),this.settings.keepInvalidTags&&this.reCheckInvalidTags()},replaceTag(t3,e2){e2&&e2.value||(e2=t3.__tagifyTagData),e2.__isValid&&e2.__isValid!=1&&g(e2,this.getInvalidTagAttrs(e2,e2.__isValid));var i2=this.createTagElem(e2);return t3.parentNode.replaceChild(i2,t3),this.updateValueByDOMTags(),i2},updateValueByDOMTags(){this.value.length=0,[].forEach.call(this.getTagElms(),t3=>{t3.classList.contains(this.settings.classNames.tagNotAllowed.split(" ")[0])||this.value.push(this.tagData(t3))}),this.update()},setRangeAtStartEnd(t3,e2){t3=typeof t3=="number"?t3:!!t3,e2=(e2=e2||this.DOM.input).lastChild||e2;var i2=document.getSelection();try{i2.rangeCount>=1&&["Start","End"].forEach(s3=>i2.getRangeAt(0)["set"+s3](e2,t3||e2.length))}catch{}},injectAtCaret(t3,e2){return!(e2=e2||this.state.selection?.range)&&t3?(this.appendMixTags(t3),this):(typeof t3=="string"&&(t3=document.createTextNode(t3)),e2.deleteContents(),e2.insertNode(t3),this.setRangeAtStartEnd(!1,t3),this.updateValueByDOMTags(),this.update(),this)},input:{set(){let t3=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",e2=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];var i2=this.settings.dropdown.closeOnSelect;this.state.inputText=t3,e2&&(this.DOM.input.innerHTML=d(""+t3)),!t3&&i2&&this.dropdown.hide.bind(this),this.input.autocomplete.suggest.call(this),this.input.validate.call(this)},raw(){return this.DOM.input.textContent},validate(){var t3=!this.state.inputText||this.validateTag({value:this.state.inputText})===!0;return this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid,!t3),t3},normalize(t3){var e2=t3||this.DOM.input,i2=[];e2.childNodes.forEach(t4=>t4.nodeType==3&&i2.push(t4.nodeValue)),i2=i2.join(` `);try{i2=i2.replace(/(?:\r\n|\r|\n)/g,this.settings.delimiters.source.charAt(0))}catch{}return i2=i2.replace(/\s/g," "),this.trim(i2)},autocomplete:{suggest(t3){if(this.settings.autoComplete.enabled){typeof(t3=t3||{})=="string"&&(t3={value:t3});var e2=t3.value?""+t3.value:"",i2=e2.substr(0,this.state.inputText.length).toLowerCase(),s3=e2.substring(this.state.inputText.length);e2&&this.state.inputText&&i2==this.state.inputText.toLowerCase()?(this.DOM.input.setAttribute("data-suggest",s3),this.state.inputSuggestion=t3):(this.DOM.input.removeAttribute("data-suggest"),delete this.state.inputSuggestion)}},set(t3){var e2=this.DOM.input.getAttribute("data-suggest"),i2=t3||(e2?this.state.inputText+e2:null);return!!i2&&(this.settings.mode=="mix"?this.replaceTextWithNode(document.createTextNode(this.state.tag.prefix+i2)):(this.input.set.call(this,i2),this.setRangeAtStartEnd()),this.input.autocomplete.suggest.call(this),this.dropdown.hide(),!0)}}},getTagIdx(t3){return this.value.findIndex(e2=>e2.__tagId==(t3||{}).__tagId)},getNodeIndex(t3){var e2=0;if(t3)for(;t3=t3.previousElementSibling;)e2++;return e2},getTagElms(){for(var t3=arguments.length,e2=new Array(t3),i2=0;i2t3?(e2&&(t3.__tagifyTagData=i2?e2:g({},t3.__tagifyTagData||{},e2)),t3.__tagifyTagData):(console.warn("tag element doesn't exist",t3,e2),e2),isTagDuplicate(t3,e2,i2){var a2=0;if(this.settings.mode=="select")return!1;for(let n3 of this.value)s2(this.trim(""+t3),n3.value,e2)&&i2!=n3.__tagId&&a2++;return a2},getTagIndexByValue(t3){var e2=[];return this.getTagElms().forEach((i2,a2)=>{s2(this.trim(i2.textContent),t3,this.settings.dropdown.caseSensitive)&&e2.push(a2)}),e2},getTagElmByValue(t3){var e2=this.getTagIndexByValue(t3)[0];return this.getTagElms()[e2]},flashTag(t3){t3&&(t3.classList.add(this.settings.classNames.tagFlash),setTimeout(()=>{t3.classList.remove(this.settings.classNames.tagFlash)},100))},isTagBlacklisted(t3){return t3=this.trim(t3.toLowerCase()),this.settings.blacklist.filter(e2=>(""+e2).toLowerCase()==t3).length},isTagWhitelisted(t3){return!!this.getWhitelistItem(t3)},getWhitelistItem(t3,e2,i2){e2=e2||"value";var a2,n3=this.settings;return(i2=i2||n3.whitelist).some(i3=>{var o2=typeof i3=="string"?i3:i3[e2]||i3.value;if(s2(o2,t3,n3.dropdown.caseSensitive,n3.trim))return a2=typeof i3=="string"?{value:i3}:i3,!0}),a2||e2!="value"||n3.tagTextProp=="value"||(a2=this.getWhitelistItem(t3,n3.tagTextProp,i2)),a2},validateTag(t3){var e2=this.settings,i2="value"in t3?"value":e2.tagTextProp,s3=this.trim(t3[i2]+"");return(t3[i2]+"").trim()?e2.pattern&&e2.pattern instanceof RegExp&&!e2.pattern.test(s3)?this.TEXTS.pattern:!e2.duplicates&&this.isTagDuplicate(s3,e2.dropdown.caseSensitive,t3.__tagId)?this.TEXTS.duplicate:this.isTagBlacklisted(s3)||e2.enforceWhitelist&&!this.isTagWhitelisted(s3)?this.TEXTS.notAllowed:!e2.validate||e2.validate(t3):this.TEXTS.empty},getInvalidTagAttrs(t3,e2){return{"aria-invalid":!0,class:`${t3.class||""} ${this.settings.classNames.tagNotAllowed}`.trim(),title:e2}},hasMaxTags(){return this.value.length>=this.settings.maxTags&&this.TEXTS.exceed},setReadonly(t3,e2){var i2=this.settings;document.activeElement.blur(),i2[e2||"readonly"]=t3,this.DOM.scope[(t3?"set":"remove")+"Attribute"](e2||"readonly",!0),this.setContentEditable(!t3)},setContentEditable(t3){this.settings.userInput&&(this.DOM.input.contentEditable=t3,this.DOM.input.tabIndex=t3?0:-1)},setDisabled(t3){this.setReadonly(t3,"disabled")},normalizeTags(t3){var e2=this.settings,i2=e2.whitelist,s3=e2.delimiters,a2=e2.mode,n3=e2.tagTextProp;e2.enforceWhitelist;var o2=[],r2=!!i2&&i2[0]instanceof Object,l3=Array.isArray(t3),d2=l3&&t3[0].value,h2=__name2(t4=>(t4+"").split(s3).filter(t5=>t5).map(t5=>({[n3]:this.trim(t5),value:this.trim(t5)})),"h");if(typeof t3=="number"&&(t3=t3.toString()),typeof t3=="string"){if(!t3.trim())return[];t3=h2(t3)}else l3&&(t3=[].concat(...t3.map(t4=>t4.value?t4:h2(t4))));return r2&&!d2&&(t3.forEach(t4=>{var e3=o2.map(t5=>t5.value),i3=this.dropdown.filterListItems.call(this,t4[n3],{exact:!0});this.settings.duplicates||(i3=i3.filter(t5=>!e3.includes(t5.value)));var s4=i3.length>1?this.getWhitelistItem(t4[n3],n3,i3):i3[0];s4&&s4 instanceof Object?o2.push(s4):a2!="mix"&&(t4.value==null&&(t4.value=t4[n3]),o2.push(t4))}),o2.length&&(t3=o2)),t3},parseMixTags(t3){var e2=this.settings,i2=e2.mixTagsInterpolator,s3=e2.duplicates,a2=e2.transformTag,n3=e2.enforceWhitelist,o2=e2.maxTags,r2=e2.tagTextProp,l3=[];return t3=t3.split(i2[0]).map((t4,e3)=>{var d2,h2,g2,p2=t4.split(i2[1]),c2=p2[0],u2=l3.length==o2;try{if(c2==+c2)throw Error;h2=JSON.parse(c2)}catch{h2=this.normalizeTags(c2)[0]||{value:c2}}if(a2.call(this,h2),u2||!(p2.length>1)||n3&&!this.isTagWhitelisted(h2.value)||!s3&&this.isTagDuplicate(h2.value)){if(t4)return e3?i2[0]+t4:t4}else h2[d2=h2[r2]?r2:"value"]=this.trim(h2[d2]),g2=this.createTagElem(h2),l3.push(h2),g2.classList.add(this.settings.classNames.tagNoAnimation),p2[0]=g2.outerHTML,this.value.push(h2);return p2.join("")}).join(""),this.DOM.input.innerHTML=t3,this.DOM.input.appendChild(document.createTextNode("")),this.DOM.input.normalize(),this.getTagElms().forEach((t4,e3)=>this.tagData(t4,l3[e3])),this.update({withoutChangeEvent:!0}),t3},replaceTextWithNode(t3,e2){if(this.state.tag||e2){e2=e2||this.state.tag.prefix+this.state.tag.value;var i2,s3,a2=this.state.selection||window.getSelection(),n3=a2.anchorNode,o2=this.state.tag.delimiters?this.state.tag.delimiters.length:0;return n3.splitText(a2.anchorOffset-o2),(i2=n3.nodeValue.lastIndexOf(e2))==-1||(s3=n3.splitText(i2),t3&&n3.parentNode.replaceChild(t3,s3)),!0}},selectTag(t3,e2){var i2=this.settings;if(!i2.enforceWhitelist||this.isTagWhitelisted(e2.value)){this.input.set.call(this,e2[i2.tagTextProp]||e2.value,!0),this.state.actions.selectOption&&setTimeout(this.setRangeAtStartEnd.bind(this));var s3=this.getLastTag();return s3?this.replaceTag(s3,e2):this.appendTag(t3),this.value[0]=e2,this.update(),this.trigger("add",{tag:t3,data:e2}),[t3]}},addEmptyTag(t3){var e2=g({value:""},t3||{}),i2=this.createTagElem(e2);this.tagData(i2,e2),this.appendTag(i2),this.editTag(i2,{skipValidation:!0})},addTags(t3,e2,i2){var s3=[],a2=this.settings,n3=[],o2=document.createDocumentFragment();if(i2=i2||a2.skipInvalid,!t3||t3.length==0)return s3;switch(t3=this.normalizeTags(t3),a2.mode){case"mix":return this.addMixTags(t3);case"select":e2=!1,this.removeAllTags()}return this.DOM.input.removeAttribute("style"),t3.forEach(t4=>{var e3,r2={},l3=Object.assign({},t4,{value:t4.value+""});if(t4=Object.assign({},l3),a2.transformTag.call(this,t4),t4.__isValid=this.hasMaxTags()||this.validateTag(t4),t4.__isValid!==!0){if(i2)return;if(g(r2,this.getInvalidTagAttrs(t4,t4.__isValid),{__preInvalidData:l3}),t4.__isValid==this.TEXTS.duplicate&&this.flashTag(this.getTagElmByValue(t4.value)),!a2.createInvalidTags)return void n3.push(t4.value)}if("readonly"in t4&&(t4.readonly?r2["aria-readonly"]=!0:delete t4.readonly),e3=this.createTagElem(t4,r2),s3.push(e3),a2.mode=="select")return this.selectTag(e3,t4);o2.appendChild(e3),t4.__isValid&&t4.__isValid===!0?(this.value.push(t4),this.trigger("add",{tag:e3,index:this.value.length-1,data:t4})):(this.trigger("invalid",{data:t4,index:this.value.length,tag:e3,message:t4.__isValid}),a2.keepInvalidTags||setTimeout(()=>this.removeTags(e3,!0),1e3)),this.dropdown.position()}),this.appendTag(o2),this.update(),t3.length&&e2&&(this.input.set.call(this,a2.createInvalidTags?"":n3.join(a2._delimiters)),this.setRangeAtStartEnd()),a2.dropdown.enabled&&this.dropdown.refilter(),s3},addMixTags(t3){if((t3=this.normalizeTags(t3))[0].prefix||this.state.tag)return this.prefixedTextToTag(t3[0]);typeof t3=="string"&&(t3=[{value:t3}]),this.state.selection;var e2=document.createDocumentFragment();return t3.forEach(t4=>{var i2=this.createTagElem(t4);e2.appendChild(i2),this.insertAfterTag(i2)}),this.appendMixTags(e2),e2},appendMixTags(t3){var e2=!!this.state.selection;e2?this.injectAtCaret(t3):(this.DOM.input.focus(),(e2=this.setStateSelection()).range.setStart(this.DOM.input,e2.range.endOffset),e2.range.setEnd(this.DOM.input,e2.range.endOffset),this.DOM.input.appendChild(t3),this.updateValueByDOMTags(),this.update())},prefixedTextToTag(t3){var e2,i2=this.settings,s3=this.state.tag.delimiters;if(i2.transformTag.call(this,t3),t3.prefix=t3.prefix||this.state.tag?this.state.tag.prefix:(i2.pattern.source||i2.pattern)[0],e2=this.createTagElem(t3),this.replaceTextWithNode(e2)||this.DOM.input.appendChild(e2),setTimeout(()=>e2.classList.add(this.settings.classNames.tagNoAnimation),300),this.value.push(t3),this.update(),!s3){var a2=this.insertAfterTag(e2)||e2;this.placeCaretAfterNode(a2)}return this.state.tag=null,this.trigger("add",g({},{tag:e2},{data:t3})),e2},appendTag(t3){var e2=this.DOM,i2=e2.input;i2===e2.input?e2.scope.insertBefore(t3,i2):e2.scope.appendChild(t3)},createTagElem(t3,i2){t3.__tagId=m();var s3,a2=g({},t3,e({value:d(t3.value+"")},i2));return function(t4){for(var e2,i3=document.createNodeIterator(t4,NodeFilter.SHOW_TEXT,null,!1);e2=i3.nextNode();)e2.textContent.trim()||e2.parentNode.removeChild(e2)}(s3=this.parseTemplate("tag",[a2,this])),this.tagData(s3,t3),s3},reCheckInvalidTags(){var t3=this.settings;this.getTagElms(t3.classNames.tagNotAllowed).forEach((e2,i2)=>{var s3=this.tagData(e2),a2=this.hasMaxTags(),n3=this.validateTag(s3),o2=n3===!0&&!a2;if(t3.mode=="select"&&this.toggleScopeValidation(n3),o2)return s3=s3.__preInvalidData?s3.__preInvalidData:{value:s3.value},this.replaceTag(e2,s3);e2.title=a2||n3})},removeTags(t3,e2,i2){var s3,a2=this.settings;if(t3=t3&&t3 instanceof HTMLElement?[t3]:t3 instanceof Array?t3:t3?[t3]:[this.getLastTag()],s3=t3.reduce((t4,e3)=>{e3&&typeof e3=="string"&&(e3=this.getTagElmByValue(e3));var i3=this.tagData(e3);return e3&&i3&&!i3.readonly&&t4.push({node:e3,idx:this.getTagIdx(i3),data:this.tagData(e3,{__removed:!0})}),t4},[]),i2=typeof i2=="number"?i2:this.CSSVars.tagHideTransition,a2.mode=="select"&&(i2=0,this.input.set.call(this)),s3.length==1&&a2.mode!="select"&&s3[0].node.classList.contains(a2.classNames.tagNotAllowed)&&(e2=!0),s3.length)return a2.hooks.beforeRemoveTag(s3,{tagify:this}).then(()=>{function t4(t5){t5.node.parentNode&&(t5.node.parentNode.removeChild(t5.node),e2?a2.keepInvalidTags&&this.trigger("remove",{tag:t5.node,index:t5.idx}):(this.trigger("remove",{tag:t5.node,index:t5.idx,data:t5.data}),this.dropdown.refilter(),this.dropdown.position(),this.DOM.input.normalize(),a2.keepInvalidTags&&this.reCheckInvalidTags()))}__name(t4,"t4"),__name2(t4,"t"),i2&&i2>10&&s3.length==1?function(e3){e3.node.style.width=parseFloat(window.getComputedStyle(e3.node).width)+"px",document.body.clientTop,e3.node.classList.add(a2.classNames.tagHide),setTimeout(t4.bind(this),i2,e3)}.call(this,s3[0]):s3.forEach(t4.bind(this)),e2||(this.removeTagsFromValue(s3.map(t5=>t5.node)),this.update(),a2.mode=="select"&&this.setContentEditable(!0))}).catch(t4=>{})},removeTagsFromDOM(){[].slice.call(this.getTagElms()).forEach(t3=>t3.parentNode.removeChild(t3))},removeTagsFromValue(t3){(t3=Array.isArray(t3)?t3:[t3]).forEach(t4=>{var e2=this.tagData(t4),i2=this.getTagIdx(e2);i2>-1&&this.value.splice(i2,1)})},removeAllTags(t3){t3=t3||{},this.value=[],this.settings.mode=="mix"?this.DOM.input.innerHTML="":this.removeTagsFromDOM(),this.dropdown.refilter(),this.dropdown.position(),this.state.dropdown.visible&&setTimeout(()=>{this.DOM.input.focus()}),this.settings.mode=="select"&&(this.input.set.call(this),this.setContentEditable(!0)),this.update(t3)},postUpdate(){var t3=this.settings,e2=t3.classNames,i2=t3.mode=="mix"?t3.mixMode.integrated?this.DOM.input.textContent:this.DOM.originalInput.value.trim():this.value.length+this.input.raw.call(this).length;this.toggleClass(e2.hasMaxTags,this.value.length>=t3.maxTags),this.toggleClass(e2.hasNoTags,!this.value.length),this.toggleClass(e2.empty,!i2),t3.mode=="select"&&this.toggleScopeValidation(this.value?.[0]?.__isValid)},setOriginalInputValue(t3){var e2=this.DOM.originalInput;this.settings.mixMode.integrated||(e2.value=t3,e2.tagifyValue=e2.value,this.setPersistedData(t3,"value"))},update(t3){var e2=this.getInputValue();this.setOriginalInputValue(e2),this.postUpdate(),this.settings.onChangeAfterBlur&&(t3||{}).withoutChangeEvent||this.state.blockChangeEvent||this.triggerChangeEvent()},getInputValue(){var t3=this.getCleanValue();return this.settings.mode=="mix"?this.getMixedTagsAsString(t3):t3.length?this.settings.originalInputValueFormat?this.settings.originalInputValueFormat(t3):JSON.stringify(t3):""},getCleanValue(t3){return a(t3||this.value,this.dataProps)},getMixedTagsAsString(){var t3="",e2=this,i2=this.settings,s3=i2.originalInputValueFormat||JSON.stringify,a2=i2.mixTagsInterpolator;return __name2(__name(function i3(o2){o2.childNodes.forEach(o3=>{if(o3.nodeType==1){const r2=e2.tagData(o3);if(o3.tagName=="BR"&&(t3+=`\r `),r2&&v.call(e2,o3)){if(r2.__removed)return;t3+=a2[0]+s3(n2(r2,e2.dataProps))+a2[1]}else o3.getAttribute("style")||["B","I","U"].includes(o3.tagName)?t3+=o3.textContent:o3.tagName!="DIV"&&o3.tagName!="P"||(t3+=`\r `,i3(o3))}else t3+=o3.textContent})},"i3"),"i")(this.DOM.input),t3}},M.prototype.removeTag=M.prototype.removeTags,M})})(tagify_min);var tagify_minExports=tagify_min.exports;const Tagify=getDefaultExportFromCjs(tagify_minExports);/**! * Sortable 1.15.0 * @author RubaXa * @author owenm * @license MIT */function ownKeys(object,enumerableOnly){var keys2=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys2.push.apply(keys2,symbols)}return keys2}__name(ownKeys,"ownKeys"),__name2(ownKeys,"ownKeys");function _objectSpread2(target){for(var i=1;i=0)&&(target[key]=source[key]);return target}__name(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose"),__name2(_objectWithoutPropertiesLoose,"_objectWithoutPropertiesLoose");function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded),key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}__name(_objectWithoutProperties,"_objectWithoutProperties"),__name2(_objectWithoutProperties,"_objectWithoutProperties");var version="1.15.0";function userAgent(pattern){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(pattern)}__name(userAgent,"userAgent"),__name2(userAgent,"userAgent");var IE11OrLess=userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Edge=userAgent(/Edge/i),FireFox=userAgent(/firefox/i),Safari=userAgent(/safari/i)&&!userAgent(/chrome/i)&&!userAgent(/android/i),IOS=userAgent(/iP(ad|od|hone)/i),ChromeForAndroid=userAgent(/chrome/i)&&userAgent(/android/i),captureMode={capture:!1,passive:!1};function on(el,event,fn){el.addEventListener(event,fn,!IE11OrLess&&captureMode)}__name(on,"on"),__name2(on,"on");function off(el,event,fn){el.removeEventListener(event,fn,!IE11OrLess&&captureMode)}__name(off,"off"),__name2(off,"off");function matches(el,selector){if(selector){if(selector[0]===">"&&(selector=selector.substring(1)),el)try{if(el.matches)return el.matches(selector);if(el.msMatchesSelector)return el.msMatchesSelector(selector);if(el.webkitMatchesSelector)return el.webkitMatchesSelector(selector)}catch{return!1}return!1}}__name(matches,"matches"),__name2(matches,"matches");function getParentOrHost(el){return el.host&&el!==document&&el.host.nodeType?el.host:el.parentNode}__name(getParentOrHost,"getParentOrHost"),__name2(getParentOrHost,"getParentOrHost");function closest$1(el,selector,ctx,includeCTX){if(el){ctx=ctx||document;do{if(selector!=null&&(selector[0]===">"?el.parentNode===ctx&&matches(el,selector):matches(el,selector))||includeCTX&&el===ctx)return el;if(el===ctx)break}while(el=getParentOrHost(el))}return null}__name(closest$1,"closest$1"),__name2(closest$1,"closest$1");var R_SPACE=/\s+/g;function toggleClass(el,name2,state){if(el&&name2)if(el.classList)el.classList[state?"add":"remove"](name2);else{var className=(" "+el.className+" ").replace(R_SPACE," ").replace(" "+name2+" "," ");el.className=(className+(state?" "+name2:"")).replace(R_SPACE," ")}}__name(toggleClass,"toggleClass"),__name2(toggleClass,"toggleClass");function css(el,prop,val){var style=el&&el.style;if(style){if(val===void 0)return document.defaultView&&document.defaultView.getComputedStyle?val=document.defaultView.getComputedStyle(el,""):el.currentStyle&&(val=el.currentStyle),prop===void 0?val:val[prop];!(prop in style)&&prop.indexOf("webkit")===-1&&(prop="-webkit-"+prop),style[prop]=val+(typeof val=="string"?"":"px")}}__name(css,"css"),__name2(css,"css");function matrix(el,selfOnly){var appliedTransforms="";if(typeof el=="string")appliedTransforms=el;else do{var transform=css(el,"transform");transform&&transform!=="none"&&(appliedTransforms=transform+" "+appliedTransforms)}while(!selfOnly&&(el=el.parentNode));var matrixFn=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return matrixFn&&new matrixFn(appliedTransforms)}__name(matrix,"matrix"),__name2(matrix,"matrix");function find$1(ctx,tagName,iterator){if(ctx){var list=ctx.getElementsByTagName(tagName),i=0,n2=list.length;if(iterator)for(;i=parentSideVal:visible=elSideVal<=parentSideVal,!visible)return parent;if(parent===getWindowScrollingElement())break;parent=getParentAutoScrollElement(parent,!1)}return!1}__name(isScrolledPast,"isScrolledPast"),__name2(isScrolledPast,"isScrolledPast");function getChild(el,childNum,options,includeDragEl){for(var currentChild=0,i=0,children=el.children;i2&&arguments[2]!==void 0?arguments[2]:{},originalEvent=_ref.evt,data=_objectWithoutProperties(_ref,_excluded);PluginManager.pluginEvent.bind(Sortable)(eventName,sortable,_objectSpread2({dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,dragStarted:moved,putSortable,activeSortable:Sortable.active,originalEvent,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex,hideGhostForTarget:_hideGhostForTarget,unhideGhostForTarget:_unhideGhostForTarget,cloneNowHidden:__name2(__name(function(){cloneHidden=!0},"cloneNowHidden"),"cloneNowHidden"),cloneNowShown:__name2(__name(function(){cloneHidden=!1},"cloneNowShown"),"cloneNowShown"),dispatchSortableEvent:__name2(__name(function(name2){_dispatchEvent({sortable,name:name2,originalEvent})},"dispatchSortableEvent"),"dispatchSortableEvent")},data))},"pluginEvent3"),"pluginEvent");function _dispatchEvent(info){dispatchEvent$1(_objectSpread2({putSortable,cloneEl,targetEl:dragEl,rootEl,oldIndex,oldDraggableIndex,newIndex,newDraggableIndex},info))}__name(_dispatchEvent,"_dispatchEvent"),__name2(_dispatchEvent,"_dispatchEvent");var dragEl,parentEl,ghostEl,rootEl,nextEl,lastDownEl,cloneEl,cloneHidden,oldIndex,newIndex,oldDraggableIndex,newDraggableIndex,activeGroup,putSortable,awaitingDragStarted=!1,ignoreNextClick=!1,sortables=[],tapEvt,touchEvt,lastDx,lastDy,tapDistanceLeft,tapDistanceTop,moved,lastTarget,lastDirection,pastFirstInvertThresh=!1,isCircumstantialInvert=!1,targetMoveDistance,ghostRelativeParent,ghostRelativeParentInitialScroll=[],_silent=!1,savedInputChecked=[],documentExists=typeof document<"u",PositionGhostAbsolutely=IOS,CSSFloatProperty=Edge||IE11OrLess?"cssFloat":"float",supportDraggable=documentExists&&!ChromeForAndroid&&!IOS&&"draggable"in document.createElement("div"),supportCssPointerEvents=function(){if(documentExists){if(IE11OrLess)return!1;var el=document.createElement("x");return el.style.cssText="pointer-events:auto",el.style.pointerEvents==="auto"}}(),_detectDirection=__name2(__name(function(el,options){var elCSS=css(el),elWidth=parseInt(elCSS.width)-parseInt(elCSS.paddingLeft)-parseInt(elCSS.paddingRight)-parseInt(elCSS.borderLeftWidth)-parseInt(elCSS.borderRightWidth),child1=getChild(el,0,options),child2=getChild(el,1,options),firstChildCSS=child1&&css(child1),secondChildCSS=child2&&css(child2),firstChildWidth=firstChildCSS&&parseInt(firstChildCSS.marginLeft)+parseInt(firstChildCSS.marginRight)+getRect(child1).width,secondChildWidth=secondChildCSS&&parseInt(secondChildCSS.marginLeft)+parseInt(secondChildCSS.marginRight)+getRect(child2).width;if(elCSS.display==="flex")return elCSS.flexDirection==="column"||elCSS.flexDirection==="column-reverse"?"vertical":"horizontal";if(elCSS.display==="grid")return elCSS.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(child1&&firstChildCSS.float&&firstChildCSS.float!=="none"){var touchingSideChild2=firstChildCSS.float==="left"?"left":"right";return child2&&(secondChildCSS.clear==="both"||secondChildCSS.clear===touchingSideChild2)?"vertical":"horizontal"}return child1&&(firstChildCSS.display==="block"||firstChildCSS.display==="flex"||firstChildCSS.display==="table"||firstChildCSS.display==="grid"||firstChildWidth>=elWidth&&elCSS[CSSFloatProperty]==="none"||child2&&elCSS[CSSFloatProperty]==="none"&&firstChildWidth+secondChildWidth>elWidth)?"vertical":"horizontal"},"_detectDirection2"),"_detectDirection"),_dragElInRowColumn=__name2(__name(function(dragRect,targetRect,vertical){var dragElS1Opp=vertical?dragRect.left:dragRect.top,dragElS2Opp=vertical?dragRect.right:dragRect.bottom,dragElOppLength=vertical?dragRect.width:dragRect.height,targetS1Opp=vertical?targetRect.left:targetRect.top,targetS2Opp=vertical?targetRect.right:targetRect.bottom,targetOppLength=vertical?targetRect.width:targetRect.height;return dragElS1Opp===targetS1Opp||dragElS2Opp===targetS2Opp||dragElS1Opp+dragElOppLength/2===targetS1Opp+targetOppLength/2},"_dragElInRowColumn2"),"_dragElInRowColumn"),_detectNearestEmptySortable=__name2(__name(function(x,y){var ret;return sortables.some(function(sortable){var threshold=sortable[expando].options.emptyInsertThreshold;if(!(!threshold||lastChild(sortable))){var rect=getRect(sortable),insideHorizontally=x>=rect.left-threshold&&x<=rect.right+threshold,insideVertically=y>=rect.top-threshold&&y<=rect.bottom+threshold;if(insideHorizontally&&insideVertically)return ret=sortable}}),ret},"_detectNearestEmptySortable2"),"_detectNearestEmptySortable"),_prepareGroup=__name2(__name(function(options){function toFn(value,pull){return function(to,from,dragEl2,evt){var sameGroup=to.options.group.name&&from.options.group.name&&to.options.group.name===from.options.group.name;if(value==null&&(pull||sameGroup))return!0;if(value==null||value===!1)return!1;if(pull&&value==="clone")return value;if(typeof value=="function")return toFn(value(to,from,dragEl2,evt),pull)(to,from,dragEl2,evt);var otherGroup=(pull?to:from).options.group.name;return value===!0||typeof value=="string"&&value===otherGroup||value.join&&value.indexOf(otherGroup)>-1}}__name(toFn,"toFn"),__name2(toFn,"toFn");var group={},originalGroup=options.group;(!originalGroup||_typeof(originalGroup)!="object")&&(originalGroup={name:originalGroup}),group.name=originalGroup.name,group.checkPull=toFn(originalGroup.pull,!0),group.checkPut=toFn(originalGroup.put),group.revertClone=originalGroup.revertClone,options.group=group},"_prepareGroup2"),"_prepareGroup"),_hideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","none")},"_hideGhostForTarget2"),"_hideGhostForTarget"),_unhideGhostForTarget=__name2(__name(function(){!supportCssPointerEvents&&ghostEl&&css(ghostEl,"display","")},"_unhideGhostForTarget2"),"_unhideGhostForTarget");documentExists&&!ChromeForAndroid&&document.addEventListener("click",function(evt){if(ignoreNextClick)return evt.preventDefault(),evt.stopPropagation&&evt.stopPropagation(),evt.stopImmediatePropagation&&evt.stopImmediatePropagation(),ignoreNextClick=!1,!1},!0);var nearestEmptyInsertDetectEvent=__name2(__name(function(evt){if(dragEl){evt=evt.touches?evt.touches[0]:evt;var nearest=_detectNearestEmptySortable(evt.clientX,evt.clientY);if(nearest){var event={};for(var i in evt)evt.hasOwnProperty(i)&&(event[i]=evt[i]);event.target=event.rootEl=nearest,event.preventDefault=void 0,event.stopPropagation=void 0,nearest[expando]._onDragOver(event)}}},"nearestEmptyInsertDetectEvent2"),"nearestEmptyInsertDetectEvent"),_checkOutsideTargetEl=__name2(__name(function(evt){dragEl&&dragEl.parentNode[expando]._isOutsideThisEl(evt.target)},"_checkOutsideTargetEl2"),"_checkOutsideTargetEl");function Sortable(el,options){if(!(el&&el.nodeType&&el.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));this.el=el,this.options=options=_extends({},options),el[expando]=this;var defaults2={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(el.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:__name2(__name(function(){return _detectDirection(el,this.options)},"direction"),"direction"),ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:__name2(__name(function(dataTransfer,dragEl2){dataTransfer.setData("Text",dragEl2.textContent)},"setData"),"setData"),dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Sortable.supportPointer!==!1&&"PointerEvent"in window&&!Safari,emptyInsertThreshold:5};PluginManager.initializePlugins(this,el,defaults2);for(var name2 in defaults2)!(name2 in options)&&(options[name2]=defaults2[name2]);_prepareGroup(options);for(var fn in this)fn.charAt(0)==="_"&&typeof this[fn]=="function"&&(this[fn]=this[fn].bind(this));this.nativeDraggable=options.forceFallback?!1:supportDraggable,this.nativeDraggable&&(this.options.touchStartThreshold=1),options.supportPointer?on(el,"pointerdown",this._onTapStart):(on(el,"mousedown",this._onTapStart),on(el,"touchstart",this._onTapStart)),this.nativeDraggable&&(on(el,"dragover",this),on(el,"dragenter",this)),sortables.push(this.el),options.store&&options.store.get&&this.sort(options.store.get(this)||[]),_extends(this,AnimationStateManager())}__name(Sortable,"Sortable"),__name2(Sortable,"Sortable"),Sortable.prototype={constructor:Sortable,_isOutsideThisEl:__name2(__name(function(target){!this.el.contains(target)&&target!==this.el&&(lastTarget=null)},"_isOutsideThisEl"),"_isOutsideThisEl"),_getDirection:__name2(__name(function(evt,target){return typeof this.options.direction=="function"?this.options.direction.call(this,evt,target,dragEl):this.options.direction},"_getDirection"),"_getDirection"),_onTapStart:__name2(__name(function(evt){if(evt.cancelable){var _this=this,el=this.el,options=this.options,preventOnFilter=options.preventOnFilter,type=evt.type,touch=evt.touches&&evt.touches[0]||evt.pointerType&&evt.pointerType==="touch"&&evt,target=(touch||evt).target,originalTarget=evt.target.shadowRoot&&(evt.path&&evt.path[0]||evt.composedPath&&evt.composedPath()[0])||target,filter2=options.filter;if(_saveInputCheckedState(el),!dragEl&&!(/mousedown|pointerdown/.test(type)&&evt.button!==0||options.disabled)&&!originalTarget.isContentEditable&&!(!this.nativeDraggable&&Safari&&target&&target.tagName.toUpperCase()==="SELECT")&&(target=closest$1(target,options.draggable,el,!1),!(target&&target.animated)&&lastDownEl!==target)){if(oldIndex=index(target),oldDraggableIndex=index(target,options.draggable),typeof filter2=="function"){if(filter2.call(this,evt,target,this)){_dispatchEvent({sortable:_this,rootEl:originalTarget,name:"filter",targetEl:target,toEl:el,fromEl:el}),pluginEvent2("filter",_this,{evt}),preventOnFilter&&evt.cancelable&&evt.preventDefault();return}}else if(filter2&&(filter2=filter2.split(",").some(function(criteria){if(criteria=closest$1(originalTarget,criteria.trim(),el,!1),criteria)return _dispatchEvent({sortable:_this,rootEl:criteria,name:"filter",targetEl:target,fromEl:el,toEl:el}),pluginEvent2("filter",_this,{evt}),!0}),filter2)){preventOnFilter&&evt.cancelable&&evt.preventDefault();return}options.handle&&!closest$1(originalTarget,options.handle,el,!1)||this._prepareDragStart(evt,touch,target)}}},"_onTapStart"),"_onTapStart"),_prepareDragStart:__name2(__name(function(evt,touch,target){var _this=this,el=_this.el,options=_this.options,ownerDocument=el.ownerDocument,dragStartFn;if(target&&!dragEl&&target.parentNode===el){var dragRect=getRect(target);if(rootEl=el,dragEl=target,parentEl=dragEl.parentNode,nextEl=dragEl.nextSibling,lastDownEl=target,activeGroup=options.group,Sortable.dragged=dragEl,tapEvt={target:dragEl,clientX:(touch||evt).clientX,clientY:(touch||evt).clientY},tapDistanceLeft=tapEvt.clientX-dragRect.left,tapDistanceTop=tapEvt.clientY-dragRect.top,this._lastX=(touch||evt).clientX,this._lastY=(touch||evt).clientY,dragEl.style["will-change"]="all",dragStartFn=__name2(__name(function(){if(pluginEvent2("delayEnded",_this,{evt}),Sortable.eventCanceled){_this._onDrop();return}_this._disableDelayedDragEvents(),!FireFox&&_this.nativeDraggable&&(dragEl.draggable=!0),_this._triggerDragStart(evt,touch),_dispatchEvent({sortable:_this,name:"choose",originalEvent:evt}),toggleClass(dragEl,options.chosenClass,!0)},"dragStartFn2"),"dragStartFn"),options.ignore.split(",").forEach(function(criteria){find$1(dragEl,criteria.trim(),_disableDraggable)}),on(ownerDocument,"dragover",nearestEmptyInsertDetectEvent),on(ownerDocument,"mousemove",nearestEmptyInsertDetectEvent),on(ownerDocument,"touchmove",nearestEmptyInsertDetectEvent),on(ownerDocument,"mouseup",_this._onDrop),on(ownerDocument,"touchend",_this._onDrop),on(ownerDocument,"touchcancel",_this._onDrop),FireFox&&this.nativeDraggable&&(this.options.touchStartThreshold=4,dragEl.draggable=!0),pluginEvent2("delayStart",this,{evt}),options.delay&&(!options.delayOnTouchOnly||touch)&&(!this.nativeDraggable||!(Edge||IE11OrLess))){if(Sortable.eventCanceled){this._onDrop();return}on(ownerDocument,"mouseup",_this._disableDelayedDrag),on(ownerDocument,"touchend",_this._disableDelayedDrag),on(ownerDocument,"touchcancel",_this._disableDelayedDrag),on(ownerDocument,"mousemove",_this._delayedDragTouchMoveHandler),on(ownerDocument,"touchmove",_this._delayedDragTouchMoveHandler),options.supportPointer&&on(ownerDocument,"pointermove",_this._delayedDragTouchMoveHandler),_this._dragStartTimer=setTimeout(dragStartFn,options.delay)}else dragStartFn()}},"_prepareDragStart"),"_prepareDragStart"),_delayedDragTouchMoveHandler:__name2(__name(function(e){var touch=e.touches?e.touches[0]:e;Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},"_delayedDragTouchMoveHandler"),"_delayedDragTouchMoveHandler"),_disableDelayedDrag:__name2(__name(function(){dragEl&&_disableDraggable(dragEl),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},"_disableDelayedDrag"),"_disableDelayedDrag"),_disableDelayedDragEvents:__name2(__name(function(){var ownerDocument=this.el.ownerDocument;off(ownerDocument,"mouseup",this._disableDelayedDrag),off(ownerDocument,"touchend",this._disableDelayedDrag),off(ownerDocument,"touchcancel",this._disableDelayedDrag),off(ownerDocument,"mousemove",this._delayedDragTouchMoveHandler),off(ownerDocument,"touchmove",this._delayedDragTouchMoveHandler),off(ownerDocument,"pointermove",this._delayedDragTouchMoveHandler)},"_disableDelayedDragEvents"),"_disableDelayedDragEvents"),_triggerDragStart:__name2(__name(function(evt,touch){touch=touch||evt.pointerType=="touch"&&evt,!this.nativeDraggable||touch?this.options.supportPointer?on(document,"pointermove",this._onTouchMove):touch?on(document,"touchmove",this._onTouchMove):on(document,"mousemove",this._onTouchMove):(on(dragEl,"dragend",this),on(rootEl,"dragstart",this._onDragStart));try{document.selection?_nextTick(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},"_triggerDragStart"),"_triggerDragStart"),_dragStarted:__name2(__name(function(fallback,evt){if(awaitingDragStarted=!1,rootEl&&dragEl){pluginEvent2("dragStarted",this,{evt}),this.nativeDraggable&&on(document,"dragover",_checkOutsideTargetEl);var options=this.options;!fallback&&toggleClass(dragEl,options.dragClass,!1),toggleClass(dragEl,options.ghostClass,!0),Sortable.active=this,fallback&&this._appendGhost(),_dispatchEvent({sortable:this,name:"start",originalEvent:evt})}else this._nulling()},"_dragStarted"),"_dragStarted"),_emulateDragOver:__name2(__name(function(){if(touchEvt){this._lastX=touchEvt.clientX,this._lastY=touchEvt.clientY,_hideGhostForTarget();for(var target=document.elementFromPoint(touchEvt.clientX,touchEvt.clientY),parent=target;target&&target.shadowRoot&&(target=target.shadowRoot.elementFromPoint(touchEvt.clientX,touchEvt.clientY),target!==parent);)parent=target;if(dragEl.parentNode[expando]._isOutsideThisEl(target),parent)do{if(parent[expando]){var inserted=void 0;if(inserted=parent[expando]._onDragOver({clientX:touchEvt.clientX,clientY:touchEvt.clientY,target,rootEl:parent}),inserted&&!this.options.dragoverBubble)break}target=parent}while(parent=parent.parentNode);_unhideGhostForTarget()}},"_emulateDragOver"),"_emulateDragOver"),_onTouchMove:__name2(__name(function(evt){if(tapEvt){var options=this.options,fallbackTolerance=options.fallbackTolerance,fallbackOffset=options.fallbackOffset,touch=evt.touches?evt.touches[0]:evt,ghostMatrix=ghostEl&&matrix(ghostEl,!0),scaleX=ghostEl&&ghostMatrix&&ghostMatrix.a,scaleY=ghostEl&&ghostMatrix&&ghostMatrix.d,relativeScrollOffset=PositionGhostAbsolutely&&ghostRelativeParent&&getRelativeScrollOffset(ghostRelativeParent),dx=(touch.clientX-tapEvt.clientX+fallbackOffset.x)/(scaleX||1)+(relativeScrollOffset?relativeScrollOffset[0]-ghostRelativeParentInitialScroll[0]:0)/(scaleX||1),dy=(touch.clientY-tapEvt.clientY+fallbackOffset.y)/(scaleY||1)+(relativeScrollOffset?relativeScrollOffset[1]-ghostRelativeParentInitialScroll[1]:0)/(scaleY||1);if(!Sortable.active&&!awaitingDragStarted){if(fallbackTolerance&&Math.max(Math.abs(touch.clientX-this._lastX),Math.abs(touch.clientY-this._lastY))=0&&(_dispatchEvent({rootEl:parentEl,name:"add",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"remove",toEl:parentEl,originalEvent:evt}),_dispatchEvent({rootEl:parentEl,name:"sort",toEl:parentEl,fromEl:rootEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),putSortable&&putSortable.save()):newIndex!==oldIndex&&newIndex>=0&&(_dispatchEvent({sortable:this,name:"update",toEl:parentEl,originalEvent:evt}),_dispatchEvent({sortable:this,name:"sort",toEl:parentEl,originalEvent:evt})),Sortable.active&&((newIndex==null||newIndex===-1)&&(newIndex=oldIndex,newDraggableIndex=oldDraggableIndex),_dispatchEvent({sortable:this,name:"end",toEl:parentEl,originalEvent:evt}),this.save()))),this._nulling()},"_onDrop"),"_onDrop"),_nulling:__name2(__name(function(){pluginEvent2("nulling",this),rootEl=dragEl=parentEl=ghostEl=nextEl=cloneEl=lastDownEl=cloneHidden=tapEvt=touchEvt=moved=newIndex=newDraggableIndex=oldIndex=oldDraggableIndex=lastTarget=lastDirection=putSortable=activeGroup=Sortable.dragged=Sortable.ghost=Sortable.clone=Sortable.active=null,savedInputChecked.forEach(function(el){el.checked=!0}),savedInputChecked.length=lastDx=lastDy=0},"_nulling"),"_nulling"),handleEvent:__name2(__name(function(evt){switch(evt.type){case"drop":case"dragend":this._onDrop(evt);break;case"dragenter":case"dragover":dragEl&&(this._onDragOver(evt),_globalDragOver(evt));break;case"selectstart":evt.preventDefault();break}},"handleEvent"),"handleEvent"),toArray:__name2(__name(function(){for(var order=[],el,children=this.el.children,i=0,n2=children.length,options=this.options;irect.right+spacer||evt.clientX<=rect.right&&evt.clientY>rect.bottom&&evt.clientX>=rect.left:evt.clientX>rect.right&&evt.clientY>rect.top||evt.clientX<=rect.right&&evt.clientY>rect.bottom+spacer}__name(_ghostIsLast,"_ghostIsLast"),__name2(_ghostIsLast,"_ghostIsLast");function _getSwapDirection(evt,target,targetRect,vertical,swapThreshold,invertedSwapThreshold,invertSwap,isLastTarget){var mouseOnAxis=vertical?evt.clientY:evt.clientX,targetLength=vertical?targetRect.height:targetRect.width,targetS1=vertical?targetRect.top:targetRect.left,targetS2=vertical?targetRect.bottom:targetRect.right,invert=!1;if(!invertSwap){if(isLastTarget&&targetMoveDistancetargetS1+targetLength*invertedSwapThreshold/2:mouseOnAxistargetS2-targetMoveDistance)return-lastDirection}else if(mouseOnAxis>targetS1+targetLength*(1-swapThreshold)/2&&mouseOnAxistargetS2-targetLength*invertedSwapThreshold/2)?mouseOnAxis>targetS1+targetLength/2?1:-1:0}__name(_getSwapDirection,"_getSwapDirection"),__name2(_getSwapDirection,"_getSwapDirection");function _getInsertDirection(target){return index(dragEl)=0?over:1e3+over,(asUTC-asTS)/(60*1e3)}equals(otherZone){return otherZone.type==="iana"&&otherZone.name===this.name}get isValid(){return this.valid}};__name2(_IANAZone,"IANAZone");let IANAZone=_IANAZone,intlLFCache={};function getCachedLF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlLFCache[key];return dtf||(dtf=new Intl.ListFormat(locString,opts),intlLFCache[key]=dtf),dtf}__name(getCachedLF,"getCachedLF"),__name2(getCachedLF,"getCachedLF");let intlDTCache={};function getCachedDTF(locString,opts={}){const key=JSON.stringify([locString,opts]);let dtf=intlDTCache[key];return dtf||(dtf=new Intl.DateTimeFormat(locString,opts),intlDTCache[key]=dtf),dtf}__name(getCachedDTF,"getCachedDTF"),__name2(getCachedDTF,"getCachedDTF");let intlNumCache={};function getCachedINF(locString,opts={}){const key=JSON.stringify([locString,opts]);let inf=intlNumCache[key];return inf||(inf=new Intl.NumberFormat(locString,opts),intlNumCache[key]=inf),inf}__name(getCachedINF,"getCachedINF"),__name2(getCachedINF,"getCachedINF");let intlRelCache={};function getCachedRTF(locString,opts={}){const{base:base2,...cacheKeyOpts}=opts,key=JSON.stringify([locString,cacheKeyOpts]);let inf=intlRelCache[key];return inf||(inf=new Intl.RelativeTimeFormat(locString,opts),intlRelCache[key]=inf),inf}__name(getCachedRTF,"getCachedRTF"),__name2(getCachedRTF,"getCachedRTF");let sysLocaleCache=null;function systemLocale(){return sysLocaleCache||(sysLocaleCache=new Intl.DateTimeFormat().resolvedOptions().locale,sysLocaleCache)}__name(systemLocale,"systemLocale"),__name2(systemLocale,"systemLocale");function parseLocaleString(localeStr){const xIndex=localeStr.indexOf("-x-");xIndex!==-1&&(localeStr=localeStr.substring(0,xIndex));const uIndex=localeStr.indexOf("-u-");if(uIndex===-1)return[localeStr];{let options,selectedStr;try{options=getCachedDTF(localeStr).resolvedOptions(),selectedStr=localeStr}catch{const smaller=localeStr.substring(0,uIndex);options=getCachedDTF(smaller).resolvedOptions(),selectedStr=smaller}const{numberingSystem,calendar}=options;return[selectedStr,numberingSystem,calendar]}}__name(parseLocaleString,"parseLocaleString"),__name2(parseLocaleString,"parseLocaleString");function intlConfigString(localeStr,numberingSystem,outputCalendar){return(outputCalendar||numberingSystem)&&(localeStr.includes("-u-")||(localeStr+="-u"),outputCalendar&&(localeStr+=`-ca-${outputCalendar}`),numberingSystem&&(localeStr+=`-nu-${numberingSystem}`)),localeStr}__name(intlConfigString,"intlConfigString"),__name2(intlConfigString,"intlConfigString");function mapMonths(f){const ms=[];for(let i=1;i<=12;i++){const dt=DateTime.utc(2009,i,1);ms.push(f(dt))}return ms}__name(mapMonths,"mapMonths"),__name2(mapMonths,"mapMonths");function mapWeekdays(f){const ms=[];for(let i=1;i<=7;i++){const dt=DateTime.utc(2016,11,13+i);ms.push(f(dt))}return ms}__name(mapWeekdays,"mapWeekdays"),__name2(mapWeekdays,"mapWeekdays");function listStuff(loc,length,englishFn,intlFn){const mode=loc.listingMode();return mode==="error"?null:mode==="en"?englishFn(length):intlFn(length)}__name(listStuff,"listStuff"),__name2(listStuff,"listStuff");function supportsFastNumbers(loc){return loc.numberingSystem&&loc.numberingSystem!=="latn"?!1:loc.numberingSystem==="latn"||!loc.locale||loc.locale.startsWith("en")||new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem==="latn"}__name(supportsFastNumbers,"supportsFastNumbers"),__name2(supportsFastNumbers,"supportsFastNumbers");const _PolyNumberFormatter=class{static{__name(this,"_PolyNumberFormatter")}constructor(intl,forceSimple,opts){this.padTo=opts.padTo||0,this.floor=opts.floor||!1;const{padTo,floor,...otherOpts}=opts;if(!forceSimple||Object.keys(otherOpts).length>0){const intlOpts={useGrouping:!1,...opts};opts.padTo>0&&(intlOpts.minimumIntegerDigits=opts.padTo),this.inf=getCachedINF(intl,intlOpts)}}format(i){if(this.inf){const fixed=this.floor?Math.floor(i):i;return this.inf.format(fixed)}else{const fixed=this.floor?Math.floor(i):roundTo(i,3);return padStart(fixed,this.padTo)}}};__name2(_PolyNumberFormatter,"PolyNumberFormatter");let PolyNumberFormatter=_PolyNumberFormatter;const _PolyDateFormatter=class{static{__name(this,"_PolyDateFormatter")}constructor(dt,intl,opts){this.opts=opts,this.originalZone=void 0;let z;if(this.opts.timeZone)this.dt=dt;else if(dt.zone.type==="fixed"){const gmtOffset=-1*(dt.offset/60),offsetZ=gmtOffset>=0?`Etc/GMT+${gmtOffset}`:`Etc/GMT${gmtOffset}`;dt.offset!==0&&IANAZone.create(offsetZ).valid?(z=offsetZ,this.dt=dt):(z="UTC",this.dt=dt.offset===0?dt:dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone)}else dt.zone.type==="system"?this.dt=dt:dt.zone.type==="iana"?(this.dt=dt,z=dt.zone.name):(z="UTC",this.dt=dt.setZone("UTC").plus({minutes:dt.offset}),this.originalZone=dt.zone);const intlOpts={...this.opts};intlOpts.timeZone=intlOpts.timeZone||z,this.dtf=getCachedDTF(intl,intlOpts)}format(){return this.originalZone?this.formatToParts().map(({value})=>value).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const parts=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?parts.map(part=>{if(part.type==="timeZoneName"){const offsetName=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...part,value:offsetName}}else return part}):parts}resolvedOptions(){return this.dtf.resolvedOptions()}};__name2(_PolyDateFormatter,"PolyDateFormatter");let PolyDateFormatter=_PolyDateFormatter;const _PolyRelFormatter=class{static{__name(this,"_PolyRelFormatter")}constructor(intl,isEnglish,opts){this.opts={style:"long",...opts},!isEnglish&&hasRelative()&&(this.rtf=getCachedRTF(intl,opts))}format(count,unit){return this.rtf?this.rtf.format(count,unit):formatRelativeTime(unit,count,this.opts.numeric,this.opts.style!=="long")}formatToParts(count,unit){return this.rtf?this.rtf.formatToParts(count,unit):[]}};__name2(_PolyRelFormatter,"PolyRelFormatter");let PolyRelFormatter=_PolyRelFormatter;const _Locale=class _Locale2{static{__name(this,"_Locale")}static fromOpts(opts){return _Locale2.create(opts.locale,opts.numberingSystem,opts.outputCalendar,opts.defaultToEN)}static create(locale,numberingSystem,outputCalendar,defaultToEN=!1){const specifiedLocale=locale||Settings.defaultLocale,localeR=specifiedLocale||(defaultToEN?"en-US":systemLocale()),numberingSystemR=numberingSystem||Settings.defaultNumberingSystem,outputCalendarR=outputCalendar||Settings.defaultOutputCalendar;return new _Locale2(localeR,numberingSystemR,outputCalendarR,specifiedLocale)}static resetCache(){sysLocaleCache=null,intlDTCache={},intlNumCache={},intlRelCache={}}static fromObject({locale,numberingSystem,outputCalendar}={}){return _Locale2.create(locale,numberingSystem,outputCalendar)}constructor(locale,numbering,outputCalendar,specifiedLocale){const[parsedLocale,parsedNumberingSystem,parsedOutputCalendar]=parseLocaleString(locale);this.locale=parsedLocale,this.numberingSystem=numbering||parsedNumberingSystem||null,this.outputCalendar=outputCalendar||parsedOutputCalendar||null,this.intl=intlConfigString(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=specifiedLocale,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=supportsFastNumbers(this)),this.fastNumbersCached}listingMode(){const isActuallyEn=this.isEnglish(),hasNoWeirdness=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return isActuallyEn&&hasNoWeirdness?"en":"intl"}clone(alts){return!alts||Object.getOwnPropertyNames(alts).length===0?this:_Locale2.create(alts.locale||this.specifiedLocale,alts.numberingSystem||this.numberingSystem,alts.outputCalendar||this.outputCalendar,alts.defaultToEN||!1)}redefaultToEN(alts={}){return this.clone({...alts,defaultToEN:!0})}redefaultToSystem(alts={}){return this.clone({...alts,defaultToEN:!1})}months(length,format=!1){return listStuff(this,length,months,()=>{const intl=format?{month:length,day:"numeric"}:{month:length},formatStr=format?"format":"standalone";return this.monthsCache[formatStr][length]||(this.monthsCache[formatStr][length]=mapMonths(dt=>this.extract(dt,intl,"month"))),this.monthsCache[formatStr][length]})}weekdays(length,format=!1){return listStuff(this,length,weekdays,()=>{const intl=format?{weekday:length,year:"numeric",month:"long",day:"numeric"}:{weekday:length},formatStr=format?"format":"standalone";return this.weekdaysCache[formatStr][length]||(this.weekdaysCache[formatStr][length]=mapWeekdays(dt=>this.extract(dt,intl,"weekday"))),this.weekdaysCache[formatStr][length]})}meridiems(){return listStuff(this,void 0,()=>meridiems,()=>{if(!this.meridiemCache){const intl={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[DateTime.utc(2016,11,13,9),DateTime.utc(2016,11,13,19)].map(dt=>this.extract(dt,intl,"dayperiod"))}return this.meridiemCache})}eras(length){return listStuff(this,length,eras,()=>{const intl={era:length};return this.eraCache[length]||(this.eraCache[length]=[DateTime.utc(-40,1,1),DateTime.utc(2017,1,1)].map(dt=>this.extract(dt,intl,"era"))),this.eraCache[length]})}extract(dt,intlOpts,field){const df=this.dtFormatter(dt,intlOpts),results=df.formatToParts(),matching=results.find(m=>m.type.toLowerCase()===field);return matching?matching.value:null}numberFormatter(opts={}){return new PolyNumberFormatter(this.intl,opts.forceSimple||this.fastNumbers,opts)}dtFormatter(dt,intlOpts={}){return new PolyDateFormatter(dt,this.intl,intlOpts)}relFormatter(opts={}){return new PolyRelFormatter(this.intl,this.isEnglish(),opts)}listFormatter(opts={}){return getCachedLF(this.intl,opts)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(other){return this.locale===other.locale&&this.numberingSystem===other.numberingSystem&&this.outputCalendar===other.outputCalendar}};__name2(_Locale,"Locale");let Locale=_Locale,singleton=null;const _FixedOffsetZone=class _FixedOffsetZone2 extends Zone{static{__name(this,"_FixedOffsetZone")}static get utcInstance(){return singleton===null&&(singleton=new _FixedOffsetZone2(0)),singleton}static instance(offset2){return offset2===0?_FixedOffsetZone2.utcInstance:new _FixedOffsetZone2(offset2)}static parseSpecifier(s2){if(s2){const r=s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new _FixedOffsetZone2(signedOffset(r[1],r[2]))}return null}constructor(offset2){super(),this.fixed=offset2}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${formatOffset(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${formatOffset(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(ts,format){return formatOffset(this.fixed,format)}get isUniversal(){return!0}offset(){return this.fixed}equals(otherZone){return otherZone.type==="fixed"&&otherZone.fixed===this.fixed}get isValid(){return!0}};__name2(_FixedOffsetZone,"FixedOffsetZone");let FixedOffsetZone=_FixedOffsetZone;const _InvalidZone=class extends Zone{static{__name(this,"_InvalidZone")}constructor(zoneName){super(),this.zoneName=zoneName}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};__name2(_InvalidZone,"InvalidZone");let InvalidZone=_InvalidZone;function normalizeZone(input,defaultZone2){if(isUndefined(input)||input===null)return defaultZone2;if(input instanceof Zone)return input;if(isString(input)){const lowered=input.toLowerCase();return lowered==="default"?defaultZone2:lowered==="local"||lowered==="system"?SystemZone.instance:lowered==="utc"||lowered==="gmt"?FixedOffsetZone.utcInstance:FixedOffsetZone.parseSpecifier(lowered)||IANAZone.create(input)}else return isNumber(input)?FixedOffsetZone.instance(input):typeof input=="object"&&"offset"in input&&typeof input.offset=="function"?input:new InvalidZone(input)}__name(normalizeZone,"normalizeZone"),__name2(normalizeZone,"normalizeZone");let now=__name2(()=>Date.now(),"now"),defaultZone="system",defaultLocale=null,defaultNumberingSystem=null,defaultOutputCalendar=null,twoDigitCutoffYear=60,throwOnInvalid;const _Settings=class{static{__name(this,"_Settings")}static get now(){return now}static set now(n2){now=n2}static set defaultZone(zone){defaultZone=zone}static get defaultZone(){return normalizeZone(defaultZone,SystemZone.instance)}static get defaultLocale(){return defaultLocale}static set defaultLocale(locale){defaultLocale=locale}static get defaultNumberingSystem(){return defaultNumberingSystem}static set defaultNumberingSystem(numberingSystem){defaultNumberingSystem=numberingSystem}static get defaultOutputCalendar(){return defaultOutputCalendar}static set defaultOutputCalendar(outputCalendar){defaultOutputCalendar=outputCalendar}static get twoDigitCutoffYear(){return twoDigitCutoffYear}static set twoDigitCutoffYear(cutoffYear){twoDigitCutoffYear=cutoffYear%100}static get throwOnInvalid(){return throwOnInvalid}static set throwOnInvalid(t2){throwOnInvalid=t2}static resetCaches(){Locale.resetCache(),IANAZone.resetCache()}};__name2(_Settings,"Settings");let Settings=_Settings;function isUndefined(o){return typeof o>"u"}__name(isUndefined,"isUndefined"),__name2(isUndefined,"isUndefined");function isNumber(o){return typeof o=="number"}__name(isNumber,"isNumber"),__name2(isNumber,"isNumber");function isInteger(o){return typeof o=="number"&&o%1===0}__name(isInteger,"isInteger"),__name2(isInteger,"isInteger");function isString(o){return typeof o=="string"}__name(isString,"isString"),__name2(isString,"isString");function isDate(o){return Object.prototype.toString.call(o)==="[object Date]"}__name(isDate,"isDate"),__name2(isDate,"isDate");function hasRelative(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}__name(hasRelative,"hasRelative"),__name2(hasRelative,"hasRelative");function maybeArray(thing){return Array.isArray(thing)?thing:[thing]}__name(maybeArray,"maybeArray"),__name2(maybeArray,"maybeArray");function bestBy(arr,by,compare2){if(arr.length!==0)return arr.reduce((best,next)=>{const pair2=[by(next),next];return best&&compare2(best[0],pair2[0])===best[0]?best:pair2},null)[1]}__name(bestBy,"bestBy"),__name2(bestBy,"bestBy");function pick(obj,keys2){return keys2.reduce((a,k)=>(a[k]=obj[k],a),{})}__name(pick,"pick"),__name2(pick,"pick");function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}__name(hasOwnProperty,"hasOwnProperty"),__name2(hasOwnProperty,"hasOwnProperty");function integerBetween(thing,bottom,top2){return isInteger(thing)&&thing>=bottom&&thing<=top2}__name(integerBetween,"integerBetween"),__name2(integerBetween,"integerBetween");function floorMod(x,n2){return x-n2*Math.floor(x/n2)}__name(floorMod,"floorMod"),__name2(floorMod,"floorMod");function padStart(input,n2=2){const isNeg=input<0;let padded;return isNeg?padded="-"+(""+-input).padStart(n2,"0"):padded=(""+input).padStart(n2,"0"),padded}__name(padStart,"padStart"),__name2(padStart,"padStart");function parseInteger(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseInt(string2,10)}__name(parseInteger,"parseInteger"),__name2(parseInteger,"parseInteger");function parseFloating(string2){if(!(isUndefined(string2)||string2===null||string2===""))return parseFloat(string2)}__name(parseFloating,"parseFloating"),__name2(parseFloating,"parseFloating");function parseMillis(fraction){if(!(isUndefined(fraction)||fraction===null||fraction==="")){const f=parseFloat("0."+fraction)*1e3;return Math.floor(f)}}__name(parseMillis,"parseMillis"),__name2(parseMillis,"parseMillis");function roundTo(number2,digits,towardZero=!1){const factor=10**digits;return(towardZero?Math.trunc:Math.round)(number2*factor)/factor}__name(roundTo,"roundTo"),__name2(roundTo,"roundTo");function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}__name(isLeapYear,"isLeapYear"),__name2(isLeapYear,"isLeapYear");function daysInYear(year){return isLeapYear(year)?366:365}__name(daysInYear,"daysInYear"),__name2(daysInYear,"daysInYear");function daysInMonth(year,month){const modMonth=floorMod(month-1,12)+1,modYear=year+(month-modMonth)/12;return modMonth===2?isLeapYear(modYear)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][modMonth-1]}__name(daysInMonth,"daysInMonth"),__name2(daysInMonth,"daysInMonth");function objToLocalTS(obj){let d=Date.UTC(obj.year,obj.month-1,obj.day,obj.hour,obj.minute,obj.second,obj.millisecond);return obj.year<100&&obj.year>=0&&(d=new Date(d),d.setUTCFullYear(obj.year,obj.month-1,obj.day)),+d}__name(objToLocalTS,"objToLocalTS"),__name2(objToLocalTS,"objToLocalTS");function weeksInWeekYear(weekYear){const p1=(weekYear+Math.floor(weekYear/4)-Math.floor(weekYear/100)+Math.floor(weekYear/400))%7,last2=weekYear-1,p2=(last2+Math.floor(last2/4)-Math.floor(last2/100)+Math.floor(last2/400))%7;return p1===4||p2===3?53:52}__name(weeksInWeekYear,"weeksInWeekYear"),__name2(weeksInWeekYear,"weeksInWeekYear");function untruncateYear(year){return year>99?year:year>Settings.twoDigitCutoffYear?1900+year:2e3+year}__name(untruncateYear,"untruncateYear"),__name2(untruncateYear,"untruncateYear");function parseZoneInfo(ts,offsetFormat,locale,timeZone=null){const date=new Date(ts),intlOpts={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};timeZone&&(intlOpts.timeZone=timeZone);const modified={timeZoneName:offsetFormat,...intlOpts},parsed=new Intl.DateTimeFormat(locale,modified).formatToParts(date).find(m=>m.type.toLowerCase()==="timezonename");return parsed?parsed.value:null}__name(parseZoneInfo,"parseZoneInfo"),__name2(parseZoneInfo,"parseZoneInfo");function signedOffset(offHourStr,offMinuteStr){let offHour=parseInt(offHourStr,10);Number.isNaN(offHour)&&(offHour=0);const offMin=parseInt(offMinuteStr,10)||0,offMinSigned=offHour<0||Object.is(offHour,-0)?-offMin:offMin;return offHour*60+offMinSigned}__name(signedOffset,"signedOffset"),__name2(signedOffset,"signedOffset");function asNumber(value){const numericValue=Number(value);if(typeof value=="boolean"||value===""||Number.isNaN(numericValue))throw new InvalidArgumentError(`Invalid unit value ${value}`);return numericValue}__name(asNumber,"asNumber"),__name2(asNumber,"asNumber");function normalizeObject(obj,normalizer){const normalized={};for(const u in obj)if(hasOwnProperty(obj,u)){const v=obj[u];if(v==null)continue;normalized[normalizer(u)]=asNumber(v)}return normalized}__name(normalizeObject,"normalizeObject"),__name2(normalizeObject,"normalizeObject");function formatOffset(offset2,format){const hours=Math.trunc(Math.abs(offset2/60)),minutes=Math.trunc(Math.abs(offset2%60)),sign=offset2>=0?"+":"-";switch(format){case"short":return`${sign}${padStart(hours,2)}:${padStart(minutes,2)}`;case"narrow":return`${sign}${hours}${minutes>0?`:${minutes}`:""}`;case"techie":return`${sign}${padStart(hours,2)}${padStart(minutes,2)}`;default:throw new RangeError(`Value format ${format} is out of range for property format`)}}__name(formatOffset,"formatOffset"),__name2(formatOffset,"formatOffset");function timeObject(obj){return pick(obj,["hour","minute","second","millisecond"])}__name(timeObject,"timeObject"),__name2(timeObject,"timeObject");const monthsLong=["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsNarrow=["J","F","M","A","M","J","J","A","S","O","N","D"];function months(length){switch(length){case"narrow":return[...monthsNarrow];case"short":return[...monthsShort];case"long":return[...monthsLong];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}__name(months,"months"),__name2(months,"months");const weekdaysLong=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekdaysShort=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],weekdaysNarrow=["M","T","W","T","F","S","S"];function weekdays(length){switch(length){case"narrow":return[...weekdaysNarrow];case"short":return[...weekdaysShort];case"long":return[...weekdaysLong];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}__name(weekdays,"weekdays"),__name2(weekdays,"weekdays");const meridiems=["AM","PM"],erasLong=["Before Christ","Anno Domini"],erasShort=["BC","AD"],erasNarrow=["B","A"];function eras(length){switch(length){case"narrow":return[...erasNarrow];case"short":return[...erasShort];case"long":return[...erasLong];default:return null}}__name(eras,"eras"),__name2(eras,"eras");function meridiemForDateTime(dt){return meridiems[dt.hour<12?0:1]}__name(meridiemForDateTime,"meridiemForDateTime"),__name2(meridiemForDateTime,"meridiemForDateTime");function weekdayForDateTime(dt,length){return weekdays(length)[dt.weekday-1]}__name(weekdayForDateTime,"weekdayForDateTime"),__name2(weekdayForDateTime,"weekdayForDateTime");function monthForDateTime(dt,length){return months(length)[dt.month-1]}__name(monthForDateTime,"monthForDateTime"),__name2(monthForDateTime,"monthForDateTime");function eraForDateTime(dt,length){return eras(length)[dt.year<0?0:1]}__name(eraForDateTime,"eraForDateTime"),__name2(eraForDateTime,"eraForDateTime");function formatRelativeTime(unit,count,numeric="always",narrow=!1){const units={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},lastable=["hours","minutes","seconds"].indexOf(unit)===-1;if(numeric==="auto"&&lastable){const isDay=unit==="days";switch(count){case 1:return isDay?"tomorrow":`next ${units[unit][0]}`;case-1:return isDay?"yesterday":`last ${units[unit][0]}`;case 0:return isDay?"today":`this ${units[unit][0]}`}}const isInPast=Object.is(count,-0)||count<0,fmtValue=Math.abs(count),singular=fmtValue===1,lilUnits=units[unit],fmtUnit=narrow?singular?lilUnits[1]:lilUnits[2]||lilUnits[1]:singular?units[unit][0]:unit;return isInPast?`${fmtValue} ${fmtUnit} ago`:`in ${fmtValue} ${fmtUnit}`}__name(formatRelativeTime,"formatRelativeTime"),__name2(formatRelativeTime,"formatRelativeTime");function stringifyTokens(splits,tokenToString){let s2="";for(const token of splits)token.literal?s2+=token.val:s2+=tokenToString(token.val);return s2}__name(stringifyTokens,"stringifyTokens"),__name2(stringifyTokens,"stringifyTokens");const macroTokenToFormatOpts={D:DATE_SHORT,DD:DATE_MED,DDD:DATE_FULL,DDDD:DATE_HUGE,t:TIME_SIMPLE,tt:TIME_WITH_SECONDS,ttt:TIME_WITH_SHORT_OFFSET,tttt:TIME_WITH_LONG_OFFSET,T:TIME_24_SIMPLE,TT:TIME_24_WITH_SECONDS,TTT:TIME_24_WITH_SHORT_OFFSET,TTTT:TIME_24_WITH_LONG_OFFSET,f:DATETIME_SHORT,ff:DATETIME_MED,fff:DATETIME_FULL,ffff:DATETIME_HUGE,F:DATETIME_SHORT_WITH_SECONDS,FF:DATETIME_MED_WITH_SECONDS,FFF:DATETIME_FULL_WITH_SECONDS,FFFF:DATETIME_HUGE_WITH_SECONDS},_Formatter=class _Formatter2{static{__name(this,"_Formatter")}static create(locale,opts={}){return new _Formatter2(locale,opts)}static parseFormat(fmt){let current=null,currentFull="",bracketed=!1;const splits=[];for(let i=0;i0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),current=null,currentFull="",bracketed=!bracketed):bracketed||c===current?currentFull+=c:(currentFull.length>0&&splits.push({literal:/^\s+$/.test(currentFull),val:currentFull}),currentFull=c,current=c)}return currentFull.length>0&&splits.push({literal:bracketed||/^\s+$/.test(currentFull),val:currentFull}),splits}static macroTokenToFormatOpts(token){return macroTokenToFormatOpts[token]}constructor(locale,formatOpts){this.opts=formatOpts,this.loc=locale,this.systemLoc=null}formatWithSystemDefault(dt,opts){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(dt,{...this.opts,...opts}).format()}dtFormatter(dt,opts={}){return this.loc.dtFormatter(dt,{...this.opts,...opts})}formatDateTime(dt,opts){return this.dtFormatter(dt,opts).format()}formatDateTimeParts(dt,opts){return this.dtFormatter(dt,opts).formatToParts()}formatInterval(interval,opts){return this.dtFormatter(interval.start,opts).dtf.formatRange(interval.start.toJSDate(),interval.end.toJSDate())}resolvedOptions(dt,opts){return this.dtFormatter(dt,opts).resolvedOptions()}num(n2,p=0){if(this.opts.forceSimple)return padStart(n2,p);const opts={...this.opts};return p>0&&(opts.padTo=p),this.loc.numberFormatter(opts).format(n2)}formatDateTimeFromString(dt,fmt){const knownEnglish=this.loc.listingMode()==="en",useDateTimeFormatter=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",string2=__name2((opts,extract)=>this.loc.extract(dt,opts,extract),"string"),formatOffset2=__name2(opts=>dt.isOffsetFixed&&dt.offset===0&&opts.allowZ?"Z":dt.isValid?dt.zone.formatOffset(dt.ts,opts.format):"","formatOffset"),meridiem=__name2(()=>knownEnglish?meridiemForDateTime(dt):string2({hour:"numeric",hourCycle:"h12"},"dayperiod"),"meridiem"),month=__name2((length,standalone)=>knownEnglish?monthForDateTime(dt,length):string2(standalone?{month:length}:{month:length,day:"numeric"},"month"),"month"),weekday=__name2((length,standalone)=>knownEnglish?weekdayForDateTime(dt,length):string2(standalone?{weekday:length}:{weekday:length,month:"long",day:"numeric"},"weekday"),"weekday"),maybeMacro=__name2(token=>{const formatOpts=_Formatter2.macroTokenToFormatOpts(token);return formatOpts?this.formatWithSystemDefault(dt,formatOpts):token},"maybeMacro"),era=__name2(length=>knownEnglish?eraForDateTime(dt,length):string2({era:length},"era"),"era"),tokenToString=__name2(token=>{switch(token){case"S":return this.num(dt.millisecond);case"u":case"SSS":return this.num(dt.millisecond,3);case"s":return this.num(dt.second);case"ss":return this.num(dt.second,2);case"uu":return this.num(Math.floor(dt.millisecond/10),2);case"uuu":return this.num(Math.floor(dt.millisecond/100));case"m":return this.num(dt.minute);case"mm":return this.num(dt.minute,2);case"h":return this.num(dt.hour%12===0?12:dt.hour%12);case"hh":return this.num(dt.hour%12===0?12:dt.hour%12,2);case"H":return this.num(dt.hour);case"HH":return this.num(dt.hour,2);case"Z":return formatOffset2({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return formatOffset2({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return formatOffset2({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return dt.zone.offsetName(dt.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return dt.zone.offsetName(dt.ts,{format:"long",locale:this.loc.locale});case"z":return dt.zoneName;case"a":return meridiem();case"d":return useDateTimeFormatter?string2({day:"numeric"},"day"):this.num(dt.day);case"dd":return useDateTimeFormatter?string2({day:"2-digit"},"day"):this.num(dt.day,2);case"c":return this.num(dt.weekday);case"ccc":return weekday("short",!0);case"cccc":return weekday("long",!0);case"ccccc":return weekday("narrow",!0);case"E":return this.num(dt.weekday);case"EEE":return weekday("short",!1);case"EEEE":return weekday("long",!1);case"EEEEE":return weekday("narrow",!1);case"L":return useDateTimeFormatter?string2({month:"numeric",day:"numeric"},"month"):this.num(dt.month);case"LL":return useDateTimeFormatter?string2({month:"2-digit",day:"numeric"},"month"):this.num(dt.month,2);case"LLL":return month("short",!0);case"LLLL":return month("long",!0);case"LLLLL":return month("narrow",!0);case"M":return useDateTimeFormatter?string2({month:"numeric"},"month"):this.num(dt.month);case"MM":return useDateTimeFormatter?string2({month:"2-digit"},"month"):this.num(dt.month,2);case"MMM":return month("short",!1);case"MMMM":return month("long",!1);case"MMMMM":return month("narrow",!1);case"y":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year);case"yy":return useDateTimeFormatter?string2({year:"2-digit"},"year"):this.num(dt.year.toString().slice(-2),2);case"yyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,4);case"yyyyyy":return useDateTimeFormatter?string2({year:"numeric"},"year"):this.num(dt.year,6);case"G":return era("short");case"GG":return era("long");case"GGGGG":return era("narrow");case"kk":return this.num(dt.weekYear.toString().slice(-2),2);case"kkkk":return this.num(dt.weekYear,4);case"W":return this.num(dt.weekNumber);case"WW":return this.num(dt.weekNumber,2);case"o":return this.num(dt.ordinal);case"ooo":return this.num(dt.ordinal,3);case"q":return this.num(dt.quarter);case"qq":return this.num(dt.quarter,2);case"X":return this.num(Math.floor(dt.ts/1e3));case"x":return this.num(dt.ts);default:return maybeMacro(token)}},"tokenToString");return stringifyTokens(_Formatter2.parseFormat(fmt),tokenToString)}formatDurationFromString(dur,fmt){const tokenToField=__name2(token=>{switch(token[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},"tokenToField"),tokenToString=__name2(lildur=>token=>{const mapped=tokenToField(token);return mapped?this.num(lildur.get(mapped),token.length):token},"tokenToString"),tokens=_Formatter2.parseFormat(fmt),realTokens=tokens.reduce((found,{literal:literal2,val})=>literal2?found:found.concat(val),[]),collapsed=dur.shiftTo(...realTokens.map(tokenToField).filter(t2=>t2));return stringifyTokens(tokens,tokenToString(collapsed))}};__name2(_Formatter,"Formatter");let Formatter=_Formatter;const _Invalid=class{static{__name(this,"_Invalid")}constructor(reason,explanation){this.reason=reason,this.explanation=explanation}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};__name2(_Invalid,"Invalid");let Invalid=_Invalid;const ianaRegex=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function combineRegexes(...regexes){const full=regexes.reduce((f,r)=>f+r.source,"");return RegExp(`^${full}$`)}__name(combineRegexes,"combineRegexes"),__name2(combineRegexes,"combineRegexes");function combineExtractors(...extractors){return m=>extractors.reduce(([mergedVals,mergedZone,cursor],ex)=>{const[val,zone,next]=ex(m,cursor);return[{...mergedVals,...val},zone||mergedZone,next]},[{},null,1]).slice(0,2)}__name(combineExtractors,"combineExtractors"),__name2(combineExtractors,"combineExtractors");function parse(s2,...patterns){if(s2==null)return[null,null];for(const[regex,extractor]of patterns){const m=regex.exec(s2);if(m)return extractor(m)}return[null,null]}__name(parse,"parse"),__name2(parse,"parse");function simpleParse(...keys2){return(match2,cursor)=>{const ret={};let i;for(i=0;inum!==void 0&&(force||num&&hasNegativePrefix)?-num:num,"maybeNegate");return[{years:maybeNegate(parseFloating(yearStr)),months:maybeNegate(parseFloating(monthStr)),weeks:maybeNegate(parseFloating(weekStr)),days:maybeNegate(parseFloating(dayStr)),hours:maybeNegate(parseFloating(hourStr)),minutes:maybeNegate(parseFloating(minuteStr)),seconds:maybeNegate(parseFloating(secondStr),secondStr==="-0"),milliseconds:maybeNegate(parseMillis(millisecondsStr),negativeSeconds)}]}__name(extractISODuration,"extractISODuration"),__name2(extractISODuration,"extractISODuration");const obsOffsets={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){const result={year:yearStr.length===2?untruncateYear(parseInteger(yearStr)):parseInteger(yearStr),month:monthsShort.indexOf(monthStr)+1,day:parseInteger(dayStr),hour:parseInteger(hourStr),minute:parseInteger(minuteStr)};return secondStr&&(result.second=parseInteger(secondStr)),weekdayStr&&(result.weekday=weekdayStr.length>3?weekdaysLong.indexOf(weekdayStr)+1:weekdaysShort.indexOf(weekdayStr)+1),result}__name(fromStrings,"fromStrings"),__name2(fromStrings,"fromStrings");const rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function extractRFC2822(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr,obsOffset,milOffset,offHourStr,offMinuteStr]=match2,result=fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr);let offset2;return obsOffset?offset2=obsOffsets[obsOffset]:milOffset?offset2=0:offset2=signedOffset(offHourStr,offMinuteStr),[result,new FixedOffsetZone(offset2)]}__name(extractRFC2822,"extractRFC2822"),__name2(extractRFC2822,"extractRFC2822");function preprocessRFC2822(s2){return s2.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}__name(preprocessRFC2822,"preprocessRFC2822"),__name2(preprocessRFC2822,"preprocessRFC2822");const rfc1123=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,rfc850=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ascii=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function extractRFC1123Or850(match2){const[,weekdayStr,dayStr,monthStr,yearStr,hourStr,minuteStr,secondStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractRFC1123Or850,"extractRFC1123Or850"),__name2(extractRFC1123Or850,"extractRFC1123Or850");function extractASCII(match2){const[,weekdayStr,monthStr,dayStr,hourStr,minuteStr,secondStr,yearStr]=match2;return[fromStrings(weekdayStr,yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr),FixedOffsetZone.utcInstance]}__name(extractASCII,"extractASCII"),__name2(extractASCII,"extractASCII");const isoYmdWithTimeExtensionRegex=combineRegexes(isoYmdRegex,isoTimeExtensionRegex),isoWeekWithTimeExtensionRegex=combineRegexes(isoWeekRegex,isoTimeExtensionRegex),isoOrdinalWithTimeExtensionRegex=combineRegexes(isoOrdinalRegex,isoTimeExtensionRegex),isoTimeCombinedRegex=combineRegexes(isoTimeRegex),extractISOYmdTimeAndOffset=combineExtractors(extractISOYmd,extractISOTime,extractISOOffset,extractIANAZone),extractISOWeekTimeAndOffset=combineExtractors(extractISOWeekData,extractISOTime,extractISOOffset,extractIANAZone),extractISOOrdinalDateAndTime=combineExtractors(extractISOOrdinalData,extractISOTime,extractISOOffset,extractIANAZone),extractISOTimeAndOffset=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseISODate(s2){return parse(s2,[isoYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[isoWeekWithTimeExtensionRegex,extractISOWeekTimeAndOffset],[isoOrdinalWithTimeExtensionRegex,extractISOOrdinalDateAndTime],[isoTimeCombinedRegex,extractISOTimeAndOffset])}__name(parseISODate,"parseISODate"),__name2(parseISODate,"parseISODate");function parseRFC2822Date(s2){return parse(preprocessRFC2822(s2),[rfc2822,extractRFC2822])}__name(parseRFC2822Date,"parseRFC2822Date"),__name2(parseRFC2822Date,"parseRFC2822Date");function parseHTTPDate(s2){return parse(s2,[rfc1123,extractRFC1123Or850],[rfc850,extractRFC1123Or850],[ascii,extractASCII])}__name(parseHTTPDate,"parseHTTPDate"),__name2(parseHTTPDate,"parseHTTPDate");function parseISODuration(s2){return parse(s2,[isoDuration,extractISODuration])}__name(parseISODuration,"parseISODuration"),__name2(parseISODuration,"parseISODuration");const extractISOTimeOnly=combineExtractors(extractISOTime);function parseISOTimeOnly(s2){return parse(s2,[isoTimeOnly,extractISOTimeOnly])}__name(parseISOTimeOnly,"parseISOTimeOnly"),__name2(parseISOTimeOnly,"parseISOTimeOnly");const sqlYmdWithTimeExtensionRegex=combineRegexes(sqlYmdRegex,sqlTimeExtensionRegex),sqlTimeCombinedRegex=combineRegexes(sqlTimeRegex),extractISOTimeOffsetAndIANAZone=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseSQL(s2){return parse(s2,[sqlYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[sqlTimeCombinedRegex,extractISOTimeOffsetAndIANAZone])}__name(parseSQL,"parseSQL"),__name2(parseSQL,"parseSQL");const INVALID$2="Invalid Duration",lowOrderMatrix={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},casualMatrix={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...lowOrderMatrix},daysInYearAccurate=146097/400,daysInMonthAccurate=146097/4800,accurateMatrix={years:{quarters:4,months:12,weeks:daysInYearAccurate/7,days:daysInYearAccurate,hours:daysInYearAccurate*24,minutes:daysInYearAccurate*24*60,seconds:daysInYearAccurate*24*60*60,milliseconds:daysInYearAccurate*24*60*60*1e3},quarters:{months:3,weeks:daysInYearAccurate/28,days:daysInYearAccurate/4,hours:daysInYearAccurate*24/4,minutes:daysInYearAccurate*24*60/4,seconds:daysInYearAccurate*24*60*60/4,milliseconds:daysInYearAccurate*24*60*60*1e3/4},months:{weeks:daysInMonthAccurate/7,days:daysInMonthAccurate,hours:daysInMonthAccurate*24,minutes:daysInMonthAccurate*24*60,seconds:daysInMonthAccurate*24*60*60,milliseconds:daysInMonthAccurate*24*60*60*1e3},...lowOrderMatrix},orderedUnits$1=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],reverseUnits=orderedUnits$1.slice(0).reverse();function clone$1(dur,alts,clear=!1){const conf={values:clear?alts.values:{...dur.values,...alts.values||{}},loc:dur.loc.clone(alts.loc),conversionAccuracy:alts.conversionAccuracy||dur.conversionAccuracy,matrix:alts.matrix||dur.matrix};return new Duration(conf)}__name(clone$1,"clone$1"),__name2(clone$1,"clone$1");function durationToMillis(matrix2,vals){let sum=vals.milliseconds??0;for(const unit of reverseUnits.slice(1))vals[unit]&&(sum+=vals[unit]*matrix2[unit].milliseconds);return sum}__name(durationToMillis,"durationToMillis"),__name2(durationToMillis,"durationToMillis");function normalizeValues(matrix2,vals){const factor=durationToMillis(matrix2,vals)<0?-1:1;orderedUnits$1.reduceRight((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const previousVal=vals[previous]*factor,conv=matrix2[current][previous],rollUp=Math.floor(previousVal/conv);vals[current]+=rollUp*factor,vals[previous]-=rollUp*conv*factor}return current},null),orderedUnits$1.reduce((previous,current)=>{if(isUndefined(vals[current]))return previous;if(previous){const fraction=vals[previous]%1;vals[previous]-=fraction,vals[current]+=fraction*matrix2[previous][current]}return current},null)}__name(normalizeValues,"normalizeValues"),__name2(normalizeValues,"normalizeValues");function removeZeroes(vals){const newVals={};for(const[key,value]of Object.entries(vals))value!==0&&(newVals[key]=value);return newVals}__name(removeZeroes,"removeZeroes"),__name2(removeZeroes,"removeZeroes");const _Duration=class _Duration2{static{__name(this,"_Duration")}constructor(config2){const accurate=config2.conversionAccuracy==="longterm"||!1;let matrix2=accurate?accurateMatrix:casualMatrix;config2.matrix&&(matrix2=config2.matrix),this.values=config2.values,this.loc=config2.loc||Locale.create(),this.conversionAccuracy=accurate?"longterm":"casual",this.invalid=config2.invalid||null,this.matrix=matrix2,this.isLuxonDuration=!0}static fromMillis(count,opts){return _Duration2.fromObject({milliseconds:count},opts)}static fromObject(obj,opts={}){if(obj==null||typeof obj!="object")throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj===null?"null":typeof obj}`);return new _Duration2({values:normalizeObject(obj,_Duration2.normalizeUnit),loc:Locale.fromObject(opts),conversionAccuracy:opts.conversionAccuracy,matrix:opts.matrix})}static fromDurationLike(durationLike){if(isNumber(durationLike))return _Duration2.fromMillis(durationLike);if(_Duration2.isDuration(durationLike))return durationLike;if(typeof durationLike=="object")return _Duration2.fromObject(durationLike);throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`)}static fromISO(text,opts){const[parsed]=parseISODuration(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static fromISOTime(text,opts){const[parsed]=parseISOTimeOnly(text);return parsed?_Duration2.fromObject(parsed,opts):_Duration2.invalid("unparsable",`the input "${text}" can't be parsed as ISO 8601`)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the Duration is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDurationError(invalid);return new _Duration2({invalid})}static normalizeUnit(unit){const normalized={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[unit&&unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}static isDuration(o){return o&&o.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(fmt,opts={}){const fmtOpts={...opts,floor:opts.round!==!1&&opts.floor!==!1};return this.isValid?Formatter.create(this.loc,fmtOpts).formatDurationFromString(this,fmt):INVALID$2}toHuman(opts={}){if(!this.isValid)return INVALID$2;const l2=orderedUnits$1.map(unit=>{const val=this.values[unit];return isUndefined(val)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...opts,unit:unit.slice(0,-1)}).format(val)}).filter(n2=>n2);return this.loc.listFormatter({type:"conjunction",style:opts.listStyle||"narrow",...opts}).format(l2)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s2="P";return this.years!==0&&(s2+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s2+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s2+=this.weeks+"W"),this.days!==0&&(s2+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s2+="T"),this.hours!==0&&(s2+=this.hours+"H"),this.minutes!==0&&(s2+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s2+=roundTo(this.seconds+this.milliseconds/1e3,3)+"S"),s2==="P"&&(s2+="T0S"),s2}toISOTime(opts={}){if(!this.isValid)return null;const millis=this.toMillis();return millis<0||millis>=864e5?null:(opts={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...opts,includeOffset:!1},DateTime.fromMillis(millis,{zone:"UTC"}).toISOTime(opts))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?durationToMillis(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration),result={};for(const k of orderedUnits$1)(hasOwnProperty(dur.values,k)||hasOwnProperty(this.values,k))&&(result[k]=dur.get(k)+this.get(k));return clone$1(this,{values:result},!0)}minus(duration){if(!this.isValid)return this;const dur=_Duration2.fromDurationLike(duration);return this.plus(dur.negate())}mapUnits(fn){if(!this.isValid)return this;const result={};for(const k of Object.keys(this.values))result[k]=asNumber(fn(this.values[k],k));return clone$1(this,{values:result},!0)}get(unit){return this[_Duration2.normalizeUnit(unit)]}set(values){if(!this.isValid)return this;const mixed={...this.values,...normalizeObject(values,_Duration2.normalizeUnit)};return clone$1(this,{values:mixed})}reconfigure({locale,numberingSystem,conversionAccuracy,matrix:matrix2}={}){const opts={loc:this.loc.clone({locale,numberingSystem}),matrix:matrix2,conversionAccuracy};return clone$1(this,opts)}as(unit){return this.isValid?this.shiftTo(unit).get(unit):NaN}normalize(){if(!this.isValid)return this;const vals=this.toObject();return normalizeValues(this.matrix,vals),clone$1(this,{values:vals},!0)}rescale(){if(!this.isValid)return this;const vals=removeZeroes(this.normalize().shiftToAll().toObject());return clone$1(this,{values:vals},!0)}shiftTo(...units){if(!this.isValid)return this;if(units.length===0)return this;units=units.map(u=>_Duration2.normalizeUnit(u));const built={},accumulated={},vals=this.toObject();let lastUnit;for(const k of orderedUnits$1)if(units.indexOf(k)>=0){lastUnit=k;let own=0;for(const ak in accumulated)own+=this.matrix[ak][k]*accumulated[ak],accumulated[ak]=0;isNumber(vals[k])&&(own+=vals[k]);const i=Math.trunc(own);built[k]=i,accumulated[k]=(own*1e3-i*1e3)/1e3}else isNumber(vals[k])&&(accumulated[k]=vals[k]);for(const key in accumulated)accumulated[key]!==0&&(built[lastUnit]+=key===lastUnit?accumulated[key]:accumulated[key]/this.matrix[lastUnit][key]);return normalizeValues(this.matrix,built),clone$1(this,{values:built},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const negated={};for(const k of Object.keys(this.values))negated[k]=this.values[k]===0?0:-this.values[k];return clone$1(this,{values:negated},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(other){if(!this.isValid||!other.isValid||!this.loc.equals(other.loc))return!1;function eq(v1,v2){return v1===void 0||v1===0?v2===void 0||v2===0:v1===v2}__name(eq,"eq"),__name2(eq,"eq");for(const u of orderedUnits$1)if(!eq(this.values[u],other.values[u]))return!1;return!0}};__name2(_Duration,"Duration");let Duration=_Duration;const INVALID$1="Invalid Interval";function validateStartEnd(start,end){return!start||!start.isValid?Interval.invalid("missing or invalid start"):!end||!end.isValid?Interval.invalid("missing or invalid end"):enddateTime:!1}isBefore(dateTime){return this.isValid?this.e<=dateTime:!1}contains(dateTime){return this.isValid?this.s<=dateTime&&this.e>dateTime:!1}set({start,end}={}){return this.isValid?_Interval2.fromDateTimes(start||this.s,end||this.e):this}splitAt(...dateTimes){if(!this.isValid)return[];const sorted=dateTimes.map(friendlyDateTime).filter(d=>this.contains(d)).sort(),results=[];let{s:s2}=this,i=0;for(;s2+this.e?this.e:added;results.push(_Interval2.fromDateTimes(s2,next)),s2=next,i+=1}return results}splitBy(duration){const dur=Duration.fromDurationLike(duration);if(!this.isValid||!dur.isValid||dur.as("milliseconds")===0)return[];let{s:s2}=this,idx=1,next;const results=[];for(;s2x*idx));next=+added>+this.e?this.e:added,results.push(_Interval2.fromDateTimes(s2,next)),s2=next,idx+=1}return results}divideEqually(numberOfParts){return this.isValid?this.splitBy(this.length()/numberOfParts).slice(0,numberOfParts):[]}overlaps(other){return this.e>other.s&&this.s=other.e:!1}equals(other){return!this.isValid||!other.isValid?!1:this.s.equals(other.s)&&this.e.equals(other.e)}intersection(other){if(!this.isValid)return this;const s2=this.s>other.s?this.s:other.s,e=this.e=e?null:_Interval2.fromDateTimes(s2,e)}union(other){if(!this.isValid)return this;const s2=this.sother.e?this.e:other.e;return _Interval2.fromDateTimes(s2,e)}static merge(intervals){const[found,final]=intervals.sort((a,b)=>a.s-b.s).reduce(([sofar,current],item)=>current?current.overlaps(item)||current.abutsStart(item)?[sofar,current.union(item)]:[sofar.concat([current]),item]:[sofar,item],[[],null]);return final&&found.push(final),found}static xor(intervals){let start=null,currentCount=0;const results=[],ends=intervals.map(i=>[{time:i.s,type:"s"},{time:i.e,type:"e"}]),flattened2=Array.prototype.concat(...ends),arr=flattened2.sort((a,b)=>a.time-b.time);for(const i of arr)currentCount+=i.type==="s"?1:-1,currentCount===1?start=i.time:(start&&+start!=+i.time&&results.push(_Interval2.fromDateTimes(start,i.time)),start=null);return _Interval2.merge(results)}difference(...intervals){return _Interval2.xor([this].concat(intervals)).map(i=>this.intersection(i)).filter(i=>i&&!i.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:INVALID$1}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.s.loc.clone(opts),formatOpts).formatInterval(this):INVALID$1}toISO(opts){return this.isValid?`${this.s.toISO(opts)}/${this.e.toISO(opts)}`:INVALID$1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:INVALID$1}toISOTime(opts){return this.isValid?`${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`:INVALID$1}toFormat(dateFormat,{separator=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`:INVALID$1}toDuration(unit,opts){return this.isValid?this.e.diff(this.s,unit,opts):Duration.invalid(this.invalidReason)}mapEndpoints(mapFn){return _Interval2.fromDateTimes(mapFn(this.s),mapFn(this.e))}};__name2(_Interval,"Interval");let Interval=_Interval;const _Info=class{static{__name(this,"_Info")}static hasDST(zone=Settings.defaultZone){const proto=DateTime.now().setZone(zone).set({month:12});return!zone.isUniversal&&proto.offset!==proto.set({month:6}).offset}static isValidIANAZone(zone){return IANAZone.isValidZone(zone)}static normalizeZone(input){return normalizeZone(input,Settings.defaultZone)}static months(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length)}static monthsFormat(length="long",{locale=null,numberingSystem=null,locObj=null,outputCalendar="gregory"}={}){return(locObj||Locale.create(locale,numberingSystem,outputCalendar)).months(length,!0)}static weekdays(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length)}static weekdaysFormat(length="long",{locale=null,numberingSystem=null,locObj=null}={}){return(locObj||Locale.create(locale,numberingSystem,null)).weekdays(length,!0)}static meridiems({locale=null}={}){return Locale.create(locale).meridiems()}static eras(length="short",{locale=null}={}){return Locale.create(locale,null,"gregory").eras(length)}static features(){return{relative:hasRelative()}}};__name2(_Info,"Info");let Info=_Info;function dayDiff(earlier,later){const utcDayStart=__name2(dt=>dt.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),"utcDayStart"),ms=utcDayStart(later)-utcDayStart(earlier);return Math.floor(Duration.fromMillis(ms).as("days"))}__name(dayDiff,"dayDiff"),__name2(dayDiff,"dayDiff");function highOrderDiffs(cursor,later,units){const differs=[["years",(a,b)=>b.year-a.year],["quarters",(a,b)=>b.quarter-a.quarter+(b.year-a.year)*4],["months",(a,b)=>b.month-a.month+(b.year-a.year)*12],["weeks",(a,b)=>{const days=dayDiff(a,b);return(days-days%7)/7}],["days",dayDiff]],results={},earlier=cursor;let lowestOrder,highWater;for(const[unit,differ]of differs)units.indexOf(unit)>=0&&(lowestOrder=unit,results[unit]=differ(cursor,later),highWater=earlier.plus(results),highWater>later?(results[unit]--,cursor=earlier.plus(results),cursor>later&&(highWater=cursor,results[unit]--,cursor=earlier.plus(results))):cursor=highWater);return[cursor,results,highWater,lowestOrder]}__name(highOrderDiffs,"highOrderDiffs"),__name2(highOrderDiffs,"highOrderDiffs");function diff(earlier,later,units,opts){let[cursor,results,highWater,lowestOrder]=highOrderDiffs(earlier,later,units);const remainingMillis=later-cursor,lowerOrderUnits=units.filter(u=>["hours","minutes","seconds","milliseconds"].indexOf(u)>=0);lowerOrderUnits.length===0&&(highWater0?Duration.fromMillis(remainingMillis,opts).shiftTo(...lowerOrderUnits).plus(duration):duration}__name(diff,"diff"),__name2(diff,"diff");const numberingSystems={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},numberingSystemsUTF16={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},hanidecChars=numberingSystems.hanidec.replace(/[\[|\]]/g,"").split("");function parseDigits(str){let value=parseInt(str,10);if(isNaN(value)){value="";for(let i=0;i=min&&code<=max&&(value+=code-min)}}return parseInt(value,10)}else return value}__name(parseDigits,"parseDigits"),__name2(parseDigits,"parseDigits");function digitRegex({numberingSystem},append=""){return new RegExp(`${numberingSystems[numberingSystem||"latn"]}${append}`)}__name(digitRegex,"digitRegex"),__name2(digitRegex,"digitRegex");const MISSING_FTP="missing Intl.DateTimeFormat.formatToParts support";function intUnit(regex,post=i=>i){return{regex,deser:([s2])=>post(parseDigits(s2))}}__name(intUnit,"intUnit"),__name2(intUnit,"intUnit");const NBSP=String.fromCharCode(160),spaceOrNBSP=`[ ${NBSP}]`,spaceOrNBSPRegExp=new RegExp(spaceOrNBSP,"g");function fixListRegex(s2){return s2.replace(/\./g,"\\.?").replace(spaceOrNBSPRegExp,spaceOrNBSP)}__name(fixListRegex,"fixListRegex"),__name2(fixListRegex,"fixListRegex");function stripInsensitivities(s2){return s2.replace(/\./g,"").replace(spaceOrNBSPRegExp," ").toLowerCase()}__name(stripInsensitivities,"stripInsensitivities"),__name2(stripInsensitivities,"stripInsensitivities");function oneOf(strings,startIndex){return strings===null?null:{regex:RegExp(strings.map(fixListRegex).join("|")),deser:([s2])=>strings.findIndex(i=>stripInsensitivities(s2)===stripInsensitivities(i))+startIndex}}__name(oneOf,"oneOf"),__name2(oneOf,"oneOf");function offset$1(regex,groups){return{regex,deser:([,h,m])=>signedOffset(h,m),groups}}__name(offset$1,"offset$1"),__name2(offset$1,"offset$1");function simple(regex){return{regex,deser:([s2])=>s2}}__name(simple,"simple"),__name2(simple,"simple");function escapeToken(value){return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}__name(escapeToken,"escapeToken"),__name2(escapeToken,"escapeToken");function unitForToken(token,loc){const one=digitRegex(loc),two=digitRegex(loc,"{2}"),three=digitRegex(loc,"{3}"),four=digitRegex(loc,"{4}"),six=digitRegex(loc,"{6}"),oneOrTwo=digitRegex(loc,"{1,2}"),oneToThree=digitRegex(loc,"{1,3}"),oneToSix=digitRegex(loc,"{1,6}"),oneToNine=digitRegex(loc,"{1,9}"),twoToFour=digitRegex(loc,"{2,4}"),fourToSix=digitRegex(loc,"{4,6}"),literal2=__name2(t2=>({regex:RegExp(escapeToken(t2.val)),deser:([s2])=>s2,literal:!0}),"literal"),unit=__name2(t2=>{if(token.literal)return literal2(t2);switch(t2.val){case"G":return oneOf(loc.eras("short"),0);case"GG":return oneOf(loc.eras("long"),0);case"y":return intUnit(oneToSix);case"yy":return intUnit(twoToFour,untruncateYear);case"yyyy":return intUnit(four);case"yyyyy":return intUnit(fourToSix);case"yyyyyy":return intUnit(six);case"M":return intUnit(oneOrTwo);case"MM":return intUnit(two);case"MMM":return oneOf(loc.months("short",!0),1);case"MMMM":return oneOf(loc.months("long",!0),1);case"L":return intUnit(oneOrTwo);case"LL":return intUnit(two);case"LLL":return oneOf(loc.months("short",!1),1);case"LLLL":return oneOf(loc.months("long",!1),1);case"d":return intUnit(oneOrTwo);case"dd":return intUnit(two);case"o":return intUnit(oneToThree);case"ooo":return intUnit(three);case"HH":return intUnit(two);case"H":return intUnit(oneOrTwo);case"hh":return intUnit(two);case"h":return intUnit(oneOrTwo);case"mm":return intUnit(two);case"m":return intUnit(oneOrTwo);case"q":return intUnit(oneOrTwo);case"qq":return intUnit(two);case"s":return intUnit(oneOrTwo);case"ss":return intUnit(two);case"S":return intUnit(oneToThree);case"SSS":return intUnit(three);case"u":return simple(oneToNine);case"uu":return simple(oneOrTwo);case"uuu":return intUnit(one);case"a":return oneOf(loc.meridiems(),0);case"kkkk":return intUnit(four);case"kk":return intUnit(twoToFour,untruncateYear);case"W":return intUnit(oneOrTwo);case"WW":return intUnit(two);case"E":case"c":return intUnit(one);case"EEE":return oneOf(loc.weekdays("short",!1),1);case"EEEE":return oneOf(loc.weekdays("long",!1),1);case"ccc":return oneOf(loc.weekdays("short",!0),1);case"cccc":return oneOf(loc.weekdays("long",!0),1);case"Z":case"ZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`),2);case"ZZZ":return offset$1(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`),2);case"z":return simple(/[a-z_+-/]{1,256}?/i);case" ":return simple(/[^\S\n\r]/);default:return literal2(t2)}},"unitate")(token)||{invalidReason:MISSING_FTP};return unit.token=token,unit}__name(unitForToken,"unitForToken"),__name2(unitForToken,"unitForToken");const partTypeStyleToTokenVal={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function tokenForPart(part,formatOpts,resolvedOpts){const{type,value}=part;if(type==="literal"){const isSpace=/^\s+$/.test(value);return{literal:!isSpace,val:isSpace?" ":value}}const style=formatOpts[type];let actualType=type;type==="hour"&&(formatOpts.hour12!=null?actualType=formatOpts.hour12?"hour12":"hour24":formatOpts.hourCycle!=null?formatOpts.hourCycle==="h11"||formatOpts.hourCycle==="h12"?actualType="hour12":actualType="hour24":actualType=resolvedOpts.hour12?"hour12":"hour24");let val=partTypeStyleToTokenVal[actualType];if(typeof val=="object"&&(val=val[style]),val)return{literal:!1,val}}__name(tokenForPart,"tokenForPart"),__name2(tokenForPart,"tokenForPart");function buildRegex(units){return[`^${units.map(u=>u.regex).reduce((f,r)=>`${f}(${r.source})`,"")}$`,units]}__name(buildRegex,"buildRegex"),__name2(buildRegex,"buildRegex");function match(input,regex,handlers2){const matches2=input.match(regex);if(matches2){const all={};let matchIndex=1;for(const i in handlers2)if(hasOwnProperty(handlers2,i)){const h=handlers2[i],groups=h.groups?h.groups+1:1;!h.literal&&h.token&&(all[h.token.val[0]]=h.deser(matches2.slice(matchIndex,matchIndex+groups))),matchIndex+=groups}return[matches2,all]}else return[matches2,{}]}__name(match,"match"),__name2(match,"match");function dateTimeFromMatches(matches2){const toField=__name2(token=>{switch(token){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},"toField");let zone=null,specificOffset;return isUndefined(matches2.z)||(zone=IANAZone.create(matches2.z)),isUndefined(matches2.Z)||(zone||(zone=new FixedOffsetZone(matches2.Z)),specificOffset=matches2.Z),isUndefined(matches2.q)||(matches2.M=(matches2.q-1)*3+1),isUndefined(matches2.h)||(matches2.h<12&&matches2.a===1?matches2.h+=12:matches2.h===12&&matches2.a===0&&(matches2.h=0)),matches2.G===0&&matches2.y&&(matches2.y=-matches2.y),isUndefined(matches2.u)||(matches2.S=parseMillis(matches2.u)),[Object.keys(matches2).reduce((r,k)=>{const f=toField(k);return f&&(r[f]=matches2[k]),r},{}),zone,specificOffset]}__name(dateTimeFromMatches,"dateTimeFromMatches"),__name2(dateTimeFromMatches,"dateTimeFromMatches");let dummyDateTimeCache=null;function getDummyDateTime(){return dummyDateTimeCache||(dummyDateTimeCache=DateTime.fromMillis(1555555555555)),dummyDateTimeCache}__name(getDummyDateTime,"getDummyDateTime"),__name2(getDummyDateTime,"getDummyDateTime");function maybeExpandMacroToken(token,locale){if(token.literal)return token;const formatOpts=Formatter.macroTokenToFormatOpts(token.val),tokens=formatOptsToTokens(formatOpts,locale);return tokens==null||tokens.includes(void 0)?token:tokens}__name(maybeExpandMacroToken,"maybeExpandMacroToken"),__name2(maybeExpandMacroToken,"maybeExpandMacroToken");function expandMacroTokens(tokens,locale){return Array.prototype.concat(...tokens.map(t2=>maybeExpandMacroToken(t2,locale)))}__name(expandMacroTokens,"expandMacroTokens"),__name2(expandMacroTokens,"expandMacroTokens");function explainFromTokens(locale,input,format){const tokens=expandMacroTokens(Formatter.parseFormat(format),locale),units=tokens.map(t2=>unitForToken(t2,locale)),disqualifyingUnit=units.find(t2=>t2.invalidReason);if(disqualifyingUnit)return{input,tokens,invalidReason:disqualifyingUnit.invalidReason};{const[regexString,handlers2]=buildRegex(units),regex=RegExp(regexString,"i"),[rawMatches,matches2]=match(input,regex,handlers2),[result,zone,specificOffset]=matches2?dateTimeFromMatches(matches2):[null,null,void 0];if(hasOwnProperty(matches2,"a")&&hasOwnProperty(matches2,"H"))throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");return{input,tokens,regex,rawMatches,matches:matches2,result,zone,specificOffset}}}__name(explainFromTokens,"explainFromTokens"),__name2(explainFromTokens,"explainFromTokens");function parseFromTokens(locale,input,format){const{result,zone,specificOffset,invalidReason}=explainFromTokens(locale,input,format);return[result,zone,specificOffset,invalidReason]}__name(parseFromTokens,"parseFromTokens"),__name2(parseFromTokens,"parseFromTokens");function formatOptsToTokens(formatOpts,locale){if(!formatOpts)return null;const df=Formatter.create(locale,formatOpts).dtFormatter(getDummyDateTime()),parts=df.formatToParts(),resolvedOpts=df.resolvedOptions();return parts.map(p=>tokenForPart(p,formatOpts,resolvedOpts))}__name(formatOptsToTokens,"formatOptsToTokens"),__name2(formatOptsToTokens,"formatOptsToTokens");const nonLeapLadder=[0,31,59,90,120,151,181,212,243,273,304,334],leapLadder=[0,31,60,91,121,152,182,213,244,274,305,335];function unitOutOfRange(unit,value){return new Invalid("unit out of range",`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`)}__name(unitOutOfRange,"unitOutOfRange"),__name2(unitOutOfRange,"unitOutOfRange");function dayOfWeek(year,month,day){const d=new Date(Date.UTC(year,month-1,day));year<100&&year>=0&&d.setUTCFullYear(d.getUTCFullYear()-1900);const js=d.getUTCDay();return js===0?7:js}__name(dayOfWeek,"dayOfWeek"),__name2(dayOfWeek,"dayOfWeek");function computeOrdinal(year,month,day){return day+(isLeapYear(year)?leapLadder:nonLeapLadder)[month-1]}__name(computeOrdinal,"computeOrdinal"),__name2(computeOrdinal,"computeOrdinal");function uncomputeOrdinal(year,ordinal){const table=isLeapYear(year)?leapLadder:nonLeapLadder,month0=table.findIndex(i=>iweeksInWeekYear(year)?(weekYear=year+1,weekNumber=1):weekYear=year,{weekYear,weekNumber,weekday,...timeObject(gregObj)}}__name(gregorianToWeek,"gregorianToWeek"),__name2(gregorianToWeek,"gregorianToWeek");function weekToGregorian(weekData){const{weekYear,weekNumber,weekday}=weekData,weekdayOfJan4=dayOfWeek(weekYear,1,4),yearInDays=daysInYear(weekYear);let ordinal=weekNumber*7+weekday-weekdayOfJan4-3,year;ordinal<1?(year=weekYear-1,ordinal+=daysInYear(year)):ordinal>yearInDays?(year=weekYear+1,ordinal-=daysInYear(weekYear)):year=weekYear;const{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(weekData)}}__name(weekToGregorian,"weekToGregorian"),__name2(weekToGregorian,"weekToGregorian");function gregorianToOrdinal(gregData){const{year,month,day}=gregData,ordinal=computeOrdinal(year,month,day);return{year,ordinal,...timeObject(gregData)}}__name(gregorianToOrdinal,"gregorianToOrdinal"),__name2(gregorianToOrdinal,"gregorianToOrdinal");function ordinalToGregorian(ordinalData){const{year,ordinal}=ordinalData,{month,day}=uncomputeOrdinal(year,ordinal);return{year,month,day,...timeObject(ordinalData)}}__name(ordinalToGregorian,"ordinalToGregorian"),__name2(ordinalToGregorian,"ordinalToGregorian");function hasInvalidWeekData(obj){const validYear=isInteger(obj.weekYear),validWeek=integerBetween(obj.weekNumber,1,weeksInWeekYear(obj.weekYear)),validWeekday=integerBetween(obj.weekday,1,7);return validYear?validWeek?validWeekday?!1:unitOutOfRange("weekday",obj.weekday):unitOutOfRange("week",obj.week):unitOutOfRange("weekYear",obj.weekYear)}__name(hasInvalidWeekData,"hasInvalidWeekData"),__name2(hasInvalidWeekData,"hasInvalidWeekData");function hasInvalidOrdinalData(obj){const validYear=isInteger(obj.year),validOrdinal=integerBetween(obj.ordinal,1,daysInYear(obj.year));return validYear?validOrdinal?!1:unitOutOfRange("ordinal",obj.ordinal):unitOutOfRange("year",obj.year)}__name(hasInvalidOrdinalData,"hasInvalidOrdinalData"),__name2(hasInvalidOrdinalData,"hasInvalidOrdinalData");function hasInvalidGregorianData(obj){const validYear=isInteger(obj.year),validMonth=integerBetween(obj.month,1,12),validDay=integerBetween(obj.day,1,daysInMonth(obj.year,obj.month));return validYear?validMonth?validDay?!1:unitOutOfRange("day",obj.day):unitOutOfRange("month",obj.month):unitOutOfRange("year",obj.year)}__name(hasInvalidGregorianData,"hasInvalidGregorianData"),__name2(hasInvalidGregorianData,"hasInvalidGregorianData");function hasInvalidTimeData(obj){const{hour,minute,second,millisecond}=obj,validHour=integerBetween(hour,0,23)||hour===24&&minute===0&&second===0&&millisecond===0,validMinute=integerBetween(minute,0,59),validSecond=integerBetween(second,0,59),validMillisecond=integerBetween(millisecond,0,999);return validHour?validMinute?validSecond?validMillisecond?!1:unitOutOfRange("millisecond",millisecond):unitOutOfRange("second",second):unitOutOfRange("minute",minute):unitOutOfRange("hour",hour)}__name(hasInvalidTimeData,"hasInvalidTimeData"),__name2(hasInvalidTimeData,"hasInvalidTimeData");const INVALID="Invalid DateTime",MAX_DATE=864e13;function unsupportedZone(zone){return new Invalid("unsupported zone",`the zone "${zone.name}" is not supported`)}__name(unsupportedZone,"unsupportedZone"),__name2(unsupportedZone,"unsupportedZone");function possiblyCachedWeekData(dt){return dt.weekData===null&&(dt.weekData=gregorianToWeek(dt.c)),dt.weekData}__name(possiblyCachedWeekData,"possiblyCachedWeekData"),__name2(possiblyCachedWeekData,"possiblyCachedWeekData");function clone(inst,alts){const current={ts:inst.ts,zone:inst.zone,c:inst.c,o:inst.o,loc:inst.loc,invalid:inst.invalid};return new DateTime({...current,...alts,old:current})}__name(clone,"clone"),__name2(clone,"clone");function fixOffset(localTS,o,tz){let utcGuess=localTS-o*60*1e3;const o2=tz.offset(utcGuess);if(o===o2)return[utcGuess,o];utcGuess-=(o2-o)*60*1e3;const o3=tz.offset(utcGuess);return o2===o3?[utcGuess,o2]:[localTS-Math.min(o2,o3)*60*1e3,Math.max(o2,o3)]}__name(fixOffset,"fixOffset"),__name2(fixOffset,"fixOffset");function tsToObj(ts,offset2){ts+=offset2*60*1e3;const d=new Date(ts);return{year:d.getUTCFullYear(),month:d.getUTCMonth()+1,day:d.getUTCDate(),hour:d.getUTCHours(),minute:d.getUTCMinutes(),second:d.getUTCSeconds(),millisecond:d.getUTCMilliseconds()}}__name(tsToObj,"tsToObj"),__name2(tsToObj,"tsToObj");function objToTS(obj,offset2,zone){return fixOffset(objToLocalTS(obj),offset2,zone)}__name(objToTS,"objToTS"),__name2(objToTS,"objToTS");function adjustTime(inst,dur){const oPre=inst.o,year=inst.c.year+Math.trunc(dur.years),month=inst.c.month+Math.trunc(dur.months)+Math.trunc(dur.quarters)*3,c={...inst.c,year,month,day:Math.min(inst.c.day,daysInMonth(year,month))+Math.trunc(dur.days)+Math.trunc(dur.weeks)*7},millisToAdd=Duration.fromObject({years:dur.years-Math.trunc(dur.years),quarters:dur.quarters-Math.trunc(dur.quarters),months:dur.months-Math.trunc(dur.months),weeks:dur.weeks-Math.trunc(dur.weeks),days:dur.days-Math.trunc(dur.days),hours:dur.hours,minutes:dur.minutes,seconds:dur.seconds,milliseconds:dur.milliseconds}).as("milliseconds"),localTS=objToLocalTS(c);let[ts,o]=fixOffset(localTS,oPre,inst.zone);return millisToAdd!==0&&(ts+=millisToAdd,o=inst.zone.offset(ts)),{ts,o}}__name(adjustTime,"adjustTime"),__name2(adjustTime,"adjustTime");function parseDataToDateTime(parsed,parsedZone,opts,format,text,specificOffset){const{setZone,zone}=opts;if(parsed&&Object.keys(parsed).length!==0||parsedZone){const interpretationZone=parsedZone||zone,inst=DateTime.fromObject(parsed,{...opts,zone:interpretationZone,specificOffset});return setZone?inst:inst.setZone(zone)}else return DateTime.invalid(new Invalid("unparsable",`the input "${text}" can't be parsed as ${format}`))}__name(parseDataToDateTime,"parseDataToDateTime"),__name2(parseDataToDateTime,"parseDataToDateTime");function toTechFormat(dt,format,allowZ=!0){return dt.isValid?Formatter.create(Locale.create("en-US"),{allowZ,forceSimple:!0}).formatDateTimeFromString(dt,format):null}__name(toTechFormat,"toTechFormat"),__name2(toTechFormat,"toTechFormat");function toISODate(o,extended){const longFormat=o.c.year>9999||o.c.year<0;let c="";return longFormat&&o.c.year>=0&&(c+="+"),c+=padStart(o.c.year,longFormat?6:4),extended?(c+="-",c+=padStart(o.c.month),c+="-",c+=padStart(o.c.day)):(c+=padStart(o.c.month),c+=padStart(o.c.day)),c}__name(toISODate,"toISODate"),__name2(toISODate,"toISODate");function toISOTime(o,extended,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone){let c=padStart(o.c.hour);return extended?(c+=":",c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=":")):c+=padStart(o.c.minute),(o.c.millisecond!==0||o.c.second!==0||!suppressSeconds)&&(c+=padStart(o.c.second),(o.c.millisecond!==0||!suppressMilliseconds)&&(c+=".",c+=padStart(o.c.millisecond,3))),includeOffset&&(o.isOffsetFixed&&o.offset===0&&!extendedZone?c+="Z":o.o<0?(c+="-",c+=padStart(Math.trunc(-o.o/60)),c+=":",c+=padStart(Math.trunc(-o.o%60))):(c+="+",c+=padStart(Math.trunc(o.o/60)),c+=":",c+=padStart(Math.trunc(o.o%60)))),extendedZone&&(c+="["+o.zone.ianaName+"]"),c}__name(toISOTime,"toISOTime"),__name2(toISOTime,"toISOTime");const defaultUnitValues={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},defaultWeekUnitValues={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},defaultOrdinalUnitValues={ordinal:1,hour:0,minute:0,second:0,millisecond:0},orderedUnits=["year","month","day","hour","minute","second","millisecond"],orderedWeekUnits=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],orderedOrdinalUnits=["year","ordinal","hour","minute","second","millisecond"];function normalizeUnit(unit){const normalized={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[unit.toLowerCase()];if(!normalized)throw new InvalidUnitError(unit);return normalized}__name(normalizeUnit,"normalizeUnit"),__name2(normalizeUnit,"normalizeUnit");function quickDT(obj,opts){const zone=normalizeZone(opts.zone,Settings.defaultZone),loc=Locale.fromObject(opts),tsNow=Settings.now();let ts,o;if(isUndefined(obj.year))ts=tsNow;else{for(const u of orderedUnits)isUndefined(obj[u])&&(obj[u]=defaultUnitValues[u]);const invalid=hasInvalidGregorianData(obj)||hasInvalidTimeData(obj);if(invalid)return DateTime.invalid(invalid);const offsetProvis=zone.offset(tsNow);[ts,o]=objToTS(obj,offsetProvis,zone)}return new DateTime({ts,zone,loc,o})}__name(quickDT,"quickDT"),__name2(quickDT,"quickDT");function diffRelative(start,end,opts){const round=isUndefined(opts.round)?!0:opts.round,format=__name2((c,unit)=>(c=roundTo(c,round||opts.calendary?0:2,!0),end.loc.clone(opts).relFormatter(opts).format(c,unit)),"format"),differ=__name2(unit=>opts.calendary?end.hasSame(start,unit)?0:end.startOf(unit).diff(start.startOf(unit),unit).get(unit):end.diff(start,unit).get(unit),"differ");if(opts.unit)return format(differ(opts.unit),opts.unit);for(const unit of opts.units){const count=differ(unit);if(Math.abs(count)>=1)return format(count,unit)}return format(start>end?-0:0,opts.units[opts.units.length-1])}__name(diffRelative,"diffRelative"),__name2(diffRelative,"diffRelative");function lastOpts(argList){let opts={},args;return argList.length>0&&typeof argList[argList.length-1]=="object"?(opts=argList[argList.length-1],args=Array.from(argList).slice(0,argList.length-1)):args=Array.from(argList),[opts,args]}__name(lastOpts,"lastOpts"),__name2(lastOpts,"lastOpts");const _DateTime=class _DateTime2{static{__name(this,"_DateTime")}constructor(config2){const zone=config2.zone||Settings.defaultZone;let invalid=config2.invalid||(Number.isNaN(config2.ts)?new Invalid("invalid input"):null)||(zone.isValid?null:unsupportedZone(zone));this.ts=isUndefined(config2.ts)?Settings.now():config2.ts;let c=null,o=null;if(!invalid)if(config2.old&&config2.old.ts===this.ts&&config2.old.zone.equals(zone))[c,o]=[config2.old.c,config2.old.o];else{const ot=zone.offset(this.ts);c=tsToObj(this.ts,ot),invalid=Number.isNaN(c.year)?new Invalid("invalid input"):null,c=invalid?null:c,o=invalid?null:ot}this._zone=zone,this.loc=config2.loc||Locale.create(),this.invalid=invalid,this.weekData=null,this.c=c,this.o=o,this.isLuxonDateTime=!0}static now(){return new _DateTime2({})}static local(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return quickDT({year,month,day,hour,minute,second,millisecond},opts)}static utc(){const[opts,args]=lastOpts(arguments),[year,month,day,hour,minute,second,millisecond]=args;return opts.zone=FixedOffsetZone.utcInstance,quickDT({year,month,day,hour,minute,second,millisecond},opts)}static fromJSDate(date,options={}){const ts=isDate(date)?date.valueOf():NaN;if(Number.isNaN(ts))return _DateTime2.invalid("invalid input");const zoneToUse=normalizeZone(options.zone,Settings.defaultZone);return zoneToUse.isValid?new _DateTime2({ts,zone:zoneToUse,loc:Locale.fromObject(options)}):_DateTime2.invalid(unsupportedZone(zoneToUse))}static fromMillis(milliseconds,options={}){if(isNumber(milliseconds))return milliseconds<-MAX_DATE||milliseconds>MAX_DATE?_DateTime2.invalid("Timestamp out of range"):new _DateTime2({ts:milliseconds,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`)}static fromSeconds(seconds,options={}){if(isNumber(seconds))return new _DateTime2({ts:seconds*1e3,zone:normalizeZone(options.zone,Settings.defaultZone),loc:Locale.fromObject(options)});throw new InvalidArgumentError("fromSeconds requires a numerical input")}static fromObject(obj,opts={}){obj=obj||{};const zoneToUse=normalizeZone(opts.zone,Settings.defaultZone);if(!zoneToUse.isValid)return _DateTime2.invalid(unsupportedZone(zoneToUse));const tsNow=Settings.now(),offsetProvis=isUndefined(opts.specificOffset)?zoneToUse.offset(tsNow):opts.specificOffset,normalized=normalizeObject(obj,normalizeUnit),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber,loc=Locale.fromObject(opts);if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");const useWeekData=definiteWeekDef||normalized.weekday&&!containsGregor;let units,defaultValues,objNow=tsToObj(tsNow,offsetProvis);useWeekData?(units=orderedWeekUnits,defaultValues=defaultWeekUnitValues,objNow=gregorianToWeek(objNow)):containsOrdinal?(units=orderedOrdinalUnits,defaultValues=defaultOrdinalUnitValues,objNow=gregorianToOrdinal(objNow)):(units=orderedUnits,defaultValues=defaultUnitValues);let foundFirst=!1;for(const u of units){const v=normalized[u];isUndefined(v)?foundFirst?normalized[u]=defaultValues[u]:normalized[u]=objNow[u]:foundFirst=!0}const higherOrderInvalid=useWeekData?hasInvalidWeekData(normalized):containsOrdinal?hasInvalidOrdinalData(normalized):hasInvalidGregorianData(normalized),invalid=higherOrderInvalid||hasInvalidTimeData(normalized);if(invalid)return _DateTime2.invalid(invalid);const gregorian=useWeekData?weekToGregorian(normalized):containsOrdinal?ordinalToGregorian(normalized):normalized,[tsFinal,offsetFinal]=objToTS(gregorian,offsetProvis,zoneToUse),inst=new _DateTime2({ts:tsFinal,zone:zoneToUse,o:offsetFinal,loc});return normalized.weekday&&containsGregor&&obj.weekday!==inst.weekday?_DateTime2.invalid("mismatched weekday",`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`):inst}static fromISO(text,opts={}){const[vals,parsedZone]=parseISODate(text);return parseDataToDateTime(vals,parsedZone,opts,"ISO 8601",text)}static fromRFC2822(text,opts={}){const[vals,parsedZone]=parseRFC2822Date(text);return parseDataToDateTime(vals,parsedZone,opts,"RFC 2822",text)}static fromHTTP(text,opts={}){const[vals,parsedZone]=parseHTTPDate(text);return parseDataToDateTime(vals,parsedZone,opts,"HTTP",opts)}static fromFormat(text,fmt,opts={}){if(isUndefined(text)||isUndefined(fmt))throw new InvalidArgumentError("fromFormat requires an input string and a format");const{locale=null,numberingSystem=null}=opts,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0}),[vals,parsedZone,specificOffset,invalid]=parseFromTokens(localeToUse,text,fmt);return invalid?_DateTime2.invalid(invalid):parseDataToDateTime(vals,parsedZone,opts,`format ${fmt}`,text,specificOffset)}static fromString(text,fmt,opts={}){return _DateTime2.fromFormat(text,fmt,opts)}static fromSQL(text,opts={}){const[vals,parsedZone]=parseSQL(text);return parseDataToDateTime(vals,parsedZone,opts,"SQL",text)}static invalid(reason,explanation=null){if(!reason)throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");const invalid=reason instanceof Invalid?reason:new Invalid(reason,explanation);if(Settings.throwOnInvalid)throw new InvalidDateTimeError(invalid);return new _DateTime2({invalid})}static isDateTime(o){return o&&o.isLuxonDateTime||!1}static parseFormatForOpts(formatOpts,localeOpts={}){const tokenList=formatOptsToTokens(formatOpts,Locale.fromObject(localeOpts));return tokenList?tokenList.map(t2=>t2?t2.val:null).join(""):null}static expandFormat(fmt,localeOpts={}){return expandMacroTokens(Formatter.parseFormat(fmt),Locale.fromObject(localeOpts)).map(t2=>t2.val).join("")}get(unit){return this[unit]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?possiblyCachedWeekData(this).weekYear:NaN}get weekNumber(){return this.isValid?possiblyCachedWeekData(this).weekNumber:NaN}get weekday(){return this.isValid?possiblyCachedWeekData(this).weekday:NaN}get ordinal(){return this.isValid?gregorianToOrdinal(this.c).ordinal:NaN}get monthShort(){return this.isValid?Info.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Info.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Info.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Info.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const dayMs=864e5,minuteMs=6e4,localTS=objToLocalTS(this.c),oEarlier=this.zone.offset(localTS-dayMs),oLater=this.zone.offset(localTS+dayMs),o1=this.zone.offset(localTS-oEarlier*minuteMs),o2=this.zone.offset(localTS-oLater*minuteMs);if(o1===o2)return[this];const ts1=localTS-o1*minuteMs,ts2=localTS-o2*minuteMs,c1=tsToObj(ts1,o1),c2=tsToObj(ts2,o2);return c1.hour===c2.hour&&c1.minute===c2.minute&&c1.second===c2.second&&c1.millisecond===c2.millisecond?[clone(this,{ts:ts1}),clone(this,{ts:ts2})]:[this]}get isInLeapYear(){return isLeapYear(this.year)}get daysInMonth(){return daysInMonth(this.year,this.month)}get daysInYear(){return this.isValid?daysInYear(this.year):NaN}get weeksInWeekYear(){return this.isValid?weeksInWeekYear(this.weekYear):NaN}resolvedLocaleOptions(opts={}){const{locale,numberingSystem,calendar}=Formatter.create(this.loc.clone(opts),opts).resolvedOptions(this);return{locale,numberingSystem,outputCalendar:calendar}}toUTC(offset2=0,opts={}){return this.setZone(FixedOffsetZone.instance(offset2),opts)}toLocal(){return this.setZone(Settings.defaultZone)}setZone(zone,{keepLocalTime=!1,keepCalendarTime=!1}={}){if(zone=normalizeZone(zone,Settings.defaultZone),zone.equals(this.zone))return this;if(zone.isValid){let newTS=this.ts;if(keepLocalTime||keepCalendarTime){const offsetGuess=zone.offset(this.ts),asObj=this.toObject();[newTS]=objToTS(asObj,offsetGuess,zone)}return clone(this,{ts:newTS,zone})}else return _DateTime2.invalid(unsupportedZone(zone))}reconfigure({locale,numberingSystem,outputCalendar}={}){const loc=this.loc.clone({locale,numberingSystem,outputCalendar});return clone(this,{loc})}setLocale(locale){return this.reconfigure({locale})}set(values){if(!this.isValid)return this;const normalized=normalizeObject(values,normalizeUnit),settingWeekStuff=!isUndefined(normalized.weekYear)||!isUndefined(normalized.weekNumber)||!isUndefined(normalized.weekday),containsOrdinal=!isUndefined(normalized.ordinal),containsGregorYear=!isUndefined(normalized.year),containsGregorMD=!isUndefined(normalized.month)||!isUndefined(normalized.day),containsGregor=containsGregorYear||containsGregorMD,definiteWeekDef=normalized.weekYear||normalized.weekNumber;if((containsGregor||containsOrdinal)&&definiteWeekDef)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(containsGregorMD&&containsOrdinal)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");let mixed;settingWeekStuff?mixed=weekToGregorian({...gregorianToWeek(this.c),...normalized}):isUndefined(normalized.ordinal)?(mixed={...this.toObject(),...normalized},isUndefined(normalized.day)&&(mixed.day=Math.min(daysInMonth(mixed.year,mixed.month),mixed.day))):mixed=ordinalToGregorian({...gregorianToOrdinal(this.c),...normalized});const[ts,o]=objToTS(mixed,this.o,this.zone);return clone(this,{ts,o})}plus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration);return clone(this,adjustTime(this,dur))}minus(duration){if(!this.isValid)return this;const dur=Duration.fromDurationLike(duration).negate();return clone(this,adjustTime(this,dur))}startOf(unit){if(!this.isValid)return this;const o={},normalizedUnit=Duration.normalizeUnit(unit);switch(normalizedUnit){case"years":o.month=1;case"quarters":case"months":o.day=1;case"weeks":case"days":o.hour=0;case"hours":o.minute=0;case"minutes":o.second=0;case"seconds":o.millisecond=0;break}if(normalizedUnit==="weeks"&&(o.weekday=1),normalizedUnit==="quarters"){const q=Math.ceil(this.month/3);o.month=(q-1)*3+1}return this.set(o)}endOf(unit){return this.isValid?this.plus({[unit]:1}).startOf(unit).minus(1):this}toFormat(fmt,opts={}){return this.isValid?Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this,fmt):INVALID}toLocaleString(formatOpts=DATE_SHORT,opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),formatOpts).formatDateTime(this):INVALID}toLocaleParts(opts={}){return this.isValid?Formatter.create(this.loc.clone(opts),opts).formatDateTimeParts(this):[]}toISO({format="extended",suppressSeconds=!1,suppressMilliseconds=!1,includeOffset=!0,extendedZone=!1}={}){if(!this.isValid)return null;const ext=format==="extended";let c=toISODate(this,ext);return c+="T",c+=toISOTime(this,ext,suppressSeconds,suppressMilliseconds,includeOffset,extendedZone),c}toISODate({format="extended"}={}){return this.isValid?toISODate(this,format==="extended"):null}toISOWeekDate(){return toTechFormat(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds=!1,suppressSeconds=!1,includeOffset=!0,includePrefix=!1,extendedZone=!1,format="extended"}={}){return this.isValid?(includePrefix?"T":"")+toISOTime(this,format==="extended",suppressSeconds,suppressMilliseconds,includeOffset,extendedZone):null}toRFC2822(){return toTechFormat(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return toTechFormat(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?toISODate(this,!0):null}toSQLTime({includeOffset=!0,includeZone=!1,includeOffsetSpace=!0}={}){let fmt="HH:mm:ss.SSS";return(includeZone||includeOffset)&&(includeOffsetSpace&&(fmt+=" "),includeZone?fmt+="z":includeOffset&&(fmt+="ZZ")),toTechFormat(this,fmt,!0)}toSQL(opts={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(opts)}`:null}toString(){return this.isValid?this.toISO():INVALID}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(opts={}){if(!this.isValid)return{};const base2={...this.c};return opts.includeConfig&&(base2.outputCalendar=this.outputCalendar,base2.numberingSystem=this.loc.numberingSystem,base2.locale=this.loc.locale),base2}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(otherDateTime,unit="milliseconds",opts={}){if(!this.isValid||!otherDateTime.isValid)return Duration.invalid("created by diffing an invalid DateTime");const durOpts={locale:this.locale,numberingSystem:this.numberingSystem,...opts},units=maybeArray(unit).map(Duration.normalizeUnit),otherIsLater=otherDateTime.valueOf()>this.valueOf(),earlier=otherIsLater?this:otherDateTime,later=otherIsLater?otherDateTime:this,diffed=diff(earlier,later,units,durOpts);return otherIsLater?diffed.negate():diffed}diffNow(unit="milliseconds",opts={}){return this.diff(_DateTime2.now(),unit,opts)}until(otherDateTime){return this.isValid?Interval.fromDateTimes(this,otherDateTime):this}hasSame(otherDateTime,unit){if(!this.isValid)return!1;const inputMs=otherDateTime.valueOf(),adjustedToZone=this.setZone(otherDateTime.zone,{keepLocalTime:!0});return adjustedToZone.startOf(unit)<=inputMs&&inputMs<=adjustedToZone.endOf(unit)}equals(other){return this.isValid&&other.isValid&&this.valueOf()===other.valueOf()&&this.zone.equals(other.zone)&&this.loc.equals(other.loc)}toRelative(options={}){if(!this.isValid)return null;const base2=options.base||_DateTime2.fromObject({},{zone:this.zone}),padding=options.padding?thisi.valueOf(),Math.min)}static max(...dateTimes){if(!dateTimes.every(_DateTime2.isDateTime))throw new InvalidArgumentError("max requires all arguments be DateTimes");return bestBy(dateTimes,i=>i.valueOf(),Math.max)}static fromFormatExplain(text,fmt,options={}){const{locale=null,numberingSystem=null}=options,localeToUse=Locale.fromOpts({locale,numberingSystem,defaultToEN:!0});return explainFromTokens(localeToUse,text,fmt)}static fromStringExplain(text,fmt,options={}){return _DateTime2.fromFormatExplain(text,fmt,options)}static get DATE_SHORT(){return DATE_SHORT}static get DATE_MED(){return DATE_MED}static get DATE_MED_WITH_WEEKDAY(){return DATE_MED_WITH_WEEKDAY}static get DATE_FULL(){return DATE_FULL}static get DATE_HUGE(){return DATE_HUGE}static get TIME_SIMPLE(){return TIME_SIMPLE}static get TIME_WITH_SECONDS(){return TIME_WITH_SECONDS}static get TIME_WITH_SHORT_OFFSET(){return TIME_WITH_SHORT_OFFSET}static get TIME_WITH_LONG_OFFSET(){return TIME_WITH_LONG_OFFSET}static get TIME_24_SIMPLE(){return TIME_24_SIMPLE}static get TIME_24_WITH_SECONDS(){return TIME_24_WITH_SECONDS}static get TIME_24_WITH_SHORT_OFFSET(){return TIME_24_WITH_SHORT_OFFSET}static get TIME_24_WITH_LONG_OFFSET(){return TIME_24_WITH_LONG_OFFSET}static get DATETIME_SHORT(){return DATETIME_SHORT}static get DATETIME_SHORT_WITH_SECONDS(){return DATETIME_SHORT_WITH_SECONDS}static get DATETIME_MED(){return DATETIME_MED}static get DATETIME_MED_WITH_SECONDS(){return DATETIME_MED_WITH_SECONDS}static get DATETIME_MED_WITH_WEEKDAY(){return DATETIME_MED_WITH_WEEKDAY}static get DATETIME_FULL(){return DATETIME_FULL}static get DATETIME_FULL_WITH_SECONDS(){return DATETIME_FULL_WITH_SECONDS}static get DATETIME_HUGE(){return DATETIME_HUGE}static get DATETIME_HUGE_WITH_SECONDS(){return DATETIME_HUGE_WITH_SECONDS}};__name2(_DateTime,"DateTime");let DateTime=_DateTime;function friendlyDateTime(dateTimeish){if(DateTime.isDateTime(dateTimeish))return dateTimeish;if(dateTimeish&&dateTimeish.valueOf&&isNumber(dateTimeish.valueOf()))return DateTime.fromJSDate(dateTimeish);if(dateTimeish&&typeof dateTimeish=="object")return DateTime.fromObject(dateTimeish);throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`)}__name(friendlyDateTime,"friendlyDateTime"),__name2(friendlyDateTime,"friendlyDateTime");const _Text=class _Text2{static{__name(this,"_Text")}lineAt(pos){if(pos<0||pos>this.length)throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);return this.lineInner(pos,!1,1,0)}line(n2){if(n2<1||n2>this.lines)throw new RangeError(`Invalid line number ${n2} in ${this.lines}-line document`);return this.lineInner(n2,!0,1,0)}replace(from,to,text){let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from,to=this.length){let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(dir=1){return new RawTextCursor(this,dir)}iterRange(from,to=this.length){return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(from==null)inner=this.iter();else{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)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(text.length==0)throw new RangeError("A document must have at least one line");return text.length==1&&!text[0]?_Text2.empty:text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[]))}};__name2(_Text,"Text");let Text=_Text;const _TextLeaf=class _TextLeaf2 extends Text{static{__name(this,"_TextLeaf")}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,offset2){for(let i=0;;i++){let string2=this.text[i],end=offset2+string2.length;if((isLine?line:end)>=target)return new Line(offset2,end,line,string2);offset2=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new _TextLeaf2(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(open&1){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new _TextLeaf2(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new _TextLeaf2(joined.slice(0,mid)),new _TextLeaf2(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof _TextLeaf2))return super.replace(from,to,text);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new _TextLeaf2(lines,newLen):TextNode.from(_TextLeaf2.split(lines,[]),newLen)}sliceString(from,to=this.length,lineSep=` `){let result="";for(let pos=0,i=0;pos<=to&&ifrom&&i&&(result+=lineSep),frompos&&(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,part.length==32&&(target.push(new _TextLeaf2(part,len)),part=[],len=-1);return len>-1&&target.push(new _TextLeaf2(part,len)),target}};__name2(_TextLeaf,"TextLeaf");let TextLeaf=_TextLeaf;const _TextNode=class _TextNode2 extends Text{static{__name(this,"_TextNode")}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,offset2){for(let i=0;;i++){let child=this.children[i],end=offset2+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset2);offset2=end+1,line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));pos>=from&&end<=to&&!childOpen?target.push(child):child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if(text.lines=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text),totalLines=this.lines-child.lines+updated.lines;if(updated.lines>5-1&&updated.lines>totalLines>>5+1){let copy=this.children.slice();return copy[i]=updated,new _TextNode2(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=` `){let result="";for(let i=0,pos=0;ifrom&&i&&(result+=lineSep),frompos&&(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 _TextNode2))return 0;let length=0,[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((l2,ch)=>l2+ch.length+1,-1)){let lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1,chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add2(child){let last2;if(child.lines>maxChunk&&child instanceof _TextNode2)for(let node of child.children)add2(node);else child.lines>minChunk&&(currentLines>minChunk||!currentLines)?(flush(),chunked.push(child)):child instanceof TextLeaf&¤tLines&&(last2=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last2.lines<=32?(currentLines+=child.lines,currentLen+=child.length+1,currentChunk[currentChunk.length-1]=new TextLeaf(last2.text.concat(child.text),last2.length+1+child.length)):(currentLines+child.lines>chunk&&flush(),currentLines+=child.lines,currentLen+=child.length+1,currentChunk.push(child))}__name(add2,"add2"),__name2(add2,"add");function flush(){currentLines!=0&&(chunked.push(currentChunk.length==1?currentChunk[0]:_TextNode2.from(currentChunk,currentLen)),currentLen=-1,currentLines=currentChunk.length=0)}__name(flush,"flush"),__name2(flush,"flush");for(let child of children)add2(child);return flush(),chunked.length==1?chunked[0]:new _TextNode2(chunked,length)}};__name2(_TextNode,"TextNode");let TextNode=_TextNode;Text.empty=new TextLeaf([""],0);function textLength(text){let length=-1;for(let line of text)length+=line.length+1;return length}__name(textLength,"textLength"),__name2(textLength,"textLength");function appendText(text,target,from=0,to=1e9){for(let pos=0,i=0,first=!0;i=from&&(end>to&&(line=line.slice(0,to-pos)),pos0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){for(this.done=this.lineBreak=!1;;){let last2=this.nodes.length-1,top2=this.nodes[last2],offsetValue=this.offsets[last2],offset2=offsetValue>>1,size=top2 instanceof TextLeaf?top2.text.length:top2.children.length;if(offset2==(dir>0?size:0)){if(last2==0)return this.done=!0,this.value="",this;dir>0&&this.offsets[last2-1]++,this.nodes.pop(),this.offsets.pop()}else if((offsetValue&1)==(dir>0?0:1)){if(this.offsets[last2]+=dir,skip==0)return this.lineBreak=!0,this.value=` `,this;skip--}else if(top2 instanceof TextLeaf){let next=top2.text[offset2+(dir<0?-1:0)];if(this.offsets[last2]+=dir,next.length>Math.max(0,skip))return this.value=skip==0?next:dir>0?next.slice(skip):next.slice(0,next.length-skip),this;skip-=next.length}else{let next=top2.children[offset2+(dir<0?-1:0)];skip>next.length?(skip-=next.length,this.offsets[last2]+=dir):(dir<0&&this.offsets[last2]--,this.nodes.push(next),this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1))}}}next(skip=0){return skip<0&&(this.nextInner(-skip,-this.dir),skip=this.value.length),this.nextInner(skip,this.dir)}};__name2(_RawTextCursor,"RawTextCursor");let RawTextCursor=_RawTextCursor;const _PartialTextCursor=class{static{__name(this,"_PartialTextCursor")}constructor(text,start,end){this.value="",this.done=!1,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)return this.value="",this.done=!0,this;skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit2=dir<0?this.pos-this.from:this.to-this.pos;skip>limit2&&(skip=limit2),limit2-=skip;let{value}=this.cursor.next(skip);return this.pos+=(value.length+skip)*dir,this.value=value.length<=limit2?value:dir<0?value.slice(value.length-limit2):value.slice(0,limit2),this.done=!this.value,this}next(skip=0){return skip<0?skip=Math.max(skip,this.from-this.pos):skip>0&&(skip=Math.min(skip,this.to-this.pos)),this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}};__name2(_PartialTextCursor,"PartialTextCursor");let PartialTextCursor=_PartialTextCursor;const _LineCursor=class{static{__name(this,"_LineCursor")}constructor(inner){this.inner=inner,this.afterBreak=!0,this.value="",this.done=!1}next(skip=0){let{done,lineBreak,value}=this.inner.next(skip);return done?(this.done=!0,this.value=""):lineBreak?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=value,this.afterBreak=!1),this}get lineBreak(){return!1}};__name2(_LineCursor,"LineCursor");let LineCursor=_LineCursor;typeof Symbol<"u"&&(Text.prototype[Symbol.iterator]=function(){return this.iter()},RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this});const _Line=class{static{__name(this,"_Line")}constructor(from,to,number2,text){this.from=from,this.to=to,this.number=number2,this.text=text}get length(){return this.to-this.from}};__name2(_Line,"Line");let Line=_Line,extend="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(s2=>s2?parseInt(s2,36):1);for(let i=1;icode)return extend[i-1]<=code;return!1}__name(isExtendingChar,"isExtendingChar"),__name2(isExtendingChar,"isExtendingChar");function isRegionalIndicator(code){return code>=127462&&code<=127487}__name(isRegionalIndicator,"isRegionalIndicator"),__name2(isRegionalIndicator,"isRegionalIndicator");const ZWJ=8205;function findClusterBreak(str,pos,forward=!0,includeExtending=!0){return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}__name(findClusterBreak,"findClusterBreak"),__name2(findClusterBreak,"findClusterBreak");function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1))&&pos--;let prev=codePointAt(str,pos);for(pos+=codePointSize(prev);pos=0&&isRegionalIndicator(codePointAt(str,i));)countBefore++,i-=2;if(countBefore%2==0)break;pos+=2}else break}return pos}__name(nextClusterBreak,"nextClusterBreak"),__name2(nextClusterBreak,"nextClusterBreak");function prevClusterBreak(str,pos,includeExtending){for(;pos>0;){let found=nextClusterBreak(str,pos-2,includeExtending);if(found=56320&&ch<57344}__name(surrogateLow,"surrogateLow"),__name2(surrogateLow,"surrogateLow");function surrogateHigh(ch){return ch>=55296&&ch<56320}__name(surrogateHigh,"surrogateHigh"),__name2(surrogateHigh,"surrogateHigh");function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);return surrogateLow(code1)?(code0-55296<<10)+(code1-56320)+65536:code0}__name(codePointAt,"codePointAt"),__name2(codePointAt,"codePointAt");function fromCodePoint(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode((code>>10)+55296,(code&1023)+56320))}__name(fromCodePoint,"fromCodePoint"),__name2(fromCodePoint,"fromCodePoint");function codePointSize(code){return code<65536?1:2}__name(codePointSize,"codePointSize"),__name2(codePointSize,"codePointSize");const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode2){return MapMode2[MapMode2.Simple=0]="Simple",MapMode2[MapMode2.TrackDel=1]="TrackDel",MapMode2[MapMode2.TrackBefore=2]="TrackBefore",MapMode2[MapMode2.TrackAfter=3]="TrackAfter",MapMode2}(MapMode||(MapMode={}));const _ChangeDesc=class _ChangeDesc2{static{__name(this,"_ChangeDesc")}constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;ipos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posApos||mode==MapMode.TrackBefore&&posApos))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}touchesRange(from,to=from){for(let i=0,pos=0;i=0&&pos<=to&&end>=from)return posto?"cover":!0;pos=end}return!1}toString(){let result="";for(let i=0;i=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json2){if(!Array.isArray(json2)||json2.length%2||json2.some(a=>typeof a!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new _ChangeDesc2(json2)}static create(sections){return new _ChangeDesc2(sections)}};__name2(_ChangeDesc,"ChangeDesc");let ChangeDesc=_ChangeDesc;const _ChangeSet=class _ChangeSet2 extends ChangeDesc{static{__name(this,"_ChangeSet")}constructor(sections,inserted){super(sections),this.inserted=inserted}apply(doc2){if(this.length!=doc2.length)throw new RangeError("Applying change set to a document with the wrong length");return iterChanges(this,(fromA,toA,fromB,_toB,text)=>doc2=doc2.replace(fromB,fromB+(toA-fromA),text),!1),doc2}mapDesc(other,before=!1){return mapSet(this,other,before,!0)}invert(doc2){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i=0){sections[i]=ins,sections[i+1]=len;let index2=i>>1;for(;inserted.length0&&addInsert(resultInserted,resultSections,iter.text),iter.forward(len),pos+=len}let end=ranges[i++];for(;pos>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0,total=null;function flush(force=!1){if(!force&&!sections.length)return;posto||from<0||to>length)throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);let insText=insert2?typeof insert2=="string"?Text.of(insert2.split(lineSep||DefaultSplit)):insert2:Text.empty,insLen=insText.length;if(from==to&&insLen==0)return;frompos&&addSection(sections,from-pos,-1),addSection(sections,to-from,insLen),addInsert(inserted,sections,insText),pos=to}}return __name(process2,"process2"),__name2(process2,"process"),process2(changes),flush(!total),total}static empty(length){return new _ChangeSet2(length?[length,-1]:[],[])}static fromJSON(json2){if(!Array.isArray(json2))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;ii2&&typeof e!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(part.length==1)sections.push(part[0],0);else{for(;inserted.length=0&&ins<=0&&ins==sections[last2+1]?sections[last2]+=len:len==0&§ions[last2]==0?sections[last2+1]+=ins:forceJoin?(sections[last2]+=len,sections[last2+1]+=ins):sections.push(len,ins)}__name(addSection,"addSection"),__name2(addSection,"addSection");function addInsert(values,sections,value){if(value.length==0)return;let index2=sections.length-2>>1;if(index2>1])),!(individual||i==desc.sections.length||desc.sections[i+1]<0);)len=desc.sections[i++],ins=desc.sections[i++];f(posA,endA,posB,endB,text),posA=endA,posB=endB}}}__name(iterChanges,"iterChanges"),__name2(iterChanges,"iterChanges");function mapSet(setA,setB,before,mkSet=!1){let sections=[],insert2=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;)if(a.ins==-1&&b.ins==-1){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=0&&inserted=0){let len=0,left=a.len;for(;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.lenlen||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen),a.forward2(len),b.forward(len)}}}}__name(composeSets,"composeSets"),__name2(composeSets,"composeSets");const _SectionIter=class{static{__name(this,"_SectionIter")}constructor(set){this.set=set,this.i=0,this.next()}next(){let{sections}=this.set;this.i>1;return index2>=inserted.length?Text.empty:inserted[index2]}textBit(len){let{inserted}=this.set,index2=this.i-2>>1;return index2>=inserted.length&&!len?Text.empty:inserted[index2].slice(this.off,len==null?void 0:this.off+len)}forward(len){len==this.len?this.next():(this.len-=len,this.off+=len)}forward2(len){this.ins==-1?this.forward(len):len==this.ins?this.next():(this.ins-=len,this.off+=len)}};__name2(_SectionIter,"SectionIter");let SectionIter=_SectionIter;const _SelectionRange=class _SelectionRange2{static{__name(this,"_SelectionRange")}constructor(from,to,flags){this.from=from,this.to=to,this.flags=flags}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let level=this.flags&3;return level==3?null:level}get goalColumn(){let value=this.flags>>5;return value==33554431?void 0:value}map(change,assoc=-1){let from,to;return this.empty?from=to=change.mapPos(this.from,assoc):(from=change.mapPos(this.from,1),to=change.mapPos(this.to,-1)),from==this.from&&to==this.to?this:new _SelectionRange2(from,to,this.flags)}extend(from,to=from){if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){return this.anchor==other.anchor&&this.head==other.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json2){if(!json2||typeof json2.anchor!="number"||typeof json2.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json2.anchor,json2.head)}static create(from,to,flags){return new _SelectionRange2(from,to,flags)}};__name2(_SelectionRange,"SelectionRange");let SelectionRange=_SelectionRange;const _EditorSelection=class _EditorSelection2{static{__name(this,"_EditorSelection")}constructor(ranges,mainIndex){this.ranges=ranges,this.mainIndex=mainIndex}map(change,assoc=-1){return change.empty?this:_EditorSelection2.create(this.ranges.map(r=>r.map(change,assoc)),this.mainIndex)}eq(other){if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return!1;for(let i=0;ir.toJSON()),main:this.mainIndex}}static fromJSON(json2){if(!json2||!Array.isArray(json2.ranges)||typeof json2.main!="number"||json2.main>=json2.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new _EditorSelection2(json2.ranges.map(r=>SelectionRange.fromJSON(r)),json2.main)}static single(anchor,head=anchor){return new _EditorSelection2([_EditorSelection2.range(anchor,head)],0)}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;ianchor?4:0)|flags)}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;irange.head?_EditorSelection2.range(to,from):_EditorSelection2.range(from,to))}}return new _EditorSelection2(ranges,mainIndex)}};__name2(_EditorSelection,"EditorSelection");let EditorSelection=_EditorSelection;function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}__name(checkSelection,"checkSelection"),__name2(checkSelection,"checkSelection");let nextID=0;const _Facet=class _Facet2{static{__name(this,"_Facet")}constructor(combine,compareInput,compare2,isStatic,enables){this.combine=combine,this.compareInput=compareInput,this.compare=compare2,this.isStatic=isStatic,this.id=nextID++,this.default=combine([]),this.extensions=typeof enables=="function"?enables(this):enables}static define(config2={}){return new _Facet2(config2.combine||(a=>a),config2.compareInput||((a,b)=>a===b),config2.compare||(config2.combine?(a,b)=>a===b:sameArray$1),!!config2.static,config2.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){return get||(get=__name2(x=>x,"get")),this.compute([field],state=>get(state.field(field)))}};__name2(_Facet,"Facet");let Facet=_Facet;function sameArray$1(a,b){return a==b||a.length==b.length&&a.every((e,i)=>e===b[i])}__name(sameArray$1,"sameArray$1"),__name2(sameArray$1,"sameArray$1");const _FacetProvider=class{static{__name(this,"_FacetProvider")}constructor(dependencies,facet,type,value){this.dependencies=dependencies,this.facet=facet,this.type=type,this.value=value,this.id=nextID++}dynamicSlot(addresses){var _a3;let getter=this.value,compare2=this.facet.compareInput,id=this.id,idx=addresses[id]>>1,multi=this.type==2,depDoc=!1,depSel=!1,depAddrs=[];for(let dep of this.dependencies)dep=="doc"?depDoc=!0:dep=="selection"?depSel=!0:((_a3=addresses[dep.id])!==null&&_a3!==void 0?_a3:1)&1||depAddrs.push(addresses[dep.id]);return{create(state){return state.values[idx]=getter(state),1},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],compare2):!compare2(newVal,state.values[idx]))return state.values[idx]=newVal,1}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=>dep instanceof Facet?oldState.facet(dep)===state.facet(dep):dep instanceof StateField?oldState.field(dep,!1)==state.field(dep,!1):!0)||(multi?compareArray(newVal=getter(state),oldVal,compare2):compare2(newVal=getter(state),oldVal)))return state.values[idx]=oldVal,0}else newVal=getter(state);return state.values[idx]=newVal,1}}}};__name2(_FacetProvider,"FacetProvider");let FacetProvider=_FacetProvider;function compareArray(a,b,compare2){if(a.length!=b.length)return!1;for(let i=0;iaddresses[p.id]),providerTypes=providers.map(p=>p.type),dynamic=providerAddrs.filter(p=>!(p&1)),idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;ia===b),config2);return config2.provide&&(field.provides=config2.provide(field)),field}create(state){let init=state.facet(initField).find(i=>i.field==this);return(init?.create||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>(state.values[idx]=this.create(state),1),update:(state,tr)=>{let oldVal=state.values[idx],value=this.updateF(oldVal,tr);return this.compareF(oldVal,value)?0:(state.values[idx]=value,1)},reconfigure:(state,oldState)=>oldState.config.address[this.id]!=null?(state.values[idx]=oldState.field(this),0):(state.values[idx]=this.create(state),1)}}init(create){return[this,initField.of({field:this,create})]}get extension(){return this}};__name2(_StateField,"StateField");let StateField=_StateField;const Prec_={lowest:4,low:3,default:2,high:1,highest:0};function prec(value){return ext=>new PrecExtension(ext,value)}__name(prec,"prec"),__name2(prec,"prec");const Prec={highest:prec(Prec_.highest),high:prec(Prec_.high),default:prec(Prec_.default),low:prec(Prec_.low),lowest:prec(Prec_.lowest)},_PrecExtension=class{static{__name(this,"_PrecExtension")}constructor(inner,prec2){this.inner=inner,this.prec=prec2}};__name2(_PrecExtension,"PrecExtension");let PrecExtension=_PrecExtension;const _Compartment=class _Compartment2{static{__name(this,"_Compartment")}of(ext){return new CompartmentInstance(this,ext)}reconfigure(content2){return _Compartment2.reconfigure.of({compartment:this,extension:content2})}get(state){return state.config.compartments.get(this)}};__name2(_Compartment,"Compartment");let Compartment=_Compartment;const _CompartmentInstance=class{static{__name(this,"_CompartmentInstance")}constructor(compartment,inner){this.compartment=compartment,this.inner=inner}};__name2(_CompartmentInstance,"CompartmentInstance");let CompartmentInstance=_CompartmentInstance;const _Configuration=class _Configuration2{static{__name(this,"_Configuration")}constructor(base2,compartments,dynamicSlots,address,staticValues,facets){for(this.base=base2,this.compartments=compartments,this.dynamicSlots=dynamicSlots,this.address=address,this.staticValues=staticValues,this.facets=facets,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(base2,compartments,oldState){let fields=[],facets=Object.create(null),newCompartments=new Map;for(let ext of flatten(base2,compartments,newCompartments))ext instanceof StateField?fields.push(ext):(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext);let address=Object.create(null),staticValues=[],dynamicSlots=[];for(let field of fields)address[field.id]=dynamicSlots.length<<1,dynamicSlots.push(a=>field.slot(a));let oldFacets=oldState?.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet,oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every(p=>p.type==0))if(address[facet.id]=staticValues.length<<1|1,sameArray$1(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)p.type==0?(address[p.id]=staticValues.length<<1|1,staticValues.push(p.value)):(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 _Configuration2(base2,newCompartments,dynamic,address,staticValues,facets)}};__name2(_Configuration,"Configuration");let Configuration=_Configuration;function flatten(extension,compartments,newCompartments){let result=[[],[],[],[],[]],seen=new Map;function inner(ext,prec2){let known=seen.get(ext);if(known!=null){if(known<=prec2)return;let found=result[known].indexOf(ext);found>-1&&result[known].splice(found,1),ext instanceof CompartmentInstance&&newCompartments.delete(ext.compartment)}if(seen.set(ext,prec2),Array.isArray(ext))for(let e of ext)inner(e,prec2);else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError("Duplicate use of compartment in extensions");let content2=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content2),inner(content2,prec2)}else if(ext instanceof PrecExtension)inner(ext.inner,ext.prec);else if(ext instanceof StateField)result[prec2].push(ext),ext.provides&&inner(ext.provides,prec2);else if(ext instanceof FacetProvider)result[prec2].push(ext),ext.facet.extensions&&inner(ext.facet.extensions,Prec_.default);else{let content2=ext.extension;if(!content2)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(content2,prec2)}}return __name(inner,"inner"),__name2(inner,"inner"),inner(extension,Prec_.default),result.reduce((a,b)=>a.concat(b))}__name(flatten,"flatten"),__name2(flatten,"flatten");function ensureAddr(state,addr){if(addr&1)return 2;let idx=addr>>1,status=state.status[idx];if(status==4)throw new Error("Cyclic dependency between fields and/or facets");if(status&2)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}__name(ensureAddr,"ensureAddr"),__name2(ensureAddr,"ensureAddr");function getAddr(state,addr){return addr&1?state.config.staticValues[addr>>1]:state.values[addr>>1]}__name(getAddr,"getAddr"),__name2(getAddr,"getAddr");const languageData=Facet.define(),allowMultipleSelections=Facet.define({combine:values=>values.some(v=>v),static:!0}),lineSeparator=Facet.define({combine:values=>values.length?values[0]:void 0,static:!0}),changeFilter=Facet.define(),transactionFilter=Facet.define(),transactionExtender=Facet.define(),readOnly=Facet.define({combine:values=>values.length?values[0]:!1}),_Annotation=class{static{__name(this,"_Annotation")}constructor(type,value){this.type=type,this.value=value}static define(){return new AnnotationType}};__name2(_Annotation,"Annotation");let Annotation=_Annotation;const _AnnotationType=class{static{__name(this,"_AnnotationType")}of(value){return new Annotation(this,value)}};__name2(_AnnotationType,"AnnotationType");let AnnotationType=_AnnotationType;const _StateEffectType=class{static{__name(this,"_StateEffectType")}constructor(map2){this.map=map2}of(value){return new StateEffect(this,value)}};__name2(_StateEffectType,"StateEffectType");let StateEffectType=_StateEffectType;const _StateEffect=class _StateEffect2{static{__name(this,"_StateEffect")}constructor(type,value){this.type=type,this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return mapped===void 0?void 0:mapped==this.value?this:new _StateEffect2(this.type,mapped)}is(type){return this.type==type}static define(spec={}){return new StateEffectType(spec.map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);mapped&&result.push(mapped)}return result}};__name2(_StateEffect,"StateEffect");let StateEffect=_StateEffect;StateEffect.reconfigure=StateEffect.define(),StateEffect.appendConfig=StateEffect.define();const _Transaction=class _Transaction2{static{__name(this,"_Transaction")}constructor(startState,changes,selection,effects,annotations,scrollIntoView2){this.startState=startState,this.changes=changes,this.selection=selection,this.effects=effects,this.annotations=annotations,this.scrollIntoView=scrollIntoView2,this._doc=null,this._state=null,selection&&checkSelection(selection,changes.newLength),annotations.some(a=>a.type==_Transaction2.time)||(this.annotations=annotations.concat(_Transaction2.time.of(Date.now())))}static create(startState,changes,selection,effects,annotations,scrollIntoView2){return new _Transaction2(startState,changes,selection,effects,annotations,scrollIntoView2)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(_Transaction2.userEvent);return!!(e&&(e==event||e.length>event.length&&e.slice(0,event.length)==event&&e[event.length]=="."))}};__name2(_Transaction,"Transaction");let Transaction=_Transaction;Transaction.time=Annotation.define(),Transaction.userEvent=Annotation.define(),Transaction.addToHistory=Annotation.define(),Transaction.remote=Annotation.define();function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA=a[iA]))from=a[iA++],to=a[iA++];else if(iB=0;i--){let filtered=filters[i](tr);filtered instanceof Transaction?tr=filtered:Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction?tr=filtered[0]:tr=resolveTransaction(state,asArray$2(filtered),!1)}return tr}__name(filterTransaction,"filterTransaction"),__name2(filterTransaction,"filterTransaction");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);extension&&Object.keys(extension).length&&(spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),!0))}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}__name(extendTransaction,"extendTransaction"),__name2(extendTransaction,"extendTransaction");const none$2=[];function asArray$2(value){return value==null?none$2:Array.isArray(value)?value:[value]}__name(asArray$2,"asArray$2"),__name2(asArray$2,"asArray$2");var CharCategory=function(CharCategory2){return CharCategory2[CharCategory2.Word=0]="Word",CharCategory2[CharCategory2.Space=1]="Space",CharCategory2[CharCategory2.Other=2]="Other",CharCategory2}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hasWordChar(str){if(wordChar)return wordChar.test(str);for(let i=0;i"\x80"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return!0}return!1}__name(hasWordChar,"hasWordChar"),__name2(hasWordChar,"hasWordChar");function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(hasWordChar(char))return CharCategory.Word;for(let i=0;i-1)return CharCategory.Word;return CharCategory.Other}}__name(makeCategorizer,"makeCategorizer"),__name2(makeCategorizer,"makeCategorizer");const _EditorState=class _EditorState2{static{__name(this,"_EditorState")}constructor(config2,doc2,selection,values,computeSlot,tr){this.config=config2,this.doc=doc2,this.selection=selection,this.values=values,this.status=config2.statusTemplate.slice(),this.computeSlot=computeSlot,tr&&(tr._state=this);for(let i=0;icompartments.set(key,val)),conf=null),compartments.set(effect.value.compartment,effect.value.extension)):effect.is(StateEffect.reconfigure)?(conf=null,base2=effect.value):effect.is(StateEffect.appendConfig)&&(conf=null,base2=asArray$2(base2).concat(effect.value));let startValues;conf?startValues=tr.startState.values.slice():(conf=Configuration.resolve(base2,compartments,this),startValues=new _EditorState2(conf,this.doc,this.selection,conf.dynamicSlots.map(()=>null),(state,slot)=>slot.reconfigure(state,this),null).values),new _EditorState2(conf,tr.newDoc,tr.newSelection,startValues,(state,slot)=>slot.update(state,tr),tr)}replaceSelection(text){return typeof text=="string"&&(text=this.toText(text)),this.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)}))}changeByRange(f){let sel=this.selection,result1=f(sel.ranges[0]),changes=this.changes(result1.changes),ranges=[result1.range],effects=asArray$2(result1.effects);for(let i=1;ifield.spec.fromJSON(value,state)))}}return _EditorState2.create({doc:json2.doc,selection:EditorSelection.fromJSON(json2.selection),extensions:config2.extensions?fieldInit.concat([config2.extensions]):fieldInit})}static create(config2={}){let configuration=Configuration.resolve(config2.extensions||[],new Map),doc2=config2.doc instanceof Text?config2.doc:Text.of((config2.doc||"").split(configuration.staticFacet(_EditorState2.lineSeparator)||DefaultSplit)),selection=config2.selection?config2.selection instanceof EditorSelection?config2.selection:EditorSelection.single(config2.selection.anchor,config2.selection.head):EditorSelection.single(0);return checkSelection(selection,doc2.length),configuration.staticFacet(allowMultipleSelections)||(selection=selection.asSingle()),new _EditorState2(configuration,doc2,selection,configuration.dynamicSlots.map(()=>null),(state,slot)=>slot.create(state),null)}get tabSize(){return this.facet(_EditorState2.tabSize)}get lineBreak(){return this.facet(_EditorState2.lineSeparator)||` `}get readOnly(){return this.facet(readOnly)}phrase(phrase2,...insert2){for(let map2 of this.facet(_EditorState2.phrases))if(Object.prototype.hasOwnProperty.call(map2,phrase2)){phrase2=map2[phrase2];break}return insert2.length&&(phrase2=phrase2.replace(/\$(\$|\d*)/g,(m,i)=>{if(i=="$")return"$";let n2=+(i||1);return!n2||n2>insert2.length?m:insert2[n2-1]})),phrase2}languageDataAt(name2,pos,side=-1){let values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name2)&&values.push(result[name2]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text,from,length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;endvalues.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=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])}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();function combineConfig(configs,defaults2,combine={}){let result={};for(let config2 of configs)for(let key of Object.keys(config2)){let value=config2[key],current=result[key];if(current===void 0)result[key]=value;else if(!(current===value||value===void 0))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 defaults2)result[key]===void 0&&(result[key]=defaults2[key]);return result}__name(combineConfig,"combineConfig"),__name2(combineConfig,"combineConfig");const _RangeValue=class{static{__name(this,"_RangeValue")}eq(other){return this==other}range(from,to=from){return Range$1.create(from,to,this)}};__name2(_RangeValue,"RangeValue");let RangeValue=_RangeValue;RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=(_a=class{static{__name(this,"_a")}constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new _a(from,to,value)}},__name2(_a,"Range"),_a);function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}__name(cmpRange,"cmpRange"),__name2(cmpRange,"cmpRange");const _Chunk=class _Chunk2{static{__name(this,"_Chunk")}constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}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,diff2=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff2>=0?lo:hi;diff2>=0?hi=mid:lo=mid+1}}between(offset2,from,to,f){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new _Chunk2(from,to,value,maxPoint):null,pos:newPos}}};__name2(_Chunk,"Chunk");let Chunk=_Chunk;const _RangeSet=class _RangeSet2{static{__name(this,"_RangeSet")}constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new _RangeSet2(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last2=this.chunk.length-1;return last2<0?0:Math.max(this.chunkEnd(last2),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index2){return this.chunkPos[index2]+this.chunk[index2].length}update(updateSpec){let{add:add2=[],sort:sort2=!1,filterFrom=0,filterTo=this.length}=updateSpec,filter2=updateSpec.filter;if(add2.length==0&&!filter2)return this;if(sort2&&(add2=add2.slice().sort(cmpRange)),this.isEmpty)return add2.length?_RangeSet2.of(add2):this;let cur2=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur2.value||i=0){let range=add2[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else cur2.rangeIndex==1&&cur2.chunkIndexthis.chunkEnd(cur2.chunkIndex)||filterTocur2.to||filterTo=start&&from<=start+chunk.length&&chunk.between(start,from-start,to-start,f)===!1)return}this.nextLayer.between(from,to,f)}}iter(from=0){return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets,from=0){return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator,minPointSize=-1){let a=oldSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),b=newSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator)),textDiff.empty&&textDiff.length==0&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets,from=0,to){to==null&&(to=1e9-1);let a=oldSets.filter(set=>!set.isEmpty&&newSets.indexOf(set)<0),b=newSets.filter(set=>!set.isEmpty&&oldSets.indexOf(set)<0);if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),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||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator,minPointSize=-1){let cursor=new SpanCursor(sets,null,minPointSize).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrompos&&(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()}}static of(ranges,sort2=!1){let build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort2?lazySort(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}};__name2(_RangeSet,"RangeSet");let RangeSet=_RangeSet;RangeSet.empty=new RangeSet([],[],null,-1);function lazySort(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur2}return ranges}__name(lazySort,"lazySort"),__name2(lazySort,"lazySort"),RangeSet.empty.nextLayer=RangeSet.empty;const _RangeSetBuilder=class _RangeSetBuilder2{static{__name(this,"_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,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new _RangeSetBuilder2)).add(from,to,value)}addInner(from,to,value){let diff2=from-this.lastTo||value.startSide-this.last.endSide;if(diff2<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return diff2<0?!1:(this.from.length==250&&this.finishChunk(!0),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),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last2=chunk.value.length-1;return this.last=chunk.value[last2],this.lastFrom=chunk.from[last2]+from,this.lastTo=chunk.to[last2]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}};__name2(_RangeSetBuilder,"RangeSetBuilder");let RangeSetBuilder=_RangeSetBuilder;function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i=this.minPoint)break}}setRangeIndex(index2){if(index2==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=minPoint&&heap.push(new LayerCursor(cur2,skip,minPoint,i));return heap.length==1?heap[0]:new _HeapCursor2(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos,side=-1e9){for(let cur2 of this.heap)cur2.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur2 of this.heap)cur2.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top2=this.heap[0];this.from=top2.from,this.to=top2.to,this.value=top2.value,this.rank=top2.rank,top2.value&&top2.next(),heapBubble(this.heap,0)}}};__name2(_HeapCursor,"HeapCursor");let HeapCursor=_HeapCursor;function heapBubble(heap,index2){for(let cur2=heap[index2];;){let childIndex=(index2<<1)+1;if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0&&(child=heap[childIndex+1],childIndex++),cur2.compare(child)<0)break;heap[childIndex]=cur2,heap[index2]=child,index2=childIndex}}__name(heapBubble,"heapBubble"),__name2(heapBubble,"heapBubble");const _SpanCursor=class{static{__name(this,"_SpanCursor")}constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos,side=-1e9){return 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(),this}forward(pos,side){for(;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(index2){remove$1(this.active,index2),remove$1(this.activeTo,index2),remove$1(this.activeRank,index2),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value,to,rank}=this.cursor;for(;i-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),trackOpen&&remove$1(trackOpen,a)}else if(this.cursor.value)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)this.addActive(trackOpen),this.cursor.next();else if(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0&&trackOpen[i]=0&&!(this.activeRank[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}};__name2(_SpanCursor,"SpanCursor");let SpanCursor=_SpanCursor;function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff2=a.to+dPos-b.to||a.endSide-b.endSide,end=diff2<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff2<=0&&a.next(),diff2>=0&&b.next()}}__name(compare,"compare"),__name2(compare,"compare");function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i=index2;i--)array[i+1]=array[i];array[index2]=value}__name(insert,"insert"),__name2(insert,"insert");function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i=col)return i;if(i==string2.length)break;n2+=string2.charCodeAt(i)==9?tabSize-n2%tabSize:1,i=findClusterBreak(string2,i)}return strict===!0?-1:string2.length}__name(findColumn,"findColumn"),__name2(findColumn,"findColumn");const C="\u037C",COUNT=typeof Symbol>"u"?"__"+C:Symbol.for(C),SET=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),top=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},_StyleModule=class{static{__name(this,"_StyleModule")}constructor(spec,options){this.rules=[];let{finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}__name(splitSelector,"splitSelector"),__name2(splitSelector,"splitSelector");function render(selectors,spec2,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&isAt[1]=="keyframes";if(isAt&&spec2==null)return target.push(selectors[0]+";");for(let prop in spec2){let value=spec2[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map(part=>selectors.map(sel=>part.replace(/&/,sel))).reduce((a,b)=>a.concat(b)),value,target);else if(value&&typeof value=="object"){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else value!=null&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,l2=>"-"+l2.toLowerCase())+": "+value+";")}(local.length||keyframes)&&target.push((finish&&!isAt&&!isKeyframes?selectors.map(finish):selectors).join(", ")+" {"+local.join(" ")+"}")}__name(render,"render"),__name2(render,"render");for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join(` `)}static newName(){let id=top[COUNT]||1;return top[COUNT]=id+1,C+id.toString(36)}static mount(root,modules,options){let set=root[SET],nonce=options&&options.nonce;set?nonce&&set.setNonce(nonce):set=new StyleSet(root,nonce),set.mount(Array.isArray(modules)?modules:[modules])}};__name2(_StyleModule,"StyleModule");let StyleModule=_StyleModule,adoptedSet=new Map;const _StyleSet=class{static{__name(this,"_StyleSet")}constructor(root,nonce){let doc2=root.ownerDocument||root,win=doc2.defaultView;if(!root.head&&root.adoptedStyleSheets&&win.CSSStyleSheet){let adopted=adoptedSet.get(doc2);if(adopted)return root.adoptedStyleSheets=[adopted.sheet,...root.adoptedStyleSheets],root[SET]=adopted;this.sheet=new win.CSSStyleSheet,root.adoptedStyleSheets=[this.sheet,...root.adoptedStyleSheets],adoptedSet.set(doc2,this)}else{this.styleTag=doc2.createElement("style"),nonce&&this.styleTag.setAttribute("nonce",nonce);let target=root.head||root;target.insertBefore(this.styleTag,target.firstChild)}this.modules=[],root[SET]=this}mount(modules){let sheet=this.sheet,pos=0,j=0;for(let i=0;i-1&&(this.modules.splice(index2,1),j--,index2=-1),index2==-1){if(this.modules.splice(j++,0,mod),sheet)for(let k=0;k",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mac=typeof navigator<"u"&&/Mac/.test(navigator.platform),ie$1=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(var i=1;i<=24;i++)base[i+111]="F"+i;for(var i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code in base)shift.hasOwnProperty(code)||(shift[code]=base[code]);function keyName(event){var ignoreKey=mac&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie$1&&event.shiftKey&&event.key&&event.key.length==1||event.key=="Unidentified",name2=!ignoreKey&&event.key||(event.shiftKey?shift:base)[event.keyCode]||event.key||"Unidentified";return name2=="Esc"&&(name2="Escape"),name2=="Del"&&(name2="Delete"),name2=="Left"&&(name2="ArrowLeft"),name2=="Up"&&(name2="ArrowUp"),name2=="Right"&&(name2="ArrowRight"),name2=="Down"&&(name2="ArrowDown"),name2}__name(keyName,"keyName"),__name2(keyName,"keyName");function getSelection(root){let target;return root.nodeType==11?target=root.getSelection?root:root.ownerDocument:target=root,target.getSelection()}__name(getSelection,"getSelection"),__name2(getSelection,"getSelection");function contains(dom,node){return node?dom==node||dom.contains(node.nodeType!=1?node.parentNode:node):!1}__name(contains,"contains"),__name2(contains,"contains");function deepActiveElement(doc2){let elt=doc2.activeElement;for(;elt&&elt.shadowRoot;)elt=elt.shadowRoot.activeElement;return elt}__name(deepActiveElement,"deepActiveElement"),__name2(deepActiveElement,"deepActiveElement");function hasSelection(dom,selection){if(!selection.anchorNode)return!1;try{return contains(dom,selection.anchorNode)}catch{return!1}}__name(hasSelection,"hasSelection"),__name2(hasSelection,"hasSelection");function clientRectsFor(dom){return dom.nodeType==3?textRange(dom,0,dom.nodeValue.length).getClientRects():dom.nodeType==1?dom.getClientRects():[]}__name(clientRectsFor,"clientRectsFor"),__name2(clientRectsFor,"clientRectsFor");function isEquivalentPosition(node,off2,targetNode,targetOff){return targetNode?scanFor(node,off2,targetNode,targetOff,-1)||scanFor(node,off2,targetNode,targetOff,1):!1}__name(isEquivalentPosition,"isEquivalentPosition"),__name2(isEquivalentPosition,"isEquivalentPosition");function domIndex(node){for(var index2=0;;index2++)if(node=node.previousSibling,!node)return index2}__name(domIndex,"domIndex"),__name2(domIndex,"domIndex");function scanFor(node,off2,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off2==targetOff)return!0;if(off2==(dir<0?0:maxOffset(node))){if(node.nodeName=="DIV")return!1;let parent=node.parentNode;if(!parent||parent.nodeType!=1)return!1;off2=domIndex(node)+(dir<0?0:1),node=parent}else if(node.nodeType==1){if(node=node.childNodes[off2+(dir<0?-1:0)],node.nodeType==1&&node.contentEditable=="false")return!1;off2=dir<0?maxOffset(node):0}else return!1}}__name(scanFor,"scanFor"),__name2(scanFor,"scanFor");function maxOffset(node){return node.nodeType==3?node.nodeValue.length:node.childNodes.length}__name(maxOffset,"maxOffset"),__name2(maxOffset,"maxOffset");function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}__name(flattenRect,"flattenRect"),__name2(flattenRect,"flattenRect");function windowRect(win){return{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}__name(windowRect,"windowRect"),__name2(windowRect,"windowRect");function scrollRectIntoView(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc2=dom.ownerDocument,win=doc2.defaultView||window;for(let cur2=dom,stop=!1;cur2&&!stop;)if(cur2.nodeType==1){let bounding,top2=cur2==doc2.body,scaleX=1,scaleY=1;if(top2)bounding=windowRect(win);else{if(/^(fixed|sticky)$/.test(getComputedStyle(cur2).position)&&(stop=!0),cur2.scrollHeight<=cur2.clientHeight&&cur2.scrollWidth<=cur2.clientWidth){cur2=cur2.assignedSlot||cur2.parentNode;continue}let rect2=cur2.getBoundingClientRect();scaleX=rect2.width/cur2.offsetWidth,scaleY=rect2.height/cur2.offsetHeight,bounding={left:rect2.left,right:rect2.left+cur2.clientWidth*scaleX,top:rect2.top,bottom:rect2.top+cur2.clientHeight*scaleY}}let moveX=0,moveY=0;if(y=="nearest")rect.top0&&rect.bottom>bounding.bottom+moveY&&(moveY=rect.bottom-bounding.bottom+moveY+yMargin)):rect.bottom>bounding.bottom&&(moveY=rect.bottom-bounding.bottom+yMargin,side<0&&rect.top-moveY0&&rect.right>bounding.right+moveX&&(moveX=rect.right-bounding.right+moveX+xMargin)):rect.right>bounding.right&&(moveX=rect.right-bounding.right+xMargin,side<0&&rect.leftcur2.clientHeight||cur2.scrollWidth>cur2.clientWidth)return cur2;cur2=cur2.assignedSlot||cur2.parentNode}else if(cur2.nodeType==11)cur2=cur2.host;else break;return null}__name(scrollableParent,"scrollableParent"),__name2(scrollableParent,"scrollableParent");const _DOMSelectionState=class{static{__name(this,"_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;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}};__name2(_DOMSelectionState,"DOMSelectionState");let DOMSelectionState=_DOMSelectionState,preventScrollSupported=null;function focusPreventScroll(dom){if(dom.setActive)return dom.setActive();if(preventScrollSupported)return dom.focus(preventScrollSupported);let stack=[];for(let cur2=dom;cur2&&(stack.push(cur2,cur2.scrollTop,cur2.scrollLeft),cur2!=cur2.ownerDocument);cur2=cur2.parentNode);if(dom.focus(preventScrollSupported==null?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),!preventScrollSupported){preventScrollSupported=!1;for(let i=0;iMath.max(1,elt.scrollHeight-elt.clientHeight-4)}__name(isScrolledToBottom,"isScrolledToBottom"),__name2(isScrolledToBottom,"isScrolledToBottom");const _DOMPos=class _DOMPos2{static{__name(this,"_DOMPos")}constructor(node,offset2,precise=!0){this.node=node,this.offset=offset2,this.precise=precise}static before(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom),precise)}static after(dom,precise){return new _DOMPos2(dom.parentNode,domIndex(dom)+1,precise)}};__name2(_DOMPos,"DOMPos");let DOMPos=_DOMPos;const noChildren=[],_ContentView=class _ContentView2{static{__name(this,"_ContentView")}constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(view){let pos=this.posAtStart;for(let child of this.children){if(child==view)return pos;pos+=child.length+child.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(view){return this.posBefore(view)+view.length}sync(view,track){if(this.flags&2){let parent=this.dom,prev=null,next;for(let child of this.children){if(child.flags&7){if(!child.dom&&(next=prev?prev.nextSibling:parent.firstChild)){let contentView=_ContentView2.get(next);(!contentView||!contentView.parent&&contentView.canReuseDOM(child))&&child.reuseDOM(next)}child.sync(view,track),child.flags&=-8}if(next=prev?prev.nextSibling:parent.firstChild,track&&!track.written&&track.node==parent&&next!=child.dom&&(track.written=!0),child.dom.parentNode==parent)for(;next&&next!=child.dom;)next=rm$1(next);else parent.insertBefore(child.dom,next);prev=child.dom}for(next=prev?prev.nextSibling:parent.firstChild,next&&track&&track.node==parent&&(track.written=!0);next;)next=rm$1(next)}else if(this.flags&1)for(let child of this.children)child.flags&7&&(child.sync(view,track),child.flags&=-8)}reuseDOM(_dom){}localPosFromDOM(node,offset2){let after;if(node==this.dom)after=this.dom.childNodes[offset2];else{let bias=maxOffset(node)==0?0:offset2==0?-1:1;for(;;){let parent=node.parentNode;if(parent==this.dom)break;bias==0&&parent.firstChild!=parent.lastChild&&(node==parent.firstChild?bias=-1:bias=1),node=parent}bias<0?after=node:after=node.nextSibling}if(after==this.dom.firstChild)return 0;for(;after&&!_ContentView2.get(after);)after=after.nextSibling;if(!after)return this.length;for(let i=0,pos=0;;i++){let child=this.children[i];if(child.dom==after)return pos;pos+=child.length+child.breakAfter}}domBoundsAround(from,to,offset2=0){let fromI=-1,fromStart=-1,toI=-1,toEnd=-1;for(let i=0,pos=offset2,prevEnd=offset2;ito)return child.domBoundsAround(from,to,pos);if(end>=from&&fromI==-1&&(fromI=i,fromStart=pos),pos>to&&child.dom.parentNode==this.dom){toI=i,toEnd=prevEnd;break}prevEnd=end,pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset2+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI=0?this.children[toI].dom:null}}markDirty(andParent=!1){this.flags|=2,this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList&&(parent.flags|=2),parent.flags&1)return;parent.flags|=1,childList=!1}}setParent(parent){this.parent!=parent&&(this.parent=parent,this.flags&7&&this.markParentsDirty(!0))}setDOM(dom){this.dom!=dom&&(this.dom&&(this.dom.cmView=null),this.dom=dom,dom.cmView=this)}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to,children=noChildren){this.markDirty();for(let i=from;ithis.pos||pos==this.pos&&(bias>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=pos-this.pos,this;let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}};__name2(_ChildCursor,"ChildCursor");let ChildCursor=_ChildCursor;function replaceRange(parent,fromI,fromOff,toI,toOff,insert2,breakAtStart,openStart,openEnd){let{children}=parent,before=children.length?children[fromI]:null,last2=insert2.length?insert2[insert2.length-1]:null,breakAtEnd=last2?last2.breakAfter:breakAtStart;if(!(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert2.length<2&&before.merge(fromOff,toOff,insert2.length?last2:null,fromOff==0,openStart,openEnd))){if(toI0&&(!breakAtStart&&insert2.length&&before.merge(fromOff,before.length,insert2[0],!1,openStart,0)?before.breakAfter=insert2.shift().breakAfter:(fromOff2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/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?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios,android:/Android\b/.test(nav.userAgent),webkit,safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:doc.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const MaxJoinLen=256,_TextView=class _TextView2 extends ContentView{static{__name(this,"_TextView")}constructor(text){super(),this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(view,track){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(track&&track.node==this.dom&&(track.written=!0),this.dom.nodeValue=this.text)}reuseDOM(dom){dom.nodeType==3&&this.createDOM(dom)}merge(from,to,source){return this.flags&8||source&&(!(source instanceof _TextView2)||this.length-(to-from)+source.length>MaxJoinLen||source.flags&8)?!1:(this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to),this.markDirty(),!0)}split(from){let result=new _TextView2(this.text.slice(from));return this.text=this.text.slice(0,from),this.markDirty(),result.flags|=this.flags&8,result}localPosFromDOM(node,offset2){return node==this.dom?offset2:offset2?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset2){return{from:offset2,to:offset2+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return textCoords(this.dom,pos,side)}};__name2(_TextView,"TextView");let TextView=_TextView;const _MarkView=class _MarkView2 extends ContentView{static{__name(this,"_MarkView")}constructor(mark,children=[],length=0){super(),this.mark=mark,this.children=children,this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){if(clearAttributes(dom),this.mark.class&&(dom.className=this.mark.class),this.mark.attrs)for(let name2 in this.mark.attrs)dom.setAttribute(name2,this.mark.attrs[name2]);return dom}canReuseDOM(other){return super.canReuseDOM(other)&&!((this.flags|other.flags)&8)}reuseDOM(node){node.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(node),this.flags|=6)}sync(view,track){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(view,track)}merge(from,to,source,_hasStart,openStart,openEnd){return source&&(!(source instanceof _MarkView2&&source.mark.eq(this.mark))||from&&openStart<=0||tofrom&&result.push(off2=from&&(detachFrom=i),off2=end,i++}let length=this.length-from;return this.length=from,detachFrom>-1&&(this.children.length=detachFrom,this.markDirty()),new _MarkView2(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}};__name2(_MarkView,"MarkView");let MarkView=_MarkView;function textCoords(text,pos,side){let length=text.nodeValue.length;pos>length&&(pos=length);let from=pos,to=pos,flatten2=0;pos==0&&side<0||pos==length&&side>=0?browser.chrome||browser.gecko||(pos?(from--,flatten2=1):to=0)?0:rects.length-1];return browser.safari&&!flatten2&&rect.width==0&&(rect=Array.prototype.find.call(rects,r=>r.width)||rect),flatten2?flattenRect(rect,flatten2<0):rect||null}__name(textCoords,"textCoords"),__name2(textCoords,"textCoords");const _WidgetView=class _WidgetView2 extends ContentView{static{__name(this,"_WidgetView")}static create(widget,length,side){return new _WidgetView2(widget,length,side)}constructor(widget,length,side){super(),this.widget=widget,this.length=length,this.side=side,this.prevWidget=null}split(from){let result=_WidgetView2.create(this.widget,this.length-from,this.side);return this.length-=from,result}sync(view){(!this.dom||!this.widget.updateDOM(this.dom,view))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.dom.contentEditable="false")}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){return source&&(!(source instanceof _WidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0)?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}domBoundsAround(){return null}coordsAt(pos,side){let custom=this.widget.coordsAt(this.dom,pos,side);if(custom)return custom;let rects=this.dom.getClientRects(),rect=null;if(!rects.length)return null;let fromBack=this.side?this.side<0:pos>0;for(let i=fromBack?rects.length-1:0;rect=rects[i],!(pos>0?i==0:i==rects.length-1||rect.top0?DOMPos.before(this.dom):DOMPos.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(pos){return this.dom.getBoundingClientRect()}get overrideDOMText(){return Text.empty}get isHidden(){return!0}};__name2(_WidgetBufferView,"WidgetBufferView");let WidgetBufferView=_WidgetBufferView;TextView.prototype.children=WidgetView.prototype.children=WidgetBufferView.prototype.children=noChildren;function inlineDOMAtPos(parent,pos){let dom=parent.dom,{children}=parent,i=0;for(let off2=0;ioff2&&pos0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j0&&view instanceof MarkView&&children.length&&(last2=children[children.length-1])instanceof MarkView&&last2.mark.eq(view.mark)?joinInlineInto(last2,view.children[0],open-1):(children.push(view),view.setParent(parent)),parent.length+=view.length}__name(joinInlineInto,"joinInlineInto"),__name2(joinInlineInto,"joinInlineInto");function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;function scan(view2,pos2){for(let i=0,off2=0;i=pos2&&(child.children.length?scan(child,pos2-off2):(!after||after.isHidden&&side>0)&&(end>pos2||off2==end&&child.getSide()>0)?(after=child,afterPos=pos2-off2):(off2-1?1:0)!=keysB.length-(ignore&&keysB.indexOf(ignore)>-1?1:0))return!1;for(let key of keysA)if(key!=ignore&&(keysB.indexOf(key)==-1||a[key]!==b[key]))return!1;return!0}__name(attrsEq,"attrsEq"),__name2(attrsEq,"attrsEq");function updateAttrs(dom,prev,attrs){let changed=!1;if(prev)for(let name2 in prev)attrs&&name2 in attrs||(changed=!0,name2=="style"?dom.style.cssText="":dom.removeAttribute(name2));if(attrs)for(let name2 in attrs)prev&&prev[name2]==attrs[name2]||(changed=!0,name2=="style"?dom.style.cssText=attrs[name2]:dom.setAttribute(name2,attrs[name2]));return changed}__name(updateAttrs,"updateAttrs"),__name2(updateAttrs,"updateAttrs");function getAttrs(dom){let attrs=Object.create(null);for(let i=0;i0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=at,end}transferDOM(other){this.dom&&(this.markDirty(),other.setDOM(this.dom),other.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(attrs){attrsEq(this.attrs,attrs)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=attrs)}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;attrs&&(this.attrs=combineAttrs(attrs,this.attrs||{})),cls&&(this.attrs=combineAttrs({class:cls},this.attrs||{}))}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){node.nodeName=="DIV"&&(this.setDOM(node),this.flags|=6)}sync(view,track){var _a3;this.dom?this.flags&4&&(clearAttributes(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(updateAttrs(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(view,track);let last2=this.dom.lastChild;for(;last2&&ContentView.get(last2)instanceof MarkView;)last2=last2.lastChild;if(!last2||!this.length||last2.nodeName!="BR"&&((_a3=ContentView.get(last2))===null||_a3===void 0?void 0:_a3.isEditable)==!1&&(!browser.ios||!this.children.some(ch=>ch instanceof TextView))){let hack=document.createElement("BR");hack.cmIgnore=!0,this.dom.appendChild(hack)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let totalWidth=0,textHeight;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(rects.length!=1)return null;totalWidth+=rects[0].width,textHeight=rects[0].height}return totalWidth?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length,textHeight}:null}coordsAt(pos,side){let rect=coordsInChildren(this,pos,side);if(!this.children.length&&rect&&this.parent){let{heightOracle}=this.parent.view.viewState,height=rect.bottom-rect.top;if(Math.abs(height-heightOracle.lineHeight)<2&&heightOracle.textHeight=pos){if(block instanceof _LineView2)return block;if(end>pos)break}off2=end+block.breakAfter}return null}};__name2(_LineView,"LineView");let LineView=_LineView;const _BlockWidgetView=class _BlockWidgetView2 extends ContentView{static{__name(this,"_BlockWidgetView")}constructor(widget,length,deco){super(),this.widget=widget,this.length=length,this.deco=deco,this.breakAfter=0,this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){return source&&(!(source instanceof _BlockWidgetView2)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0}};__name2(_BlockWidgetView,"BlockWidgetView");let BlockWidgetView=_BlockWidgetView;const _WidgetType=class{static{__name(this,"_WidgetType")}eq(widget){return!1}updateDOM(dom,view){return!1}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(event){return!0}coordsAt(dom,pos,side){return null}get isHidden(){return!1}destroy(dom){}};__name2(_WidgetType,"WidgetType");let WidgetType=_WidgetType;var BlockType=function(BlockType2){return BlockType2[BlockType2.Text=0]="Text",BlockType2[BlockType2.WidgetBefore=1]="WidgetBefore",BlockType2[BlockType2.WidgetAfter=2]="WidgetAfter",BlockType2[BlockType2.WidgetRange=3]="WidgetRange",BlockType2}(BlockType||(BlockType={}));const _Decoration=class extends RangeValue{static{__name(this,"_Decoration")}constructor(startSide,endSide,widget,spec){super(),this.startSide=startSide,this.endSide=endSide,this.widget=widget,this.spec=spec}get heightRelevant(){return!1}static mark(spec){return new MarkDecoration(spec)}static widget(spec){let side=Math.max(-1e4,Math.min(1e4,spec.side||0)),block=!!spec.block;return side+=block&&!spec.inlineOrder?side>0?3e8:-4e8:side>0?1e8:-1e8,new PointDecoration(spec,side,side,block,spec.widget||null,!1)}static replace(spec){let block=!!spec.block,startSide,endSide;if(spec.isBlockGap)startSide=-5e8,endSide=4e8;else{let{start,end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1,endSide=(end?block?2e8:1:-6e8)+1}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,!0)}static line(spec){return new LineDecoration(spec)}static set(of,sort2=!1){return RangeSet.of(of,sort2)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};__name2(_Decoration,"Decoration");let Decoration=_Decoration;Decoration.none=RangeSet.empty;const _MarkDecoration=class _MarkDecoration2 extends Decoration{static{__name(this,"_MarkDecoration")}constructor(spec){let{start,end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec),this.tagName=spec.tagName||"span",this.class=spec.class||"",this.attrs=spec.attributes||null}eq(other){var _a3,_b2;return this==other||other instanceof _MarkDecoration2&&this.tagName==other.tagName&&(this.class||((_a3=this.attrs)===null||_a3===void 0?void 0:_a3.class))==(other.class||((_b2=other.attrs)===null||_b2===void 0?void 0:_b2.class))&&attrsEq(this.attrs,other.attrs,"class")}range(from,to=from){if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}};__name2(_MarkDecoration,"MarkDecoration");let MarkDecoration=_MarkDecoration;MarkDecoration.prototype.point=!1;const _LineDecoration=class _LineDecoration2 extends Decoration{static{__name(this,"_LineDecoration")}constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof _LineDecoration2&&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)}};__name2(_LineDecoration,"LineDecoration");let LineDecoration=_LineDecoration;LineDecoration.prototype.mapMode=MapMode.TrackBefore,LineDecoration.prototype.point=!0;const _PointDecoration=class _PointDecoration2 extends Decoration{static{__name(this,"_PointDecoration")}constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec),this.block=block,this.isReplace=isReplace,this.mapMode=block?startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter:MapMode.TrackDel}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 _PointDecoration2&&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)}};__name2(_PointDecoration,"PointDecoration");let PointDecoration=_PointDecoration;PointDecoration.prototype.point=!0;function getInclusive(spec,block=!1){let{inclusiveStart:start,inclusiveEnd:end}=spec;return start==null&&(start=spec.inclusive),end==null&&(end=spec.inclusive),{start:start??block,end:end??block}}__name(getInclusive,"getInclusive"),__name2(getInclusive,"getInclusive");function widgetsEq(a,b){return a==b||!!(a&&b&&a.compare(b))}__name(widgetsEq,"widgetsEq"),__name2(widgetsEq,"widgetsEq");function addRange(from,to,ranges,margin=0){let last2=ranges.length-1;last2>=0&&ranges[last2]+margin>=from?ranges[last2]=Math.max(ranges[last2],to):ranges.push(from,to)}__name(addRange,"addRange"),__name2(addRange,"addRange");const _ContentBuilder=class _ContentBuilder2{static{__name(this,"_ContentBuilder")}constructor(doc2,pos,end,disallowBlockEffectsFor){this.doc=doc2,this.pos=pos,this.end=end,this.disallowBlockEffectsFor=disallowBlockEffectsFor,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=doc2.iter(),this.skip=pos}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last2=this.content[this.content.length-1];return!(last2.breakAfter||last2 instanceof BlockWidgetView&&last2.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new LineView),this.atCursorPos=!0),this.curLine}flushBuffer(active=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length),this.pendingBuffer=0)}addBlockWidget(view){this.flushBuffer(),this.curLine=null,this.content.push(view)}finish(openEnd){this.pendingBuffer&&openEnd<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(openEnd&&this.content.length&&this.content[this.content.length-1]instanceof BlockWidgetView)&&this.getLine()}buildText(length,active,openStart){for(;length>0;){if(this.textOff==this.text.length){let{value,lineBreak,done}=this.cursor.next(this.skip);if(this.skip=0,done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,length--;continue}else this.text=value,this.textOff=0}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(active.length-openStart)),this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart),this.atCursorPos=!0,this.textOff+=take,length-=take,openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart),this.pos=to,this.openStart<0&&(this.openStart=openStart)}point(from,to,deco,active,openStart,index2){if(this.disallowBlockEffectsFor[index2]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration)if(deco.block)deco.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new BlockWidgetView(deco.widget||new NullWidget("div"),len,deco));else{let view=WidgetView.create(deco.widget||new NullWidget("span"),len,len?0:deco.startSide),cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from0),cursorAfter=!view.isEditable&&(fromactive.length||deco.startSide<=0),line=this.getLine();this.pendingBuffer==2&&!cursorBefore&&!view.isEditable&&(this.pendingBuffer=0),this.flushBuffer(active),cursorBefore&&(line.append(wrapMarks(new WidgetBufferView(1),active),openStart),openStart=active.length+Math.max(0,openStart-active.length)),line.append(wrapMarks(view,active),openStart),this.atCursorPos=cursorAfter,this.pendingBuffer=cursorAfter?fromactive.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=active.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(deco);len&&(this.textOff+len<=this.text.length?this.textOff+=len:(this.skip+=len-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=to),this.openStart<0&&(this.openStart=openStart)}static build(text,from,to,decorations2,dynamicDecorationMap){let builder=new _ContentBuilder2(text,from,to,dynamicDecorationMap);return builder.openEnd=RangeSet.spans(decorations2,from,to,builder),builder.openStart<0&&(builder.openStart=builder.openEnd),builder.finish(builder.openEnd),builder}};__name2(_ContentBuilder,"ContentBuilder");let ContentBuilder=_ContentBuilder;function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view}__name(wrapMarks,"wrapMarks"),__name2(wrapMarks,"wrapMarks");const _NullWidget=class extends WidgetType{static{__name(this,"_NullWidget")}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!0}};__name2(_NullWidget,"NullWidget");let NullWidget=_NullWidget;const clickAddsSelectionRange=Facet.define(),dragMovesSelection$1=Facet.define(),mouseSelectionStyle=Facet.define(),exceptionSink=Facet.define(),updateListener=Facet.define(),inputHandler$1=Facet.define(),focusChangeEffect=Facet.define(),perLineTextDirection=Facet.define({combine:values=>values.some(x=>x)}),nativeSelectionHidden=Facet.define({combine:values=>values.some(x=>x)}),_ScrollTarget=class _ScrollTarget2{static{__name(this,"_ScrollTarget")}constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range,this.y=y,this.x=x,this.yMargin=yMargin,this.xMargin=xMargin}map(changes){return changes.empty?this:new _ScrollTarget2(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin)}};__name2(_ScrollTarget,"ScrollTarget");let ScrollTarget=_ScrollTarget;const scrollIntoView$1=StateEffect.define({map:(t2,ch)=>t2.map(ch)});function logException(state,exception,context){let handler=state.facet(exceptionSink);handler.length?handler[0](exception):window.onerror?window.onerror(String(exception),context,void 0,void 0,exception):context?console.error(context+":",exception):console.error(exception)}__name(logException,"logException"),__name2(logException,"logException");const editable=Facet.define({combine:values=>values.length?values[0]:!0});let nextPluginID=0;const viewPlugin=Facet.define(),_ViewPlugin=class _ViewPlugin2{static{__name(this,"_ViewPlugin")}constructor(id,create,domEventHandlers,domEventObservers,buildExtensions){this.id=id,this.create=create,this.domEventHandlers=domEventHandlers,this.domEventObservers=domEventObservers,this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers,eventObservers,provide,decorations:deco}=spec||{};return new _ViewPlugin2(nextPluginID++,create,eventHandlers,eventObservers,plugin=>{let ext=[viewPlugin.of(plugin)];return deco&&ext.push(decorations.of(view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none})),provide&&ext.push(provide(plugin)),ext})}static fromClass(cls,spec){return _ViewPlugin2.define(view=>new cls(view),spec)}};__name2(_ViewPlugin,"ViewPlugin");let ViewPlugin=_ViewPlugin;const _PluginInstance=class{static{__name(this,"_PluginInstance")}constructor(spec){this.spec=spec,this.mustUpdate=null,this.value=null}update(view){if(this.value){if(this.mustUpdate){let update=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(update)}catch(e){if(logException(update.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(view){var _a3;if(!((_a3=this.value)===null||_a3===void 0)&&_a3.destroy)try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}};__name2(_PluginInstance,"PluginInstance");let PluginInstance=_PluginInstance;const editorAttributes=Facet.define(),contentAttributes=Facet.define(),decorations=Facet.define(),atomicRanges=Facet.define(),bidiIsolatedRanges=Facet.define();function getIsolatedRanges(view,from,to){let isolates=view.state.facet(bidiIsolatedRanges);if(!isolates.length)return isolates;let sets=isolates.map(i=>i instanceof Function?i(view):i),result=[];return RangeSet.spans(sets,from,to,{point(){},span(from2,to2,active,open){let level=result;for(let i=active.length-1;i>=0;i--,open--){let iso=active[i].spec.bidiIsolate,update;if(iso!=null)if(open>0&&level.length&&(update=level[level.length-1]).to==from2&&update.direction==iso)update.to=to2,level=update.inner;else{let add2={from:from2,to:to2,direction:iso,inner:[]};level.push(add2),level=add2.inner}}}}),result}__name(getIsolatedRanges,"getIsolatedRanges"),__name2(getIsolatedRanges,"getIsolatedRanges");const scrollMargins=Facet.define();function getScrollMargins(view){let left=0,right=0,top2=0,bottom=0;for(let source of view.state.facet(scrollMargins)){let m=source(view);m&&(m.left!=null&&(left=Math.max(left,m.left)),m.right!=null&&(right=Math.max(right,m.right)),m.top!=null&&(top2=Math.max(top2,m.top)),m.bottom!=null&&(bottom=Math.max(bottom,m.bottom)))}return{left,right,top:top2,bottom}}__name(getScrollMargins,"getScrollMargins"),__name2(getScrollMargins,"getScrollMargins");const styleModule=Facet.define(),_ChangedRange=class _ChangedRange2{static{__name(this,"_ChangedRange")}constructor(fromA,toA,fromB,toB){this.fromA=fromA,this.toA=toA,this.fromB=fromB,this.toB=toB}join(other){return new _ChangedRange2(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)){if(range.toAend)break;rI+=2}if(!next)return result;new _ChangedRange2(next.fromA,next.toA,next.fromB,next.toB).addToSet(result),posA=next.toA,posB=next.toB}}};__name2(_ChangedRange,"ChangedRange");let ChangedRange=_ChangedRange;const _ViewUpdate=class _ViewUpdate2{static{__name(this,"_ViewUpdate")}constructor(view,state,transactions){this.view=view,this.state=state,this.transactions=transactions,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}static create(view,state,transactions){return new _ViewUpdate2(view,state,transactions)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(tr=>tr.selection)}get empty(){return this.flags==0&&this.transactions.length==0}};__name2(_ViewUpdate,"ViewUpdate");let ViewUpdate=_ViewUpdate;var Direction=function(Direction2){return Direction2[Direction2.LTR=0]="LTR",Direction2[Direction2.RTL=1]="RTL",Direction2}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i=index2){if(span.level==level)return i;(maybe<0||(assoc!=0?assoc<0?span.fromindex2:order[maybe].level>span.level))&&(maybe=i)}}if(maybe<0)throw new RangeError("Index out of range");return maybe}};__name2(_BidiSpan,"BidiSpan");let BidiSpan=_BidiSpan;function isolatesEq(a,b){if(a.length!=b.length)return!1;for(let i=0;i=0;sJ-=3)if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2],type2=flags&2?outerType:flags&4?flags&1?oppositeType:outerType:0;type2&&(types[i]=types[BracketStack[sJ]]=type2),sI=sJ;break}}else{if(BracketStack.length==189)break;BracketStack[sI++]=i,BracketStack[sI++]=ch,BracketStack[sI++]=context}else if((type=types[i])==2||type==1){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur2=BracketStack[sJ+2];if(cur2&2)break;if(embed)BracketStack[sJ+2]|=2;else{if(cur2&4)break;BracketStack[sJ+2]|=4}}}}}__name(processBracketPairs,"processBracketPairs"),__name2(processBracketPairs,"processBracketPairs");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=iIi;)j==fromJ&&(j=isolates[--jI].from,fromJ=jI?isolates[jI-1].to:rFrom),types[--j]=replace;i=end}else prev=type,i++}}}__name(processNeutrals,"processNeutrals"),__name2(processNeutrals,"processNeutrals");function emitSpans(line,from,to,level,baseLevel,isolates,order){let ourType=level%2?2:1;if(level%2==baseLevel%2)for(let iCh=from,iI=0;iChiCh&&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?types[iScan]!=ourType:types[iScan]==ourType))break;iScan++}recurse2?emitSpans(line,iCh,iScan,level+1,baseLevel,recurse2,order):iChfrom;){let sameDir=!0,isNum=!1;if(!iI||iCh>isolates[iI-1].to){let next=types[iCh-1];next!=ourType&&(sameDir=!1,isNum=next==16)}let recurse2=!sameDir&&ourType==1?[]:null,localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI&&iScan==isolates[iI-1].to){if(isNum)break run;let iso=isolates[--iI];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(types[upto-1]==ourType)break run;break}}if(recurse2)recurse2.push(iso);else{iso.totypes.length;)types[types.length]=256;let order=[],level=direction==LTR?0:1;return computeSectionOrder(line,level,level,isolates,0,line.length,order),order}__name(computeOrder,"computeOrder"),__name2(computeOrder,"computeOrder");function trivialOrder(length){return[new BidiSpan(0,length,0)]}__name(trivialOrder,"trivialOrder"),__name2(trivialOrder,"trivialOrder");let movedOver="";function moveVisually(line,order,dir,start,forward){var _a3;let startIndex=start.head-line.from,spanI=-1;if(startIndex==0){if(!forward||!line.length)return null;order[0].level!=dir&&(startIndex=order[0].side(!1,dir),spanI=0)}else if(startIndex==line.length){if(forward)return null;let last2=order[order.length-1];last2.level!=dir&&(startIndex=last2.side(!0,dir),spanI=order.length-1)}spanI<0&&(spanI=BidiSpan.find(order,startIndex,(_a3=start.bidiLevel)!==null&&_a3!==void 0?_a3:-1,start.assoc));let span=order[spanI];startIndex==span.side(forward,dir)&&(span=order[spanI+=forward?1:-1],startIndex=span.side(!forward,dir));let indexForward=forward==(span.dir==dir),nextIndex=findClusterBreak(line.text,startIndex,indexForward);if(movedOver=line.text.slice(Math.min(startIndex,nextIndex),Math.max(startIndex,nextIndex)),nextIndex!=span.side(forward,dir))return EditorSelection.cursor(nextIndex+line.from,indexForward?-1:1,span.level);let nextSpan=spanI==(forward?order.length-1:0)?null:order[spanI+(forward?1:-1)];return!nextSpan&&span.level!=dir?EditorSelection.cursor(forward?line.to:line.from,forward?-1:1,dir):nextSpan&&nextSpan.level0&&changedRanges.length&&(changedRanges.every(({fromA,toA})=>toAthis.minWidthTo)?(this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let readCompositionAt=-1;this.view.inputState.composing>=0&&(!((_a3=this.domChanged)===null||_a3===void 0)&&_a3.newSel?readCompositionAt=this.domChanged.newSel.head:!touchesComposition(update.changes,this.hasComposition)&&!update.selectionSet&&(readCompositionAt=update.state.selection.main.head));let composition=readCompositionAt>-1?findCompositionRange(this.view,update.changes,readCompositionAt):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();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,(browser.ie||browser.chrome)&&!composition&&update&&update.state.doc.lines!=update.startState.doc.lines&&(this.forceSelection=!0);let prevDeco=this.decorations,deco=this.updateDeco(),decoDiff=findChangedDeco(prevDeco,deco,update.changes);return changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff),!(this.flags&7)&&changedRanges.length==0?!1:(this.updateInner(changedRanges,update.startState.doc.length,composition),update.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(changes,oldLength,composition){this.view.viewState.mustMeasureContent=!0,this.updateChildren(changes,oldLength,composition);let{observer}=this.view;observer.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,track),this.flags&=-8,track&&(track.written||observer.selectionRange.focusNode!=track.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(cView=>cView.flags&=-9);let gaps=[];if(this.view.viewport.from||this.view.viewport.to=0?ranges[i]:null;if(!next)break;let{fromA,toA,fromB,toB}=next,content2,breakAtStart,openStart,openEnd;if(composition&&composition.range.fromBfromB){let before=ContentBuilder.build(this.view.state.doc,fromB,composition.range.fromB,this.decorations,this.dynamicDecorationMap),after=ContentBuilder.build(this.view.state.doc,composition.range.toB,toB,this.decorations,this.dynamicDecorationMap);breakAtStart=before.breakAtStart,openStart=before.openStart,openEnd=after.openEnd;let compLine=this.compositionView(composition);after.breakAtStart?compLine.breakAfter=1:after.content.length&&compLine.merge(compLine.length,compLine.length,after.content[0],!1,after.openStart,0)&&(compLine.breakAfter=after.content[0].breakAfter,after.content.shift()),before.content.length&&compLine.merge(0,0,before.content[before.content.length-1],!0,0,before.openEnd)&&before.content.pop(),content2=before.content.concat(compLine).concat(after.content)}else({content:content2,breakAtStart,openStart,openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap));let{i:toI,off:toOff}=cursor.findPos(toA,1),{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content2,breakAtStart,openStart,openEnd)}composition&&this.fixCompositionDOM(composition)}compositionView(composition){let cur2=new TextView(composition.text.nodeValue);cur2.flags|=8;for(let{deco}of composition.marks)cur2=new MarkView(deco,[cur2],cur2.length);let line=new LineView;return line.append(cur2,0),line}fixCompositionDOM(composition){let fix=__name2((dom,cView2)=>{cView2.flags|=8|(cView2.children.some(c=>c.flags&7)?1:0),this.markedForComposition.add(cView2);let prev=ContentView.get(dom);prev&&prev!=cView2&&(prev.dom=null),cView2.setDOM(dom)},"fix"),pos=this.childPos(composition.range.fromB,1),cView=this.children[pos.i];fix(composition.line,cView);for(let i=composition.marks.length-1;i>=-1;i--)pos=cView.childPos(pos.off,1),cView=cView.children[pos.i],fix(i>=0?composition.marks[i].node:composition.text,cView)}updateSelection(mustRead=!1,fromPointer=!1){(mustRead||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let activeElt=this.view.root.activeElement,focused=activeElt==this.dom,selectionNotFocus=!focused&&hasSelection(this.dom,this.view.observer.selectionRange)&&!(activeElt&&this.dom.contains(activeElt));if(!(focused||fromPointer||selectionNotFocus))return;let force=this.forceSelection;this.forceSelection=!1;let main=this.view.state.selection.main,anchor=this.moveToLine(this.domAtPos(main.anchor)),head=main.empty?anchor:this.moveToLine(this.domAtPos(main.head));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=!0}let domSel=this.view.observer.selectionRange;(force||!domSel.focusNode||!isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)||!isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset))&&(this.view.observer.ignore(()=>{browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&inUneditable(domSel.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let rawSel=getSelection(this.view.root);if(rawSel)if(main.empty){if(browser.gecko){let nextTo=nextToUneditable(anchor.node,anchor.offset);if(nextTo&&nextTo!=3){let text=nearbyTextNode(anchor.node,anchor.offset,nextTo==1?1:-1);text&&(anchor=new DOMPos(text.node,text.offset))}}rawSel.collapse(anchor.node,anchor.offset),main.bidiLevel!=null&&rawSel.caretBidiLevel!==void 0&&(rawSel.caretBidiLevel=main.bidiLevel)}else if(rawSel.extend){rawSel.collapse(anchor.node,anchor.offset);try{rawSel.extend(head.node,head.offset)}catch{}}else{let range=document.createRange();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)}selectionNotFocus&&this.view.root.activeElement==this.dom&&(this.dom.blur(),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)}enforceCursorAssoc(){if(this.hasComposition)return;let{view}=this,cursor=view.state.selection.main,sel=getSelection(view.root),{anchorNode,anchorOffset}=view.observer.selectionRange;if(!sel||!cursor.empty||!cursor.assoc||!sel.modify)return;let line=LineView.find(this,cursor.head);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);sel.collapse(dom.node,dom.offset),sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary"),view.observer.readSelectionRange();let newRange=view.observer.selectionRange;view.docView.posFromDOM(newRange.anchorNode,newRange.anchorOffset)!=cursor.from&&sel.collapse(anchorNode,anchorOffset)}moveToLine(pos){let dom=this.dom,newPos;if(pos.node!=dom)return pos;for(let i=pos.offset;!newPos&&i=0;i--){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(view.length))}return newPos?new DOMPos(newPos.node,newPos.offset,!0):pos}nearest(dom){for(let cur2=dom;cur2;){let domView=ContentView.get(cur2);if(domView&&domView.rootView==this)return domView;cur2=cur2.parentNode}return null}posFromDOM(node,offset2){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset2)+view.posAtStart}domAtPos(pos){let{i,off:off2}=this.childCursor().findPos(pos,-1);for(;i=0;i--){let child=this.children[i],end=off2-child.breakAfter,start=end-child.length;if(endpos||child.covers(1))&&(!best||child instanceof LineView&&!(best instanceof LineView&&side>=0))&&(best=child,bestPos=start),off2=start}return best?best.coordsAt(pos-bestPos,side):null}coordsForChar(pos){let{i,off:off2}=this.childPos(pos,1),child=this.children[i];if(!(child instanceof LineView))return null;for(;child.children.length;){let{i:i2,off:childOff}=child.childPos(off2,1);for(;;i2++){if(i2==child.children.length)return null;if((child=child.children[i2]).length)break}off2=childOff}if(!(child instanceof TextView))return null;let end=findClusterBreak(child.text,off2);if(end==off2)return null;let rects=textRange(child.dom,off2,end).getClientRects();return!rects.length||rects[0].top>=rects[0].bottom?null:rects[0]}measureVisibleLineHeights(viewport){let result=[],{from,to}=viewport,contentWidth=this.view.contentDOM.clientWidth,isWider=contentWidth>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;ito)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();if(result.push(childRect.height),isWider){let last2=child.dom.lastChild,rects=last2?clientRectsFor(last2):[];if(rects.length){let rect=rects[rects.length-1],width=ltr?rect.right-childRect.left:childRect.right-rect.left;width>widest&&(widest=width,this.minWidth=contentWidth,this.minWidthFrom=pos,this.minWidthTo=end)}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i}=this.childPos(pos,1);return getComputedStyle(this.children[i].dom).direction=="rtl"?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children)if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}let dummy=document.createElement("div"),lineHeight,charWidth,textHeight;return 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.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height,charWidth=rect?rect.width/27:7,textHeight=rect?rect.height:lineHeight,dummy.remove()}),{lineHeight,charWidth,textHeight}}childCursor(pos=this.length){let i=this.children.length;return i&&(pos-=this.children[--i].length),new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i],end=next?next.from-1:this.length;if(end>pos){let height=(vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top)/this.view.scaleY;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:!0,inclusive:!0,isBlockGap:!0}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let allDeco=this.view.state.facet(decorations).map((d,i)=>(this.dynamicDecorationMap[i]=typeof d=="function")?d(this.view):d);for(let i=allDeco.length;irange.anchor?-1:1),other;if(!rect)return;!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),targetRect={left:rect.left-margins.left,top:rect.top-margins.top,right:rect.right+margins.right,bottom:rect.bottom+margins.bottom};scrollRectIntoView(this.view.scrollDOM,targetRect,range.head0)node=node.childNodes[offset2-1],offset2=maxOffset(node);else break}if(side>=0)for(let node=startNode,offset2=startOffset;;){if(node.nodeType==3)return{node,offset:offset2};if(node.nodeType==1&&offset2=0)node=node.childNodes[offset2],offset2=0;else break}return null}__name(nearbyTextNode,"nearbyTextNode"),__name2(nearbyTextNode,"nearbyTextNode");function nextToUneditable(node,offset2){return node.nodeType!=1?0:(offset2&&node.childNodes[offset2-1].contentEditable=="false"?1:0)|(offset2{fromcomposition.from&&(touched=!0)}),touched}__name(touchesComposition,"touchesComposition"),__name2(touchesComposition,"touchesComposition");function groupAt(state,pos,bias=1){let categorize=state.charCategorizer(pos),line=state.doc.lineAt(pos),linePos=pos-line.from;if(line.length==0)return EditorSelection.cursor(pos);linePos==0?bias=1:linePos==line.length&&(bias=-1);let from=linePos,to=linePos;bias<0?from=findClusterBreak(line.text,linePos,!1):to=findClusterBreak(line.text,linePos);let cat=categorize(line.text.slice(from,to));for(;from>0;){let prev=findClusterBreak(line.text,from,!1);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}for(;tox?rect.left-x:Math.max(0,x-rect.right)}__name(getdx,"getdx"),__name2(getdx,"getdx");function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}__name(getdy,"getdy"),__name2(getdy,"getdy");function yOverlap(a,b){return a.topb.top+1}__name(yOverlap,"yOverlap"),__name2(yOverlap,"yOverlap");function upTop(rect,top2){return top2rect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom}:rect}__name(upBot,"upBot"),__name2(upBot,"upBot");function domPosAtCoords(parent,x,y){let closest2,closestRect,closestX,closestY,closestOverlap=!1,above,below,aboveRect,belowRect;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;idy||closestY==dy&&closestX>dx){closest2=child,closestRect=rect,closestX=dx,closestY=dy;let side=dy?y0?i0)}dx==0?y>rect.bottom&&(!aboveRect||aboveRect.bottomrect.top)&&(below=child,belowRect=rect):aboveRect&&yOverlap(aboveRect,rect)?aboveRect=upBot(aboveRect,rect.bottom):belowRect&&yOverlap(belowRect,rect)&&(belowRect=upTop(belowRect,rect.top))}}if(aboveRect&&aboveRect.bottom>=y?(closest2=above,closestRect=aboveRect):belowRect&&belowRect.top<=y&&(closest2=below,closestRect=belowRect),!closest2)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));if(closest2.nodeType==3)return domPosInText(closest2,clipX,y);if(closestOverlap&&closest2.contentEditable!="false")return domPosAtCoords(closest2,clipX,y);let offset2=Array.prototype.indexOf.call(parent.childNodes,closest2)+(x>=(closestRect.left+closestRect.right)/2?1:0);return{node:parent,offset:offset2}}__name(domPosAtCoords,"domPosAtCoords"),__name2(domPosAtCoords,"domPosAtCoords");function domPosInText(node,x,y){let len=node.nodeValue.length,closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;iy?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy=(rect.left+rect.right)/2,after=right;if((browser.chrome||browser.gecko)&&textRange(node,i).getBoundingClientRect().left==rect.right&&(after=!right),dy<=0)return{node,offset:i+(after?1:0)};closestOffset=i+(after?1:0),closestDY=dy}}}return{node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}__name(domPosInText,"domPosInText"),__name2(domPosInText,"domPosInText");function posAtCoords(view,coords,precise,bias=-1){var _a3,_b2;let content2=view.contentDOM.getBoundingClientRect(),docTop=content2.top+view.viewState.paddingTop,block,{docHeight}=view.viewState,{x,y}=coords,yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.viewState.heightOracle.textHeight/2,bounced=!1;block=view.elementAtHeight(yOffset),block.type!=BlockType.Text;)for(;yOffset=bias>0?block.bottom+halfLine:block.top-halfLine,!(yOffset>=0&&yOffset<=docHeight);){if(bounced)return precise?null:0;bounced=!0,bias=-bias}y=docTop+yOffset;let lineStart=block.from;if(lineStartview.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content2,block,x,y);let doc2=view.dom.ownerDocument,root=view.root.elementFromPoint?view.root:doc2,element=root.elementFromPoint(x,y);element&&!view.contentDOM.contains(element)&&(element=null),element||(x=Math.max(content2.left+1,Math.min(content2.right-1,x)),element=root.elementFromPoint(x,y),element&&!view.contentDOM.contains(element)&&(element=null));let node,offset2=-1;if(element&&((_a3=view.docView.nearest(element))===null||_a3===void 0?void 0:_a3.isEditable)!=!1){if(doc2.caretPositionFromPoint){let pos=doc2.caretPositionFromPoint(x,y);pos&&({offsetNode:node,offset:offset2}=pos)}else if(doc2.caretRangeFromPoint){let range=doc2.caretRangeFromPoint(x,y);range&&({startContainer:node,startOffset:offset2}=range,(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset2,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset2,x))&&(node=void 0))}}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node,offset:offset2}=domPosAtCoords(line.dom,x,y))}let nearest=view.docView.nearest(node);if(!nearest)return null;if(nearest.isWidget&&((_b2=nearest.dom)===null||_b2===void 0?void 0:_b2.nodeType)==1){let rect=nearest.dom.getBoundingClientRect();return coords.yview.defaultLineHeight*1.5){let textHeight=view.viewState.heightOracle.textHeight,line=Math.floor((y-block.top-(view.defaultLineHeight-textHeight)*.5)/textHeight);into+=line*view.viewState.heightOracle.lineLength}let content2=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content2,into,view.state.tabSize)}__name(posAtCoordsImprecise,"posAtCoordsImprecise"),__name2(posAtCoordsImprecise,"posAtCoordsImprecise");function isSuspiciousSafariCaretResult(node,offset2,x){let len;if(node.nodeType!=3||offset2!=(len=node.nodeValue.length))return!1;for(let next=node.nextSibling;next;next=next.nextSibling)if(next.nodeType!=1||next.nodeName!="BR")return!1;return textRange(node,len-1,len).getBoundingClientRect().left>x}__name(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult"),__name2(isSuspiciousSafariCaretResult,"isSuspiciousSafariCaretResult");function isSuspiciousChromeCaretResult(node,offset2,x){if(offset2!=0)return!1;for(let cur2=node;;){let parent=cur2.parentNode;if(!parent||parent.nodeType!=1||parent.firstChild!=cur2)return!1;if(parent.classList.contains("cm-line"))break;cur2=parent}let rect=node.nodeType==1?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect();return x-rect.left>5}__name(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult"),__name2(isSuspiciousChromeCaretResult,"isSuspiciousChromeCaretResult");function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type)){for(let l2 of line.type)if(l2.to>pos||l2.to==pos&&(l2.to==line.to||l2.type==BlockType.Text))return l2}return line}__name(blockAt,"blockAt"),__name2(blockAt,"blockAt");function moveToLineBoundary(view,start,forward,includeWrap){let line=blockAt(view,start.head),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(),direction=view.textDirectionAt(line.from),pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(pos!=null)return EditorSelection.cursor(pos,forward?-1:1)}return EditorSelection.cursor(forward?line.to:line.from,forward?-1:1)}__name(moveToLineBoundary,"moveToLineBoundary"),__name2(moveToLineBoundary,"moveToLineBoundary");function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line),direction=view.textDirectionAt(line.from);for(let cur2=start,check=null;;){let next=moveVisually(line,spans,direction,cur2,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur2;char=` `,line=view.state.doc.line(line.number+(forward?1:-1)),spans=view.bidiSpans(line),next=EditorSelection.cursor(forward?line.from:line.to)}if(check){if(!check(char))return cur2}else{if(!by)return next;check=by(char)}cur2=next}}__name(moveByChar,"moveByChar"),__name2(moveByChar,"moveByChar");function byGroup(view,pos,start){let categorize=view.state.charCategorizer(pos),cat=categorize(start);return next=>{let nextCat=categorize(next);return cat==CharCategory.Space&&(cat=nextCat),cat==nextCat}}__name(byGroup,"byGroup"),__name2(byGroup,"byGroup");function moveVertically(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let goal=start.goalColumn,startY,rect=view.contentDOM.getBoundingClientRect(),startCoords=view.coordsAtPos(startPos,start.assoc||-1),docTop=view.documentTop;if(startCoords)goal==null&&(goal=startCoords.left-rect.left),startY=dir<0?startCoords.top:startCoords.bottom;else{let line=view.viewState.lineBlockAt(startPos);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,dist2=distance??view.viewState.heightOracle.textHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist2+extra)*dir,pos=posAtCoords(view,{x:resolvedGoal,y:curY},!1,dir);if(curYrect.bottom||(dir<0?posstartPos)){let charRect=view.docView.coordsForChar(pos),assoc=!charRect||curY{if(pos>from&&posf(view)),pos.from,oldPos.head>pos.from?-1:1);return newPos==pos.from?pos:EditorSelection.cursor(newPos,newPos{if(event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&(this.runHandlers("mousedown",event),!event.defaultPrevented&&event.button==2)){let start=view.contentDOM.style.minHeight;view.contentDOM.style.minHeight="100%",setTimeout(()=>view.contentDOM.style.minHeight=start,200)}}),view.scrollDOM.addEventListener("drop",event=>{event.target==view.scrollDOM&&event.clientY>view.contentDOM.getBoundingClientRect().bottom&&this.runHandlers("drop",event)}),this.notifiedFocused=view.hasFocus,browser.safari&&view.contentDOM.addEventListener("input",()=>null),browser.gecko&&firefoxCopyCutHack(view.contentDOM.ownerDocument)}handleEvent(event){!eventBelongsToEditor(this.view,event)||this.ignoreDuringComposition(event)||event.type=="keydown"&&this.keydown(event)||this.runHandlers(event.type,event)}runHandlers(type,event){let handlers2=this.handlers[type];if(handlers2){for(let observer of handlers2.observers)observer(this.view,event);for(let handler of handlers2.handlers){if(event.defaultPrevented)break;if(handler(this.view,event)){event.preventDefault();break}}}}ensureHandlers(plugins2){let handlers2=computeHandlers(plugins2),prev=this.handlers,dom=this.view.contentDOM;for(let type in handlers2)if(type!="scroll"){let passive=!handlers2[type].handlers.length,exists=prev[type];exists&&passive!=!exists.handlers.length&&(dom.removeEventListener(type,this.handleEvent),exists=null),exists||dom.addEventListener(type,this.handleEvent,{passive})}for(let type in prev)type!="scroll"&&!handlers2[type]&&dom.removeEventListener(type,this.handleEvent);this.handlers=handlers2}keydown(event){if(this.lastKeyCode=event.keyCode,this.lastKeyTime=Date.now(),event.keyCode==9&&Date.now()key.keyCode==event.keyCode))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)?(this.pendingIOSKey=pending||event,setTimeout(()=>this.flushIOSKey(),250),!0):(event.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(){let key=this.pendingIOSKey;return key?(this.pendingIOSKey=void 0,dispatchKey(this.view.contentDOM,key.key,key.keyCode)):!1}ignoreDuringComposition(event){return/^key/.test(event.type)?this.composing>0?!0:browser.safari&&!browser.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(mouseSelection){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=mouseSelection}update(update){this.mouseSelection&&this.mouseSelection.update(update),update.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};__name2(_InputState,"InputState");let InputState=_InputState;function bindHandler(plugin,handler){return(view,event)=>{try{return handler.call(plugin,event,view)}catch(e){logException(view.state,e)}}}__name(bindHandler,"bindHandler"),__name2(bindHandler,"bindHandler");function computeHandlers(plugins2){let result=Object.create(null);function record(type){return result[type]||(result[type]={observers:[],handlers:[]})}__name(record,"record"),__name2(record,"record");for(let plugin of plugins2){let spec=plugin.spec;if(spec&&spec.domEventHandlers)for(let type in spec.domEventHandlers){let f=spec.domEventHandlers[type];f&&record(type).handlers.push(bindHandler(plugin.value,f))}if(spec&&spec.domEventObservers)for(let type in spec.domEventObservers){let f=spec.domEventObservers[type];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}__name(computeHandlers,"computeHandlers"),__name2(computeHandlers,"computeHandlers");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"}],EmacsyPendingKeys="dthko",modifierCodes=[16,17,18,20,91,92,224,225],dragScrollMargin=6;function dragScrollSpeed(dist2){return Math.max(0,dist2)*.7+8}__name(dragScrollSpeed,"dragScrollSpeed"),__name2(dragScrollSpeed,"dragScrollSpeed");function dist(a,b){return Math.max(Math.abs(a.clientX-b.clientX),Math.abs(a.clientY-b.clientY))}__name(dist,"dist"),__name2(dist,"dist");const _MouseSelection=class{static{__name(this,"_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.scrollParent=scrollableParent(view.contentDOM),this.atoms=view.state.facet(atomicRanges).map(f=>f(view));let doc2=view.contentDOM.ownerDocument;doc2.addEventListener("mousemove",this.move=this.move.bind(this)),doc2.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=startEvent.shiftKey,this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&addsSelectionRange(view,startEvent),this.dragging=isInPrimarySelection(view,startEvent)&&getClickType(startEvent)==1?null:!1}start(event){this.dragging===!1&&this.select(event)}move(event){var _a3;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,rect=((_a3=this.scrollParent)===null||_a3===void 0?void 0:_a3.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},margins=getScrollMargins(this.view);event.clientX-margins.left<=rect.left+dragScrollMargin?sx=-dragScrollSpeed(rect.left-event.clientX):event.clientX+margins.right>=rect.right-dragScrollMargin&&(sx=dragScrollSpeed(event.clientX-rect.right)),event.clientY-margins.top<=rect.top+dragScrollMargin?sy=-dragScrollSpeed(rect.top-event.clientY):event.clientY+margins.bottom>=rect.bottom-dragScrollMargin&&(sy=dragScrollSpeed(event.clientY-rect.bottom)),this.setScrollSpeed(sx,sy)}up(event){this.dragging==null&&this.select(this.lastEvent),this.dragging||event.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let doc2=this.view.contentDOM.ownerDocument;doc2.removeEventListener("mousemove",this.move),doc2.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=null}setScrollSpeed(sx,sy){this.scrollSpeed={x:sx,y:sy},sx||sy?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(sel){let ranges=null;for(let i=0;ithis.select(this.lastEvent),20)}};__name2(_MouseSelection,"MouseSelection");let MouseSelection=_MouseSelection;function addsSelectionRange(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}__name(addsSelectionRange,"addsSelectionRange"),__name2(addsSelectionRange,"addsSelectionRange");function dragMovesSelection(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}__name(dragMovesSelection,"dragMovesSelection"),__name2(dragMovesSelection,"dragMovesSelection");function isInPrimarySelection(view,event){let{main}=view.state.selection;if(main.empty)return!1;let sel=getSelection(view.root);if(!sel||sel.rangeCount==0)return!0;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return!0}return!1}__name(isInPrimarySelection,"isInPrimarySelection"),__name2(isInPrimarySelection,"isInPrimarySelection");function eventBelongsToEditor(view,event){if(!event.bubbles)return!0;if(event.defaultPrevented)return!1;for(let node=event.target,cView;node!=view.contentDOM;node=node.parentNode)if(!node||node.nodeType==11||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return!1;return!0}__name(eventBelongsToEditor,"eventBelongsToEditor"),__name2(eventBelongsToEditor,"eventBelongsToEditor");const handlers=Object.create(null),observers=Object.create(null),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)}__name(capturePaste,"capturePaste"),__name2(capturePaste,"capturePaste");function doPaste(view,input){let{state}=view,changes,i=1,text=state.toText(input),byLine=text.lines==state.selection.ranges.length;if(lastLinewiseCopy!=null&&state.selection.ranges.every(r=>r.empty)&&lastLinewiseCopy==text.toString()){let lastLine=-1;changes=state.changeByRange(range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range};lastLine=line.from;let insert2=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert2},range:EditorSelection.cursor(range.from+insert2.length)}})}else byLine?changes=state.changeByRange(range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}}):changes=state.replaceSelection(text);view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:!0})}__name(doPaste,"doPaste"),__name2(doPaste,"doPaste"),observers.scroll=view=>{view.inputState.lastScrollTop=view.scrollDOM.scrollTop,view.inputState.lastScrollLeft=view.scrollDOM.scrollLeft},handlers.keydown=(view,event)=>(view.inputState.setSelectionOrigin("select"),event.keyCode==27&&(view.inputState.lastEscPress=Date.now()),!1),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)=>{if(view.observer.flush(),view.inputState.lastTouchTime>Date.now()-2e3)return!1;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle))if(style=makeStyle(view,event),style)break;if(!style&&event.button==0&&(style=basicMouseSelection(view,event)),style){let mustFocus=!view.hasFocus;view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus)),mustFocus&&view.observer.ignore(()=>focusPreventScroll(view.contentDOM));let mouseSel=view.inputState.mouseSelection;if(mouseSel)return mouseSel.start(event),!mouseSel.dragging}return!1};function rangeForClick(view,pos,bias,type){if(type==1)return EditorSelection.cursor(pos,bias);if(type==2)return groupAt(view.state,pos,bias);{let visual=LineView.find(view.docView,pos),line=view.state.doc.lineAt(visual?visual.posAtEnd:pos),from=visual?visual.posAtStart:line.from,to=visual?visual.posAtEnd:line.to;return toy>=rect.top&&y<=rect.bottom,"insideY"),inside=__name2((x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right,"inside");function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off2=pos-line.posAtStart;if(off2==0)return 1;if(off2==line.length)return-1;let before=line.coordsAt(off2,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off2,1);return after&&inside(x,y,after)?1:before&&insideY(y,before)?-1:1}__name(findPositionSide,"findPositionSide"),__name2(findPositionSide,"findPositionSide");function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},!1);return{pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}__name(queryPos,"queryPos"),__name2(queryPos,"queryPos");const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last2=lastMouseDown,lastTime=lastMouseDownTime;return lastMouseDown=event,lastMouseDownTime=Date.now(),lastMouseDownCount=!last2||lastTime>Date.now()-400&&Math.abs(last2.clientX-event.clientX)<2&&Math.abs(last2.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}__name(getClickType,"getClickType"),__name2(getClickType,"getClickType");function basicMouseSelection(view,event){let start=queryPos(view,event),type=getClickType(event),startSel=view.state.selection;return{update(update){update.docChanged&&(start.pos=update.changes.mapPos(start.pos),startSel=startSel.map(update.changes))},get(event2,extend2,multiple){let cur2=queryPos(view,event2),removed,range=rangeForClick(view,cur2.pos,cur2.bias,type);if(start.pos!=cur2.pos&&!extend2){let startRange=rangeForClick(view,start.pos,start.bias,type),from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from1&&(removed=removeRangeAround(startSel,cur2.pos))?removed:multiple?startSel.addRange(range):EditorSelection.create([range])}}}__name(basicMouseSelection,"basicMouseSelection"),__name2(basicMouseSelection,"basicMouseSelection");function removeRangeAround(sel,pos){for(let i=0;i=pos)return 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}__name(removeRangeAround,"removeRangeAround"),__name2(removeRangeAround,"removeRangeAround"),handlers.dragstart=(view,event)=>{let{selection:{main}}=view.state,{mouseSelection}=view.inputState;return mouseSelection&&(mouseSelection.dragging=main),event.dataTransfer&&(event.dataTransfer.setData("Text",view.state.sliceDoc(main.from,main.to)),event.dataTransfer.effectAllowed="copyMove"),!1};function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},!1),{mouseSelection}=view.inputState,del=direct&&mouseSelection&&mouseSelection.dragging&&dragMovesSelection(view,event)?{from:mouseSelection.dragging.from,to:mouseSelection.dragging.to}:null,ins={from:dropPos,insert:text},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"})}__name(dropText,"dropText"),__name2(dropText,"dropText"),handlers.drop=(view,event)=>{if(!event.dataTransfer)return!1;if(view.state.readOnly)return!0;let files=event.dataTransfer.files;if(files&&files.length){let text=Array(files.length),read=0,finishFile=__name2(()=>{++read==files.length&&dropText(view,event,text.filter(s2=>s2!=null).join(view.state.lineBreak),!1)},"finishFile");for(let i=0;i{/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)||(text[i]=reader.result),finishFile()},reader.readAsText(files[i])}return!0}else{let text=event.dataTransfer.getData("Text");if(text)return dropText(view,event,text,!0),!0}return!1},handlers.paste=(view,event)=>{if(view.state.readOnly)return!0;view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;return data?(doPaste(view,data.getData("text/plain")||data.getData("text/uri-text")),!0):(capturePaste(view),!1)};function captureCopy(view,text){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)}__name(captureCopy,"captureCopy"),__name2(captureCopy,"captureCopy");function copiedRange(state){let content2=[],ranges=[],linewise=!1;for(let range of state.selection.ranges)range.empty||(content2.push(state.sliceDoc(range.from,range.to)),ranges.push(range));if(!content2.length){let upto=-1;for(let{from}of state.selection.ranges){let line=state.doc.lineAt(from);line.number>upto&&(content2.push(line.text),ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})),upto=line.number}linewise=!0}return{text:content2.join(state.lineBreak),ranges,linewise}}__name(copiedRange,"copiedRange"),__name2(copiedRange,"copiedRange");let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text,ranges,linewise}=copiedRange(view.state);if(!text&&!linewise)return!1;lastLinewiseCopy=linewise?text:null,event.type=="cut"&&!view.state.readOnly&&view.dispatch({changes:ranges,scrollIntoView:!0,userEvent:"delete.cut"});let data=brokenClipboardAPI?null:event.clipboardData;return data?(data.clearData(),data.setData("text/plain",text),!0):(captureCopy(view,text),!1)};const isFocusChange=Annotation.define();function focusChangeTransaction(state,focus){let effects=[];for(let getEffect of state.facet(focusChangeEffect)){let effect=getEffect(state,focus);effect&&effects.push(effect)}return effects?state.update({effects,annotations:isFocusChange.of(!0)}):null}__name(focusChangeTransaction,"focusChangeTransaction"),__name2(focusChangeTransaction,"focusChangeTransaction");function updateForFocusChange(view){setTimeout(()=>{let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){let tr=focusChangeTransaction(view.state,focus);tr?view.dispatch(tr):view.update([])}},10)}__name(updateForFocusChange,"updateForFocusChange"),__name2(updateForFocusChange,"updateForFocusChange"),observers.focus=view=>{view.inputState.lastFocusTime=Date.now(),!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=>{view.inputState.compositionFirstChange==null&&(view.inputState.compositionFirstChange=!0),view.inputState.composing<0&&(view.inputState.composing=0)},observers.compositionend=view=>{view.inputState.composing=-1,view.inputState.compositionEndedAt=Date.now(),view.inputState.compositionPendingKey=!0,view.inputState.compositionPendingChange=view.observer.pendingRecords().length>0,view.inputState.compositionFirstChange=null,browser.chrome&&browser.android?view.observer.flushSoon():view.inputState.compositionPendingChange?Promise.resolve().then(()=>view.observer.flush()):setTimeout(()=>{view.inputState.composing<0&&view.docView.hasComposition&&view.update([])},50)},observers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()},handlers.beforeinput=(view,event)=>{var _a3;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find(key=>key.inputType==event.inputType))&&(view.observer.delayAndroidKey(pending.key,pending.keyCode),pending.key=="Backspace"||pending.key=="Delete")){let startViewHeight=((_a3=window.visualViewport)===null||_a3===void 0?void 0:_a3.height)||0;setTimeout(()=>{var _a4;(((_a4=window.visualViewport)===null||_a4===void 0?void 0:_a4.height)||0)>startViewHeight+10&&view.hasFocus&&(view.contentDOM.blur(),view.focus())},100)}return!1};const appliedFirefoxHack=new Set;function firefoxCopyCutHack(doc2){appliedFirefoxHack.has(doc2)||(appliedFirefoxHack.add(doc2),doc2.addEventListener("copy",()=>{}),doc2.addEventListener("cut",()=>{}))}__name(firefoxCopyCutHack,"firefoxCopyCutHack"),__name2(firefoxCopyCutHack,"firefoxCopyCutHack");const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"],_HeightOracle=class{static{__name(this,"_HeightOracle")}constructor(lineWrapping){this.lineWrapping=lineWrapping,this.doc=Text.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;return this.lineWrapping&&(lines+=Math.max(0,Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength))),this.lineHeight*lines}heightForLine(length){return this.lineWrapping?(1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(doc2){return this.doc=doc2,this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=!1;for(let i=0;i-1,changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;if(this.lineWrapping=lineWrapping,this.lineHeight=lineHeight,this.charWidth=charWidth,this.textHeight=textHeight,this.lineLength=lineLength,changed){this.heightSamples={};for(let i=0;i0}set outdated(value){this.flags=(value?2:0)|this.flags&-3}setHeight(oracle,height){this.height!=height&&(Math.abs(this.height-height)>Epsilon&&(oracle.heightChanged=!0),this.height=height)}replace(_from,_to,nodes){return _HeightMap2.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations2,oldDoc,oracle,changes){let me=this,doc2=oracle.doc;for(let i=changes.length-1;i>=0;i--){let{fromA,toA,fromB,toB}=changes[i],start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle.setDoc(oldDoc),0,0),end=start.to>=toA?start:me.lineAt(toA,QueryType$1.ByPosNoHeight,oracle,0,0);for(toB+=end.to-toA,toA=end.to;i>0&&start.from<=changes[i-1].toA;)fromA=changes[i-1].fromA,fromB=changes[i-1].fromB,i--,fromAafter*2){let split=nodes[i-1];split.break?nodes.splice(--i,1,split.left,null,split.right):nodes.splice(--i,1,split.left,split.right),j+=1+split.break,before-=split.size}else if(after>before*2){let split=nodes[j];split.break?nodes.splice(j,1,split.left,null,split.right):nodes.splice(j,1,split.left,split.right),j+=2+split.break,after-=split.size}else break;else if(before=offset2&&f(this.blockAt(0,oracle,top2,offset2))}updateHeight(oracle,offset2=0,_force=!1,measured){return measured&&measured.from<=offset2&&measured.more&&this.setHeight(oracle,measured.heights[measured.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}};__name2(_HeightMapBlock,"HeightMapBlock");let HeightMapBlock=_HeightMapBlock;const _HeightMapText=class _HeightMapText2 extends HeightMapBlock{static{__name(this,"_HeightMapText")}constructor(length,height){super(length,height,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(_height,_oracle,top2,offset2){return new BlockInfo(offset2,this.length,top2,this.height,this.breaks)}replace(_from,_to,nodes){let node=nodes[0];return nodes.length==1&&(node instanceof _HeightMapText2||node instanceof HeightMapGap&&node.flags&4)&&Math.abs(this.length-node.length)<10?(node instanceof HeightMapGap?node=new _HeightMapText2(node.length,this.height):node.height=this.height,this.outdated||(node.outdated=!1),node):HeightMap.of(nodes)}updateHeight(oracle,offset2=0,force=!1,measured){return measured&&measured.from<=offset2&&measured.more?this.setHeight(oracle,measured.heights[measured.index++]):(force||this.outdated)&&this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed))+this.breaks*oracle.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}};__name2(_HeightMapText,"HeightMapText");let HeightMapText=_HeightMapText;const _HeightMapGap=class _HeightMapGap2 extends HeightMap{static{__name(this,"_HeightMapGap")}constructor(length){super(length,0)}heightMetrics(oracle,offset2){let firstLine=oracle.doc.lineAt(offset2).number,lastLine=oracle.doc.lineAt(offset2+this.length).number,lines=lastLine-firstLine+1,perLine,perChar=0;if(oracle.lineWrapping){let totalPerLine=Math.min(this.height,oracle.lineHeight*lines);perLine=totalPerLine/lines,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,top2,offset2){let{firstLine,lastLine,perLine,perChar}=this.heightMetrics(oracle,offset2);if(oracle.lineWrapping){let guess=offset2+Math.round(Math.max(0,Math.min(1,(height-top2)/this.height))*this.length),line=oracle.doc.lineAt(guess),lineHeight=perLine+line.length*perChar,lineTop=Math.max(top2,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-top2)/perLine))),{from,length}=oracle.doc.line(firstLine+line);return new BlockInfo(from,length,top2+perLine*line,perLine,0)}}lineAt(value,type,oracle,top2,offset2){if(type==QueryType$1.ByHeight)return this.blockAt(value,oracle,top2,offset2);if(type==QueryType$1.ByPosNoHeight){let{from,to}=oracle.doc.lineAt(value);return new BlockInfo(from,to-from,0,0,0)}let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2),line=oracle.doc.lineAt(value),lineHeight=perLine+line.length*perChar,linesAbove=line.number-firstLine,lineTop=top2+perLine*linesAbove+perChar*(line.from-offset2-linesAbove);return new BlockInfo(line.from,line.length,Math.max(top2,Math.min(lineTop,top2+this.height-lineHeight)),lineHeight,0)}forEachLine(from,to,oracle,top2,offset2,f){from=Math.max(from,offset2),to=Math.min(to,offset2+this.length);let{firstLine,perLine,perChar}=this.heightMetrics(oracle,offset2);for(let pos=from,lineTop=top2;pos<=to;){let line=oracle.doc.lineAt(pos);if(pos==from){let linesAbove=line.number-firstLine;lineTop+=perLine*linesAbove+perChar*(from-offset2-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 last2=nodes[nodes.length-1];last2 instanceof _HeightMapGap2?nodes[nodes.length-1]=new _HeightMapGap2(last2.length+after):nodes.push(null,new _HeightMapGap2(after-1))}if(from>0){let first=nodes[0];first instanceof _HeightMapGap2?nodes[0]=new _HeightMapGap2(from+first.length):nodes.unshift(new _HeightMapGap2(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new _HeightMapGap2(to-1),null)}decomposeRight(from,result){result.push(null,new _HeightMapGap2(this.length-from-1))}updateHeight(oracle,offset2=0,force=!1,measured){let end=offset2+this.length;if(measured&&measured.from<=offset2+this.length&&measured.more){let nodes=[],pos=Math.max(offset2,measured.from),singleHeight=-1;for(measured.from>offset2&&nodes.push(new _HeightMapGap2(measured.from-offset2-1).updateHeight(oracle,offset2));pos<=end&&measured.more;){let len=oracle.doc.lineAt(pos).length;nodes.length&&nodes.push(null);let height=measured.heights[measured.index++];singleHeight==-1?singleHeight=height:Math.abs(height-singleHeight)>=Epsilon&&(singleHeight=-2);let line=new HeightMapText(len,height);line.outdated=!1,nodes.push(line),pos+=len+1}pos<=end&&nodes.push(null,new _HeightMapGap2(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);return(singleHeight<0||Math.abs(result.height-this.height)>=Epsilon||Math.abs(singleHeight-this.heightMetrics(oracle,offset2).perLine)>=Epsilon)&&(oracle.heightChanged=!0),result}else(force||this.outdated)&&(this.setHeight(oracle,oracle.heightForGap(offset2,offset2+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}};__name2(_HeightMapGap,"HeightMapGap");let HeightMapGap=_HeightMapGap;const _HeightMapBranch=class extends HeightMap{static{__name(this,"_HeightMapBranch")}constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0)),this.left=left,this.right=right,this.size=left.size+right.size}get break(){return this.flags&1}blockAt(height,oracle,top2,offset2){let mid=top2+this.left.height;return heightrightOffset))return base2;let subQuery=type==QueryType$1.ByPosNoHeight?QueryType$1.ByPosNoHeight:QueryType$1.ByPos;return left?base2.join(this.right.lineAt(rightOffset,subQuery,oracle,rightTop,rightOffset)):this.left.lineAt(rightOffset,subQuery,oracle,top2,offset2).join(base2)}forEachLine(from,to,oracle,top2,offset2,f){let rightTop=top2+this.left.height,rightOffset=offset2+this.left.length+this.break;if(this.break)from=rightOffset&&this.right.forEachLine(from,to,oracle,rightTop,rightOffset,f);else{let mid=this.lineAt(rightOffset,QueryType$1.ByPos,oracle,top2,offset2);from=from&&mid.from<=to&&f(mid),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(tothis.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];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),to=left&&result.push(null)),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);from2*right.size||right.size>2*left.size?HeightMap.of(this.break?[left,null,right]:[left,right]):(this.left=left,this.right=right,this.height=left.height+right.height,this.outdated=left.outdated||right.outdated,this.size=left.size+right.size,this.length=left.length+this.break+right.length,this)}updateHeight(oracle,offset2=0,force=!1,measured){let{left,right}=this,rightStart=offset2+left.length+this.break,rebalance=null;return measured&&measured.from<=offset2+left.length&&measured.more?rebalance=left=left.updateHeight(oracle,offset2,force,measured):left.updateHeight(oracle,offset2,force),measured&&measured.from<=rightStart+right.length&&measured.more?rebalance=right=right.updateHeight(oracle,rightStart,force,measured):right.updateHeight(oracle,rightStart,force),rebalance?this.balanced(left,right):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};__name2(_HeightMapBranch,"HeightMapBranch");let HeightMapBranch=_HeightMapBranch;function mergeGaps(nodes,around){let before,after;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))}__name(mergeGaps,"mergeGaps"),__name2(mergeGaps,"mergeGaps");const relevantWidgetHeight=5,_NodeBuilder=class _NodeBuilder2{static{__name(this,"_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),last2=this.nodes[this.nodes.length-1];last2 instanceof HeightMapText?last2.length+=end-this.pos:(end>this.pos||!this.isCovered)&&this.nodes.push(new HeightMapText(end-this.pos,-1)),this.writtenTo=end,to>end&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=to}point(from,to,deco){if(from=relevantWidgetHeight)&&this.addLineDeco(height,breaks,len)}else to>from&&this.span(from,to);this.lineEnd>-1&&this.lineEnd-1)return;let{from,to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from,this.lineEnd=to,this.writtenTofrom&&this.nodes.push(new HeightMapText(this.pos-from,-1)),this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);return this.oracle.doc.lineAt(from).to==to&&(gap.flags|=4),gap}ensureLine(){this.enterLine();let last2=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last2 instanceof HeightMapText)return last2;let line=new HeightMapText(0,-1);return this.nodes.push(line),line}addBlock(block){this.enterLine();let deco=block.deco;deco&&deco.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(block),this.writtenTo=this.pos=this.pos+block.length,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 last2=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(last2 instanceof HeightMapText)&&!this.isCovered?this.nodes.push(new HeightMapText(0,-1)):(this.writtenToelt.clientHeight||elt.scrollWidth>elt.clientWidth)&&style.overflow!="visible"){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left),right=Math.min(right,parentRect.right),top2=Math.max(top2,parentRect.top),bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent=style.position=="absolute"||style.position=="fixed"?elt.offsetParent:elt.parentNode}else if(parent.nodeType==11)parent=parent.host;else break;return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top2-(rect.top+paddingTop),bottom:Math.max(top2,bottom)-(rect.top+paddingTop)}}__name(visiblePixelRange,"visiblePixelRange"),__name2(visiblePixelRange,"visiblePixelRange");function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}__name(fullPixelRange,"fullPixelRange"),__name2(fullPixelRange,"fullPixelRange");const _LineGap=class{static{__name(this,"_LineGap")}constructor(from,to,size){this.from=from,this.to=to,this.size=size}static same(a,b){if(a.length!=b.length)return!1;for(let i=0;itypeof v!="function"&&v.class=="cm-lineWrapping");this.heightOracle=new HeightOracle(guessWrapping),this.stateDeco=state.facet(decorations).filter(d=>typeof d!="function"),this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Decoration.set(this.lineGaps.map(gap=>gap.draw(this,!1))),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),this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,block=>{this.viewportLines.push(this.scaler.scale==1?block:scaleBlock(block,this.scaler))})}update(update,scrollTarget=null){this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter(d=>typeof d!="function");let contentChanges=update.changedRanges,heightChanges=ChangedRange.extendWithRanges(contentChanges,heightRelevantDecoChanges(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length))),prevHeight=this.heightMap.height,scrollAnchor=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges),this.heightMap.height!=prevHeight&&(update.flags|=2),scrollAnchor?(this.scrollAnchorPos=update.changes.mapPos(scrollAnchor.from,-1),this.scrollAnchorHeight=scrollAnchor.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;(scrollTarget&&(scrollTarget.range.headviewport.to)||!this.viewportIsAppropriate(viewport))&&(viewport=this.getViewport(0,scrollTarget));let updateLines=!update.changes.empty||update.flags&2||viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport,this.updateForViewport(),updateLines&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes))),update.flags|=this.computeVisibleRanges(),scrollTarget&&(this.scrollTarget=scrollTarget),!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc&&!update.state.facet(nativeSelectionHidden)&&(this.mustEnforceCursorAssoc=!0)}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom),oracle=this.heightOracle,whiteSpace=style.whiteSpace;this.defaultTextDirection=style.direction=="rtl"?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace),domRect=dom.getBoundingClientRect(),measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=domRect.height;this.contentDOMHeight=domRect.height,this.mustMeasureContent=!1;let result=0,bias=0;if(domRect.width&&domRect.height){let scaleX=domRect.width/dom.offsetWidth,scaleY=domRect.height/dom.offsetHeight;(scaleX>.995&&scaleX<1.005||!isFinite(scaleX)||Math.abs(domRect.width-dom.offsetWidth)<1)&&(scaleX=1),(scaleY>.995&&scaleY<1.005||!isFinite(scaleY)||Math.abs(domRect.height-dom.offsetHeight)<1)&&(scaleY=1),(this.scaleX!=scaleX||this.scaleY!=scaleY)&&(this.scaleX=scaleX,this.scaleY=scaleY,result|=8,refresh=measureContent=!0)}let paddingTop=(parseInt(style.paddingTop)||0)*this.scaleY,paddingBottom=(parseInt(style.paddingBottom)||0)*this.scaleY;(this.paddingTop!=paddingTop||this.paddingBottom!=paddingBottom)&&(this.paddingTop=paddingTop,this.paddingBottom=paddingBottom,result|=10),this.editorWidth!=view.scrollDOM.clientWidth&&(oracle.lineWrapping&&(measureContent=!0),this.editorWidth=view.scrollDOM.clientWidth,result|=8);let scrollTop=view.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=scrollTop&&(this.scrollAnchorHeight=-1,this.scrollTop=scrollTop),this.scrolledToBottom=isScrolledToBottom(view.scrollDOM);let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop),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,inView&&(measureContent=!0)),!this.inView&&!this.scrollTarget)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|=8),measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights)&&(refresh=!0),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,contentWidth/charWidth,lineHeights),refresh&&(view.docView.minWidth=0,result|=8)}dTop>0&&dBottom>0?bias=Math.max(dTop,dBottom):dTop<0&&dBottom<0&&(bias=Math.min(dTop,dBottom)),oracle.heightChanged=!1;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,Text.empty,this.heightOracle,[new ChangedRange(0,0,0,view.state.doc.length)]):this.heightMap).updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}oracle.heightChanged&&(result|=2)}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return viewportChange&&(this.viewport=this.getViewport(bias,this.scrollTarget)),this.updateForViewport(),(result&2||viewportChange)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view)),result|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,view.docView.enforceCursorAssoc()),result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2)),map2=this.heightMap,oracle=this.heightOracle,{visibleTop,visibleBottom}=this,viewport=new Viewport(map2.lineAt(visibleTop-marginTop*1e3,QueryType$1.ByHeight,oracle,0,0).from,map2.lineAt(visibleBottom+(1-marginTop)*1e3,QueryType$1.ByHeight,oracle,0,0).to);if(scrollTarget){let{head}=scrollTarget.range;if(headviewport.to){let viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),block=map2.lineAt(head,QueryType$1.ByPos,oracle,0,0),topPos;scrollTarget.y=="center"?topPos=(block.top+block.bottom)/2-viewHeight/2:scrollTarget.y=="start"||scrollTarget.y=="nearest"&&head=visibleBottom+Math.max(10,Math.min(bias,250)))&&top2>visibleTop-2*1e3&&bottom>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[],addGap=__name2((from,to,line,structure)=>{if(to-fromfrom&&posgap2.from>=line.from&&gap2.to<=line.to&&Math.abs(gap2.from-from)gap2.frompos));if(!gap){if(tor.from<=to&&r.to>=to)){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),!1,!0).head;lineStart>from&&(to=lineStart)}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)},"addGap");for(let line of this.viewportLines){if(line.lengthline.from&&addGap(line.from,viewFrom,line,structure),viewTogap.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let deco=this.stateDeco;this.lineGaps.length&&(deco=deco.concat(this.lineGapDeco));let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from,to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to);return this.visibleRanges=ranges,changed?4:0}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$1.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(height){return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType$1.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}};__name2(_ViewState,"ViewState");let ViewState=_ViewState;const _Viewport=class{static{__name(this,"_Viewport")}constructor(from,to){this.from=from,this.to=to}};__name2(_Viewport,"Viewport");let Viewport=_Viewport;function lineStructure(from,to,stateDeco){let ranges=[],pos=from,total=0;return RangeSet.spans(stateDeco,from,to,{span(){},point(from2,to2){from2>pos&&(ranges.push({from:pos,to:from2}),total+=from2-pos),pos=to2}},20),pos=1)return ranges[ranges.length-1].to;let dist2=Math.floor(total*ratio);for(let i=0;;i++){let{from,to}=ranges[i],size=to-from;if(dist2<=size)return from+dist2;dist2-=size}}__name(findPosition,"findPosition"),__name2(findPosition,"findPosition");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}__name(findFraction,"findFraction"),__name2(findFraction,"findFraction");function find(array,f){for(let val of array)if(f(val))return val}__name(find,"find"),__name2(find,"find");const IdScaler={toDOM(n2){return n2},fromDOM(n2){return n2},scale:1},_BigScaler=class{static{__name(this,"_BigScaler")}constructor(oracle,heightMap,viewports){let vpHeight=0,base2=0,domBase=0;this.viewports=viewports.map(({from,to})=>{let top2=heightMap.lineAt(from,QueryType$1.ByPos,oracle,0,0).top,bottom=heightMap.lineAt(to,QueryType$1.ByPos,oracle,0,0).bottom;return vpHeight+=bottom-top2,{from,to,top:top2,bottom,domTop:0,domBottom:0}}),this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports)obj.domTop=domBase+(obj.top-base2)*this.scale,domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top),base2=obj.bottom}toDOM(n2){for(let i=0,base2=0,domBase=0;;i++){let vp=iscaleBlock(b,scaler)):block._content)}__name(scaleBlock,"scaleBlock"),__name2(scaleBlock,"scaleBlock");const theme=Facet.define({combine:strs=>strs.join(" ")}),darkTheme=Facet.define({combine:values=>values.indexOf(!0)>-1}),baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName(),lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new 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}})}__name(buildTheme,"buildTheme"),__name2(buildTheme,"buildTheme");const baseTheme$1$2=buildTheme("."+baseThemeID,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{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},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",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"},"@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:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},"&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",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",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},"&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-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"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,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),LineBreakPlaceholder="\uFFFF",_DOMReader=class{static{__name(this,"_DOMReader")}constructor(points,state){this.points=points,this.text="",this.lineSeparator=state.facet(EditorState.lineSeparator)}append(text){this.text+=text}lineBreak(){this.text+=LineBreakPlaceholder}readRange(start,end){if(!start)return this;let parent=start.parentNode;for(let cur2=start;;){this.findPointBefore(parent,cur2);let oldLen=this.text.length;this.readNode(cur2);let next=cur2.nextSibling;if(next==end)break;let view=ContentView.get(cur2),nextView=ContentView.get(next);(view&&nextView?view.breakAfter:(view?view.breakAfter:isBlockElement(cur2))||isBlockElement(next)&&(cur2.nodeName!="BR"||cur2.cmIgnore)&&this.text.length>oldLen)&&this.lineBreak(),cur2=next}return this.findPointBefore(parent,end),this}readTextNode(node){let text=node.nodeValue;for(let point of this.points)point.node==node&&(point.pos=this.text.length+Math.min(point.offset,text.length));for(let off2=0,re=this.lineSeparator?null:/\r\n?|\n/g;;){let nextBreak=-1,breakSize=1,m;if(this.lineSeparator?(nextBreak=text.indexOf(this.lineSeparator,off2),breakSize=this.lineSeparator.length):(m=re.exec(text))&&(nextBreak=m.index,breakSize=m[0].length),this.append(text.slice(off2,nextBreak<0?text.length:nextBreak)),nextBreak<0)break;if(this.lineBreak(),breakSize>1)for(let point of this.points)point.node==node&&point.pos>this.text.length&&(point.pos-=breakSize-1);off2=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node),fromView=view&&view.overrideDOMText;if(fromView!=null){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else node.nodeType==3?this.readTextNode(node):node.nodeName=="BR"?node.nextSibling&&this.lineBreak():node.nodeType==1&&this.readRange(node.firstChild,null)}findPointBefore(node,next){for(let point of this.points)point.node==node&&node.childNodes[point.offset]==next&&(point.pos=this.text.length)}findPointInside(node,length){for(let point of this.points)(node.nodeType==3?point.node==node:node.contains(point.node))&&(point.pos=this.text.length+(isAtEnd(node,point.node,point.offset)?length:0))}};__name2(_DOMReader,"DOMReader");let DOMReader=_DOMReader;function isAtEnd(parent,node,offset2){for(;;){if(!node||offset2-1)this.newSel=null;else if(start>-1&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:selectionPoints(view),reader=new DOMReader(selPoints,view.state);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,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),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);this.newSel=EditorSelection.single(anchor,head)}}};__name2(_DOMChange,"DOMChange");let DOMChange=_DOMChange;function applyDOMChange(view,domChange){let change,{newSel}=domChange,sel=view.state.selection.main,lastKey=view.inputState.lastKeyTime>Date.now()-100?view.inputState.lastKeyCode:-1;if(domChange.bounds){let{from,to}=domChange.bounds,preferredPos=sel.from,preferredSide=null;(lastKey===8||browser.android&&domChange.text.length=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4?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))}:(browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())&&view.contentDOM.getAttribute("autocorrect")=="off"?(newSel&&change.insert.length==2&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}):browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&change.insert.toString()==` `&&view.lineWrapping&&(newSel&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}),change){if(browser.ios&&view.inputState.flushIOSKey()||browser.android&&(change.from==sel.from&&change.to==sel.to&&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.lengthsel.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!0;let text=change.insert.toString();view.inputState.composing>=0&&view.inputState.composing++;let defaultTr,defaultInsert=__name2(()=>defaultTr||(defaultTr=applyDefaultInsert(view,change,newSel)),"defaultInsert");return view.state.facet(inputHandler$1).some(h=>h(view,change.from,change.to,text,defaultInsert))||view.dispatch(defaultInsert()),!0}else if(newSel&&!newSel.main.eq(sel)){let scrollIntoView2=!1,userEvent="select";return view.inputState.lastSelectionTime>Date.now()-50&&(view.inputState.lastSelectionOrigin=="select"&&(scrollIntoView2=!0),userEvent=view.inputState.lastSelectionOrigin),view.dispatch({selection:newSel,scrollIntoView:scrollIntoView2,userEvent}),!0}else return!1}__name(applyDOMChange,"applyDOMChange"),__name2(applyDOMChange,"applyDOMChange");function applyDefaultInsert(view,change,newSel){let tr,startState=view.state,sel=startState.selection.main;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.fromchange.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,void 0,view.state.lineBreak)+after))}else{let changes=startState.changes(change),mainSel=newSel&&newSel.main.to<=changes.newLength?newSel.main:void 0;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let replaced=view.state.sliceDoc(change.from,change.to),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 offset2=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange(range=>{if(range.from==sel.from&&range.to==sel.to)return{changes,range:mainSel||range.map(changes)};let to=range.to-offset2,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range};let rangeChanges=startState.changes({from,to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:mainSel?EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff)):range.map(rangeChanges)}})}else tr={changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}let userEvent="input.type";return(view.composing||view.inputState.compositionPendingChange&&view.inputState.compositionEndedAt>Date.now()-50)&&(view.inputState.compositionPendingChange=!1,userEvent+=".compose",view.inputState.compositionFirstChange&&(userEvent+=".start",view.inputState.compositionFirstChange=!1)),startState.update(tr,{userEvent,scrollIntoView:!0})}__name(applyDefaultInsert,"applyDefaultInsert"),__name2(applyDefaultInsert,"applyDefaultInsert");function findDiff(a,b,preferredPos,preferredSide){let minLen=Math.min(a.length,b.length),from=0;for(;from0&&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=toA?from-preferredPos:0;from-=move,toB=from+(toB-toA),toA=from}else if(toB=toB?from-preferredPos:0;from-=move,toA=from+(toA-toB),toB=from}return{from,toA,toB}}__name(findDiff,"findDiff"),__name2(findDiff,"findDiff");function selectionPoints(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode,anchorOffset,focusNode,focusOffset}=view.observer.selectionRange;return anchorNode&&(result.push(new DOMPoint(anchorNode,anchorOffset)),(focusNode!=anchorNode||focusOffset!=anchorOffset)&&result.push(new DOMPoint(focusNode,focusOffset))),result}__name(selectionPoints,"selectionPoints"),__name2(selectionPoints,"selectionPoints");function selectionFromPoints(points,base2){if(points.length==0)return null;let anchor=points[0].pos,head=points.length==2?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base2,head+base2):null}__name(selectionFromPoints,"selectionFromPoints"),__name2(selectionFromPoints,"selectionFromPoints");const observeOptions={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},useCharData=browser.ie&&browser.ie_version<=11,_DOMObserver=class{static{__name(this,"_DOMObserver")}constructor(view){this.view=view,this.active=!1,this.selectionRange=new DOMSelectionState,this.selectionChanged=!1,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.resizeContent=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=view.contentDOM,this.observer=new MutationObserver(mutations=>{for(let mut of mutations)this.queue.push(mut);(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():this.flush()}),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),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var _a3;((_a3=this.view.docView)===null||_a3===void 0?void 0:_a3.lastUpdate)this.view.requestMeasure()),this.resizeContent.observe(view.contentDOM)),this.addWindowListeners(this.win=view.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(entries=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(entries=>{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),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,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(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);if(context&&context.ignoreEvent(event)){wasChanged||(this.selectionChanged=!1);return}(browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view}=this,range=browser.safari&&view.root.nodeType==11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariSelectionRangeHack(this.view)||getSelection(view.root);if(!range||this.selectionRange.eq(range))return!1;let local=hasSelection(this.dom,range);return local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime{let key2=this.delayedAndroidKey;key2&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=key2.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&key2.force&&dispatchKey(this.dom,key2.key,key2.keyCode))},"flush");this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}(!this.delayedAndroidKey||key=="Enter")&&(this.delayedAndroidKey={key,keyCode,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){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();records.length&&(this.queue=[]);let from=-1,to=-1,typeOver=!1;for(let record of records){let range=this.readMutation(record);range&&(range.typeOver&&(typeOver=!0),from==-1?{from,to}=range:(from=Math.min(range.from,from),to=Math.max(range.to,to)))}return{from,to,typeOver}}readChange(){let{from,to,typeOver}=this.processRecords(),newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;from>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let change=new DOMChange(this.view,from,to,typeOver);return this.view.docView.domChanged={newSel:change.newSel?change.newSel.main:null},change}flush(readSelection=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;readSelection&&this.readSelectionRange();let domChange=this.readChange();if(!domChange)return!1;let startState=this.view.state,handled=applyDOMChange(this.view,domChange);return this.view.state==startState&&this.view.update([]),handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;if(cView.markDirty(rec.type=="attributes"),rec.type=="attributes"&&(cView.flags|=4),rec.type=="childList"){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1),childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:!1}}else return rec.type=="characterData"?{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}:null}setWindow(win){win!=this.win&&(this.removeWindowListeners(this.win),this.win=win,this.addWindowListeners(this.win))}addWindowListeners(win){win.addEventListener("resize",this.onResize),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),win.removeEventListener("beforeprint",this.onPrint),win.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var _a3,_b2,_c2,_d;this.stop(),(_a3=this.intersection)===null||_a3===void 0||_a3.disconnect(),(_b2=this.gapIntersection)===null||_b2===void 0||_b2.disconnect(),(_c2=this.resizeScroll)===null||_c2===void 0||_c2.disconnect(),(_d=this.resizeContent)===null||_d===void 0||_d.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)}};__name2(_DOMObserver,"DOMObserver");let DOMObserver=_DOMObserver;function findChild(cView,dom,dir){for(;dom;){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}__name(findChild,"findChild"),__name2(findChild,"findChild");function safariSelectionRangeHack(view){let found=null;function read(event){event.preventDefault(),event.stopImmediatePropagation(),found=event.getTargetRanges()[0]}if(__name(read,"read"),__name2(read,"read"),view.contentDOM.addEventListener("beforeinput",read,!0),view.dom.ownerDocument.execCommand("indent"),view.contentDOM.removeEventListener("beforeinput",read,!0),!found)return null;let anchorNode=found.startContainer,anchorOffset=found.startOffset,focusNode=found.endContainer,focusOffset=found.endOffset,curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);return isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset)&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]),{anchorNode,anchorOffset,focusNode,focusOffset}}__name(safariSelectionRangeHack,"safariSelectionRangeHack"),__name2(safariSelectionRangeHack,"safariSelectionRangeHack");const _EditorView=class _EditorView2{static{__name(this,"_EditorView")}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(config2={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,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.style.cssText="position: fixed; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM);let{dispatch}=config2;this.dispatchTransactions=config2.dispatchTransactions||dispatch&&(trs=>trs.forEach(tr=>dispatch(tr,this)))||(trs=>this.update(trs)),this.dispatch=this.dispatch.bind(this),this._root=config2.root||getRoot(config2.parent)||document,this.viewState=new ViewState(config2.state||EditorState.create(config2)),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,this.requestMeasure(),config2.parent&&config2.parent.appendChild(this.dom)}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(transactions){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let redrawn=!1,attrsChanged=!1,update,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;transactions.some(tr=>tr.annotation(isFocusChange))?(this.inputState.notifiedFocused=focus,focusFlag=1):focus!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=focus,dispatchFocus=focusChangeTransaction(state,focus),dispatchFocus||(focusFlag=1));let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey?(this.observer.clearDelayedAndroidKey(),domChange=this.observer.readChange(),(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))&&(domChange=null)):this.observer.clear(),state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions),update.flags|=focusFlag;let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget&&(scrollTarget=scrollTarget.map(tr.changes)),tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)e.is(scrollIntoView$1)&&(scrollTarget=e.value)}this.viewState.update(update,scrollTarget),this.bidiCache=CachedOrder.update(this.bidiCache,update.changes),update.empty||(this.updatePlugins(update),this.inputState.update(update)),redrawn=this.docView.update(update),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}if(update.startState.facet(theme)!=update.state.facet(theme)&&(this.viewState.mustMeasureContent=!0),(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!update.empty)for(let listener of this.state.facet(updateListener))listener(update);(dispatchFocus||domChange)&&Promise.resolve().then(()=>{dispatchFocus&&this.state==dispatchFocus.startState&&this.dispatch(dispatchFocus),domChange&&!applyDOMChange(this,domChange)&&pendingKey.force&&dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)})}setState(newState){if(this.updateState!=0)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;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=new DocView(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}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)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-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,flush&&this.observer.forceFlush();let updated=null,sDOM=this.scrollDOM,scrollTop=sDOM.scrollTop*this.scaleY,{scrollAnchorPos,scrollAnchorHeight}=this.viewState;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;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=[];changed&4||([this.measureRequests,measuring]=[measuring,this.measureRequests]);let measured=measuring.map(m=>{try{return m.read(this)}catch(e){return logException(this.state,e),BadMeasure}}),update=ViewUpdate.create(this,this.state,[]),redrawn=!1;update.flags|=changed,updated?updated.flags|=changed:updated=update,this.updateState=2,update.empty||(this.updatePlugins(update),this.inputState.update(update),this.updateAttrs(),redrawn=this.docView.update(update));for(let i2=0;i21||diff2<-1){scrollTop=scrollTop+diff2,sDOM.scrollTop=scrollTop/this.scaleY,scrollAnchorHeight=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}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}),contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(editable)?"true":"false",class:"cm-content",style:`${browser.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(contentAttrs["aria-readonly"]="true"),attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore(()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs),changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor});return this.editorAttrs=editorAttrs,this.contentAttrs=contentAttrs,changed}showAnnouncements(trs){let first=!0;for(let tr of trs)for(let effect of tr.effects)if(effect.is(_EditorView2.announce)){first&&(this.announceDOM.textContent=""),first=!1;let div=this.announceDOM.appendChild(document.createElement("div"));div.textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);let nonce=this.state.facet(_EditorView2.cspNonce);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1$2).reverse(),nonce?{nonce}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(request){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),request){if(this.measureRequests.indexOf(request)>-1)return;if(request.key!=null){for(let i=0;ip.spec==plugin)||null),known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(height){return this.readMeasured(),this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){return this.readMeasured(),this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,initial=>byGroup(this,start.head,initial)))}moveToLineBoundary(start,forward,includeWrap=!0){return moveToLineBoundary(this,start,forward,includeWrap)}moveVertically(start,forward,distance){return skipAtoms(this,start,moveVertically(this,start,forward,distance))}domAtPos(pos){return this.docView.domAtPos(pos)}posAtDOM(node,offset2=0){return this.docView.posFromDOM(node,offset2)}posAtCoords(coords,precise=!0){return this.readMeasured(),posAtCoords(this,coords,precise)}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),span=order[BidiSpan.find(order,pos-line.from,-1,side)];return flattenRect(rect,span.dir==Direction.LTR==side>0)}coordsForChar(pos){return this.readMeasured(),this.docView.coordsForChar(pos)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){return!this.state.facet(perLineTextDirection)||posthis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(pos))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}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.from,line.to))))return entry.order;isolates||(isolates=getIsolatedRanges(this,line.from,line.to));let order=computeOrder(line.text,dir,isolates);return this.bidiCache.push(new CachedOrder(line.from,line.to,dir,isolates,!0,order)),order}get hasFocus(){var _a3;return(this.dom.ownerDocument.hasFocus()||browser.safari&&((_a3=this.inputState)===null||_a3===void 0?void 0:_a3.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{focusPreventScroll(this.contentDOM),this.docView.updateSelection()})}setRoot(root){this._root!=root&&(this._root=root,this.observer.setWindow((root.nodeType==9?root:root.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(pos,options={}){return scrollIntoView$1.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}static domEventHandlers(handlers2){return ViewPlugin.define(()=>({}),{eventHandlers:handlers2})}static domEventObservers(observers2){return ViewPlugin.define(()=>({}),{eventObservers:observers2})}static theme(spec,options){let prefix=StyleModule.newName(),result=[theme.of(prefix),styleModule.of(buildTheme(`.${prefix}`,spec))];return options&&options.dark&&result.push(darkTheme.of(!0)),result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a3;let content2=dom.querySelector(".cm-content"),cView=content2&&ContentView.get(content2)||ContentView.get(dom);return((_a3=cView?.rootView)===null||_a3===void 0?void 0:_a3.view)||null}};__name2(_EditorView,"EditorView");let EditorView=_EditorView;EditorView.styleModule=styleModule,EditorView.inputHandler=inputHandler$1,EditorView.focusChangeEffect=focusChangeEffect,EditorView.perLineTextDirection=perLineTextDirection,EditorView.exceptionSink=exceptionSink,EditorView.updateListener=updateListener,EditorView.editable=editable,EditorView.mouseSelectionStyle=mouseSelectionStyle,EditorView.dragMovesSelection=dragMovesSelection$1,EditorView.clickAddsSelectionRange=clickAddsSelectionRange,EditorView.decorations=decorations,EditorView.atomicRanges=atomicRanges,EditorView.bidiIsolatedRanges=bidiIsolatedRanges,EditorView.scrollMargins=scrollMargins,EditorView.darkTheme=darkTheme,EditorView.cspNonce=Facet.define({combine:values=>values.length?values[0]:""}),EditorView.contentAttributes=contentAttributes,EditorView.editorAttributes=editorAttributes,EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"}),EditorView.announce=StateEffect.define();const MaxBidiLine=4096,BadMeasure={},_CachedOrder=class _CachedOrder2{static{__name(this,"_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=0;i--){let source=sources[i],value=typeof source=="function"?source(view):source;value&&combineAttrs(value,base2)}return base2}__name(attrsFromFacet,"attrsFromFacet"),__name2(attrsFromFacet,"attrsFromFacet");const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name2,platform){const parts=name2.split(/-(?!$)/);let result=parts[parts.length-1];result=="Space"&&(result=" ");let alt,ctrl,shift2,meta2;for(let i=0;ia.concat(b),[]))),map2}__name(getKeymap,"getKeymap"),__name2(getKeymap,"getKeymap");function runScopeHandlers(view,event,scope2){return runHandlers(getKeymap(view.state),event,view,scope2)}__name(runScopeHandlers,"runScopeHandlers"),__name2(runScopeHandlers,"runScopeHandlers");let storedPrefix=null;const PrefixTimeout=4e3;function buildKeymap(bindings,platform=currentPlatform){let bound=Object.create(null),isPrefix=Object.create(null),checkPrefix=__name2((name2,is2)=>{let current=isPrefix[name2];if(current==null)isPrefix[name2]=is2;else if(current!=is2)throw new Error("Key binding "+name2+" is used both as a regular binding and as a multi-stroke prefix")},"checkPrefix"),add2=__name2((scope2,key,command2,preventDefault2,stopPropagation)=>{var _a3,_b2;let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null)),parts=key.split(/ (?!$)/).map(k=>normalizeKeyName(k,platform));for(let i=1;i{let ourObj=storedPrefix={view,prefix,scope:scope2};return setTimeout(()=>{storedPrefix==ourObj&&(storedPrefix=null)},PrefixTimeout),!0}]})}let full=parts.join(" ");checkPrefix(full,!1);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:!1,stopPropagation:!1,run:((_b2=(_a3=scopeObj._any)===null||_a3===void 0?void 0:_a3.run)===null||_b2===void 0?void 0:_b2.slice())||[]});command2&&binding.run.push(command2),preventDefault2&&(binding.preventDefault=!0),stopPropagation&&(binding.stopPropagation=!0)},"add");for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope2 of scopes){let scopeObj=bound[scope2]||(bound[scope2]=Object.create(null));scopeObj._any||(scopeObj._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let key in scopeObj)scopeObj[key].run.push(b.any)}let name2=b[platform]||b.key;if(name2)for(let scope2 of scopes)add2(scope2,name2,b.run,b.preventDefault,b.stopPropagation),b.shift&&add2(scope2,"Shift-"+name2,b.shift,b.preventDefault,b.stopPropagation)}return bound}__name(buildKeymap,"buildKeymap"),__name2(buildKeymap,"buildKeymap");function runHandlers(map2,event,view,scope2){let name2=keyName(event),charCode=codePointAt(name2,0),isChar=codePointSize(charCode)==name2.length&&name2!=" ",prefix="",handled=!1,prevented=!1,stopPropagation=!1;storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope2&&(prefix=storedPrefix.prefix+" ",modifierCodes.indexOf(event.keyCode)<0&&(prevented=!0,storedPrefix=null));let ran=new Set,runFor=__name2(binding=>{if(binding){for(let cmd2 of binding.run)if(!ran.has(cmd2)&&(ran.add(cmd2),cmd2(view,event)))return binding.stopPropagation&&(stopPropagation=!0),!0;binding.preventDefault&&(binding.stopPropagation&&(stopPropagation=!0),prevented=!0)}return!1},"runFor"),scopeObj=map2[scope2],baseName,shiftName;return scopeObj&&(runFor(scopeObj[prefix+modifiers(name2,event,!isChar)])?handled=!0:isChar&&(event.altKey||event.metaKey||event.ctrlKey)&&!(browser.windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name2?(runFor(scopeObj[prefix+modifiers(baseName,event,!0)])||event.shiftKey&&(shiftName=shift[event.keyCode])!=name2&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,!1)]))&&(handled=!0):isChar&&event.shiftKey&&runFor(scopeObj[prefix+modifiers(name2,event,!0)])&&(handled=!0),!handled&&runFor(scopeObj._any)&&(handled=!0)),prevented&&(handled=!0),handled&&stopPropagation&&event.stopPropagation(),handled}__name(runHandlers,"runHandlers"),__name2(runHandlers,"runHandlers");const _RectangleMarker=class _RectangleMarker2{static{__name(this,"_RectangleMarker")}constructor(className,left,top2,width,height){this.className=className,this.left=left,this.top=top2,this.width=width,this.height=height}draw(){let elt=document.createElement("div");return elt.className=this.className,this.adjust(elt),elt}update(elt,prev){return prev.className!=this.className?!1:(this.adjust(elt),!0)}adjust(elt){elt.style.left=this.left+"px",elt.style.top=this.top+"px",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}static forRange(view,className,range){if(range.empty){let pos=view.coordsAtPos(range.head,range.assoc||1);if(!pos)return[];let base2=getBase(view);return[new _RectangleMarker2(className,pos.left-base2.left,pos.top-base2.top,null,pos.bottom-pos.top)]}else return rectanglesForRange(view,className,range)}};__name2(_RectangleMarker,"RectangleMarker");let RectangleMarker=_RectangleMarker;function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();return{left:(view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth*view.scaleX)-view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-view.scrollDOM.scrollTop*view.scaleY}}__name(getBase,"getBase"),__name2(getBase,"getBase");function wrappedLine(view,pos,inside2){let range=EditorSelection.cursor(pos);return{from:Math.max(inside2.from,view.moveToLineBoundary(range,!1,!0).from),to:Math.min(inside2.to,view.moveToLineBoundary(range,!0,!0).from),type:BlockType.Text}}__name(wrappedLine,"wrappedLine"),__name2(wrappedLine,"wrappedLine");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),ltr=view.textDirection==Direction.LTR,content2=view.contentDOM,contentRect=content2.getBoundingClientRect(),base2=getBase(view),lineElt=content2.querySelector(".cm-line"),lineStyle=lineElt&&window.getComputedStyle(lineElt),leftSide=contentRect.left+(lineStyle?parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent)):0),rightSide=contentRect.right-(lineStyle?parseInt(lineStyle.paddingRight):0),startBlock=blockAt(view,from),endBlock=blockAt(view,to),visualStart=startBlock.type==BlockType.Text?startBlock:null,visualEnd=endBlock.type==BlockType.Text?endBlock:null;if(visualStart&&(view.lineWrapping||startBlock.widgetLineBreaks)&&(visualStart=wrappedLine(view,from,visualStart)),visualEnd&&(view.lineWrapping||endBlock.widgetLineBreaks)&&(visualEnd=wrappedLine(view,to,visualEnd)),visualStart&&visualEnd&&visualStart.from==visualEnd.from)return pieces(drawForLine(range.from,range.to,visualStart));{let top2=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,!1),bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,!0),between=[];return(visualStart||startBlock).to<(visualEnd||endBlock).from-(visualStart&&visualEnd?1:0)||startBlock.widgetLineBreaks>1&&top2.bottom+view.defaultLineHeight/2start&&r.from=endPos)break;spanTo>pos&&addSpan(Math.max(spanFrom,pos),from2==null&&spanFrom<=start,Math.min(spanTo,endPos),to2==null&&spanTo>=end,span.dir)}if(pos=docLine.to+1,pos>=endPos)break}return horizontal.length==0&&addSpan(start,from2==null,end,to2==null,view.textDirection),{top:top2,bottom,horizontal}}__name(drawForLine,"drawForLine"),__name2(drawForLine,"drawForLine");function drawForWidget(block,top2){let y=contentRect.top+(top2?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}__name(drawForWidget,"drawForWidget"),__name2(drawForWidget,"drawForWidget")}__name(rectanglesForRange,"rectanglesForRange"),__name2(rectanglesForRange,"rectanglesForRange");function sameMarker(a,b){return a.constructor==b.constructor&&a.eq(b)}__name(sameMarker,"sameMarker"),__name2(sameMarker,"sameMarker");const _LayerView=class{static{__name(this,"_LayerView")}constructor(view,layer2){this.view=view,this.layer=layer2,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"),layer2.above&&this.dom.classList.add("cm-layer-above"),layer2.class&&this.dom.classList.add(layer2.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(view.state),view.requestMeasure(this.measureReq),layer2.mount&&layer2.mount(this.dom,view)}update(update){update.startState.facet(layerOrder)!=update.state.facet(layerOrder)&&this.setOrder(update.state),(this.layer.update(update,this.dom)||update.geometryChanged)&&(this.scale(),update.view.requestMeasure(this.measureReq))}setOrder(state){let pos=0,order=state.facet(layerOrder);for(;pos!sameMarker(p,this.drawn[i]))){let old=this.dom.firstChild,oldI=0;for(let marker of markers)marker.update&&old&&marker.constructor&&this.drawn[oldI].constructor&&marker.update(old,this.drawn[oldI])?(old=old.nextSibling,oldI++):this.dom.insertBefore(marker.draw(),old);for(;old;){let next=old.nextSibling;old.remove(),old=next}this.drawn=markers}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}};__name2(_LayerView,"LayerView");let LayerView=_LayerView;const layerOrder=Facet.define();function layer(config2){return[ViewPlugin.define(v=>new LayerView(v,config2)),layerOrder.of(config2)]}__name(layer,"layer"),__name2(layer,"layer");const CanHidePrimary=!browser.ios,selectionConfig=Facet.define({combine(configs){return combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})}});function drawSelection(config2={}){return[selectionConfig.of(config2),cursorLayer,selectionLayer,hideNativeSelection,nativeSelectionHidden.of(!0)]}__name(drawSelection,"drawSelection"),__name2(drawSelection,"drawSelection");function configChanged(update){return update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig)}__name(configChanged,"configChanged"),__name2(configChanged,"configChanged");const cursorLayer=layer({above:!0,markers(view){let{state}=view,conf=state.facet(selectionConfig),cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let className=prim?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",cursor=r.empty?r: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){update.transactions.some(tr=>tr.selection)&&(dom.style.animationName=dom.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let confChange=configChanged(update);return confChange&&setBlinkRate(update.state,dom),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"}__name(setBlinkRate,"setBlinkRate"),__name2(setBlinkRate,"setBlinkRate");const selectionLayer=layer({above:!1,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"}),themeSpec={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};CanHidePrimary&&(themeSpec[".cm-line"].caretColor="transparent !important");const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec)),setDropCursorPos=StateEffect.define({map(pos,mapping){return pos==null?null:mapping.mapPos(pos)}}),dropCursorPos=StateField.define({create(){return null},update(pos,tr){return pos!=null&&(pos=tr.changes.mapPos(pos)),tr.effects.reduce((pos2,e)=>e.is(setDropCursorPos)?e.value:pos2,pos)}}),drawDropCursor=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 _a3;let cursorPos=update.state.field(dropCursorPos);cursorPos==null?this.cursor!=null&&((_a3=this.cursor)===null||_a3===void 0||_a3.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view}=this,pos=view.state.field(dropCursorPos),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;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"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(pos){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){(event.target==this.view.contentDOM||!this.view.contentDOM.contains(event.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function dropCursor(){return[dropCursorPos,drawDropCursor]}__name(dropCursor,"dropCursor"),__name2(dropCursor,"dropCursor");function iterMatches(doc2,re,from,to,f){re.lastIndex=0;for(let cursor=doc2.iterRange(from,to),pos=from,m;!cursor.next().done;pos+=cursor.value.length)if(!cursor.lineBreak)for(;m=re.exec(cursor.value);)f(pos+m.index,m)}__name(iterMatches,"iterMatches"),__name2(iterMatches,"iterMatches");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),result.length&&result[result.length-1].to>=from?result[result.length-1].to=to:result.push({from,to});return result}__name(matchRanges,"matchRanges"),__name2(matchRanges,"matchRanges");const _MatchDecorator=class{static{__name(this,"_MatchDecorator")}constructor(config2){const{regexp,decoration,decorate,boundary,maxLength=1e3}=config2;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=regexp,decorate)this.addMatch=(match2,view,from,add2)=>decorate(add2,from,from+match2[0].length,match2,view);else if(typeof decoration=="function")this.addMatch=(match2,view,from,add2)=>{let deco=decoration(match2,view,from);deco&&add2(from,from+match2[0].length,deco)};else if(decoration)this.addMatch=(match2,_view,from,add2)=>add2(from,from+match2[0].length,decoration);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=boundary,this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add2=build.add.bind(build);for(let{from,to}of matchRanges(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,(from2,m)=>this.addMatch(m,view,from2,add2));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;return update.docChanged&&update.changes.iterChanges((_f,_t,from,to)=>{to>update.view.viewport.from&&from1e3?this.createDeco(update.view):changeTo>-1?this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo):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.tofromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;toranges.push(deco2.range(from2,to2)),"add");if(fromLine==toLine)for(this.regexp.lastIndex=start-fromLine.from;(m=this.regexp.exec(fromLine.text))&&m.indexthis.addMatch(m2,view,from2,add2));deco=deco.update({filterFrom:start,filterTo:end,filter:(from2,to2)=>from2end,add:ranges})}}return deco}};__name2(_MatchDecorator,"MatchDecorator");let MatchDecorator=_MatchDecorator;const UnicodeRegexpSupport=/x/.unicode!=null?"gu":"g",Specials=new RegExp(`[\0-\b -\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,UnicodeRegexpSupport),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 _a3;if(_supportsTabSize==null&&typeof document<"u"&&document.body){let styles=document.body.style;_supportsTabSize=((_a3=styles.tabSize)!==null&&_a3!==void 0?_a3:styles.MozTabSize)!=null}return _supportsTabSize||!1}__name(supportsTabSize,"supportsTabSize"),__name2(supportsTabSize,"supportsTabSize");const specialCharConfig=Facet.define({combine(configs){let config2=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});return(config2.replaceTabs=!supportsTabSize())&&(config2.specialChars=new RegExp(" |"+config2.specialChars.source,UnicodeRegexpSupport)),config2.addSpecialChars&&(config2.specialChars=new RegExp(config2.specialChars.source+"|"+config2.addSpecialChars.source,UnicodeRegexpSupport)),config2}});function highlightSpecialChars(config2={}){return[specialCharConfig.of(config2),specialCharPlugin()]}__name(highlightSpecialChars,"highlightSpecialChars"),__name2(highlightSpecialChars,"highlightSpecialChars");let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=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:doc2}=view.state,code=codePointAt(m[0],0);if(code==9){let line=doc2.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}__name(specialCharPlugin,"specialCharPlugin"),__name2(specialCharPlugin,"specialCharPlugin");const DefaultPlaceholder="\u2022";function placeholder$1(code){return code>=32?DefaultPlaceholder:code==10?"\u2424":String.fromCharCode(9216+code)}__name(placeholder$1,"placeholder$1"),__name2(placeholder$1,"placeholder$1");const _SpecialCharWidget=class extends WidgetType{static{__name(this,"_SpecialCharWidget")}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),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}};__name2(_SpecialCharWidget,"SpecialCharWidget");let SpecialCharWidget=_SpecialCharWidget;const _TabWidget=class extends WidgetType{static{__name(this,"_TabWidget")}constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent=" ",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}};__name2(_TabWidget,"TabWidget");let TabWidget=_TabWidget;function highlightActiveLine(){return activeLineHighlighter}__name(highlightActiveLine,"highlightActiveLine"),__name2(highlightActiveLine,"highlightActiveLine");const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(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);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations}),MaxOff=2e3;function rectangleFor(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),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);line.length<=endOff&&ranges.push(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),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}__name(rectangleFor,"rectangleFor"),__name2(rectangleFor,"rectangleFor");function absoluteColumn(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}__name(absoluteColumn,"absoluteColumn"),__name2(absoluteColumn,"absoluteColumn");function getPos(view,event){let offset2=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset2),off2=offset2-line.from,col=off2>MaxOff?-1:off2==line.length?absoluteColumn(view,event.clientX):countColumn(line.text,view.state.tabSize,offset2-line.from);return{line:line.number,col,off:off2}}__name(getPos,"getPos"),__name2(getPos,"getPos");function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),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(event2,_extend,multiple){let cur2=getPos(view,event2);if(!cur2)return startSel;let ranges=rectangleFor(view.state,start,cur2);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}__name(rectangleSelectionStyle,"rectangleSelectionStyle"),__name2(rectangleSelectionStyle,"rectangleSelectionStyle");function rectangularSelection(options){let filter2=options?.eventFilter||(e=>e.altKey&&e.button==0);return EditorView.mouseSelectionStyle.of((view,event)=>filter2(event)?rectangleSelectionStyle(view,event):null)}__name(rectangularSelection,"rectangularSelection"),__name2(rectangularSelection,"rectangularSelection");const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(options={}){let[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){(e.keyCode==code||!getter(e))&&this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of(view=>{var _a3;return!((_a3=view.plugin(plugin))===null||_a3===void 0)&&_a3.isDown?showCrosshair:null})]}__name(crosshairCursor,"crosshairCursor"),__name2(crosshairCursor,"crosshairCursor");const Outside="-10000px",_TooltipViewManager=class{static{__name(this,"_TooltipViewManager")}constructor(view,facet,createTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter(t2=>t2),this.tooltipViews=this.tooltips.map(createTooltipView)}update(update){var _a3;let input=update.state.facet(this.facet),tooltips=input.filter(x=>x);if(input===this.input){for(let t2 of this.tooltipViews)t2.update&&t2.update(update);return!1}let tooltipViews=[];for(let i=0;i{var _a3,_b2,_c2;return{position:browser.ios?"absolute":((_a3=values.find(conf=>conf.position))===null||_a3===void 0?void 0:_a3.position)||"fixed",parent:((_b2=values.find(conf=>conf.parent))===null||_b2===void 0?void 0:_b2.parent)||null,tooltipSpace:((_c2=values.find(conf=>conf.tooltipSpace))===null||_c2===void 0?void 0:_c2.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config2=view.state.facet(tooltipConfig);this.position=config2.position,this.parent=config2.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new TooltipViewManager(view,showTooltip,t2=>this.createTooltip(t2)),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{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(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):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(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t2 of this.manager.tooltipViews)t2.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t2 of this.manager.tooltipViews)this.container.appendChild(t2.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top=Outside,this.container.appendChild(tooltipView.dom),tooltipView.mount&&tooltipView.mount(this.view),tooltipView}destroy(){var _a3,_b2;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),(_a3=tooltipView.destroy)===null||_a3===void 0||_a3.call(tooltipView);this.parent&&this.container.remove(),(_b2=this.intersectionObserver)===null||_b2===void 0||_b2.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{offsetParent}=this.manager.tooltipViews[0].dom;makeAbsolute=!!(offsetParent&&offsetParent!=this.container.ownerDocument.body)}if(makeAbsolute||this.position=="absolute")if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX,scaleY}=this.view.viewState);return{editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t2,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t2.pos):this.view.coordsAtPos(t2.pos)}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX,scaleY,makeAbsolute}}writeMeasure(measured){var _a3;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t2 of this.manager.tooltipViews)t2.dom.style.position="absolute"}let{editor,space,scaleX,scaleY}=measured,others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top=Outside;continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=(_a3=knownHeight.get(tView))!==null&&_a3!==void 0?_a3:size.bottom-size.top,offset2=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset2.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset2.x),above=!!tooltip.above;!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset2.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVertleft&&r.toptop2&&(top2=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if(this.position=="absolute"?(dom.style.top=(top2-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top2/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset2.x:-offset2.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}tView.overlap!==!0&&others.push({left,top:top2,right,bottom:top2+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$5=EditorView.baseTheme({".cm-tooltip":{zIndex:100,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:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$5]}),showHoverTooltip=Facet.define(),_HoverTooltipHost=class _HoverTooltipHost2{static{__name(this,"_HoverTooltipHost")}static create(view){return new _HoverTooltipHost2(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,t2=>this.createHostedView(t2))}createHostedView(tooltip){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(hostedView.dom),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a3;for(let t2 of this.manager.tooltipViews)(_a3=t2.destroy)===null||_a3===void 0||_a3.call(t2)}};__name2(_HoverTooltipHost,"HoverTooltipHost");let HoverTooltipHost=_HoverTooltipHost;const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t2=>t2);return tooltips.length===0?null:{pos:Math.min(...tooltips.map(t2=>t2.pos)),end:Math.max(...tooltips.filter(t2=>t2.end!=null).map(t2=>t2.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t2=>t2.arrow)}}),_HoverPlugin=class{static{__name(this,"_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(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let hovered=Date.now()-this.lastMove.time;hoveredposCoords.bottom||lastMove.xposCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find(s2=>s2.from<=pos&&s2.to>=pos),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x{this.pending==pending&&(this.pending=null,result&&view.dispatch({effects:this.setHover.of(result)}))},e=>logException(view.state,e,"hover tooltip"))}else open&&view.dispatch({effects:this.setHover.of(open)})}mousemove(event){var _a3;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a3=tooltip?.end)!==null&&_a3!==void 0?_a3:pos;(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1,this.active&&!isInTooltip(e.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}};__name2(_HoverPlugin,"HoverPlugin");let HoverPlugin=_HoverPlugin;function isInTooltip(elt){for(let cur2=elt;cur2;cur2=cur2.parentNode)if(cur2.nodeType==1&&cur2.classList.contains("cm-tooltip"))return!0;return!1}__name(isInTooltip,"isInTooltip"),__name2(isInTooltip,"isInTooltip");function isOverRange(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.righty||Math.min(rect.bottom,docBottom)=from&&pos<=to}__name(isOverRange,"isOverRange"),__name2(isOverRange,"isOverRange");function hoverTooltip(source,options={}){let setHover=StateEffect.define(),hoverState=StateField.define({create(){return null},update(value,tr){if(value&&(options.hideOnChange&&(tr.docChanged||tr.selection)||options.hideOn&&options.hideOn(tr,value)))return null;if(value&&tr.docChanged){let newPos=tr.changes.mapPos(value.pos,-1,MapMode.TrackDel);if(newPos==null)return null;let copy=Object.assign(Object.create(null),value);copy.pos=newPos,value.end!=null&&(copy.end=tr.changes.mapPos(value.end)),value=copy}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=null);return value},provide:f=>showHoverTooltip.from(f)});return[hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300)),showHoverTooltipHost]}__name(hoverTooltip,"hoverTooltip"),__name2(hoverTooltip,"hoverTooltip");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]}__name(getTooltip,"getTooltip"),__name2(getTooltip,"getTooltip");const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer,bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index2=plugin?plugin.specs.indexOf(panel):-1;return index2>-1?plugin.panels[index2]:null}__name(getPanel,"getPanel"),__name2(getPanel,"getPanel");const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter(s2=>s2),this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,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"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x),panels=[],top2=[],bottom=[],mount2=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;known<0?(panel=spec(update.view),mount2.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top2:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top2),this.bottom.sync(bottom);for(let p of mount2)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}})}),_PanelGroup=class{static{__name(this,"_PanelGroup")}constructor(view,top2,container){this.view=view,this.top=top2,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);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){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;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)){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}};__name2(_PanelGroup,"PanelGroup");let PanelGroup=_PanelGroup;function rm(node){let next=node.nextSibling;return node.remove(),next}__name(rm,"rm"),__name2(rm,"rm");const showPanel=Facet.define({enables:panelPlugin}),_GutterMarker=class extends RangeValue{static{__name(this,"_GutterMarker")}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}};__name2(_GutterMarker,"GutterMarker");let GutterMarker=_GutterMarker;GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config2){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config2))]}__name(gutter,"gutter"),__name2(gutter,"gutter");const unfixGutters=Facet.define({combine:values=>values.some(x=>x)});function gutters(config2){let result=[gutterView];return config2&&config2.fixed===!1&&result.push(unfixGutters.of(!0)),result}__name(gutters,"gutters"),__name2(gutters,"gutters");const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",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));for(let gutter2 of this.gutters)this.dom.appendChild(gutter2.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<(vpB.to-vpB.from)*.8)}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map(gutter2=>new UpdateContext(gutter2,this.view.viewport,-this.view.documentPadding.top));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;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=!1}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();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur2=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur2)for(let gutter2 of this.gutters)gutter2.update(update)&&(change=!0);else{change=!0;let gutters2=[];for(let conf of cur2){let known=prev.indexOf(conf);known<0?gutters2.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters2.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters2.indexOf(g)<0&&g.destroy();for(let g of gutters2)this.dom.appendChild(g.dom);this.gutters=gutters2}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return!value||value.gutters.length==0||!value.fixed?null:view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}})});function asArray$1(val){return Array.isArray(val)?val:[val]}__name(asArray$1,"asArray$1"),__name2(asArray$1,"asArray$1");function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}__name(advanceCursor,"advanceCursor"),__name2(advanceCursor,"advanceCursor");const _UpdateContext=class{static{__name(this,"_UpdateContext")}constructor(gutter2,viewport,height){this.gutter=gutter2,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter2.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter2}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter2.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter2.elements.push(newElt),gutter2.dom.appendChild(newElt.dom)}else gutter2.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),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter2=this.gutter;localMarkers.length==0&&!gutter2.config.renderEmptyElements||this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter2=this.gutter;for(;gutter2.elements.length>this.i;){let last2=gutter2.elements.pop();gutter2.dom.removeChild(last2.dom),last2.destroy()}}};__name2(_UpdateContext,"UpdateContext");let UpdateContext=_UpdateContext;const _SingleGutterView=class{static{__name(this,"_SingleGutterView")}constructor(view,config2){this.view=view,this.config=config2,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 config2.domEventHandlers)this.dom.addEventListener(prop,event=>{let target=event.target,y;if(target!=this.dom&&this.dom.contains(target)){for(;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);config2.domEventHandlers[prop](view,line,event)&&event.preventDefault()});this.markers=asArray$1(config2.markers(view)),config2.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config2.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray$1(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(update):!1)}destroy(){for(let elt of this.elements)elt.destroy()}};__name2(_SingleGutterView,"SingleGutterView");let SingleGutterView=_SingleGutterView;const _GutterElement=class{static{__name(this,"_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){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),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=iNewexists(view,line,event2)||add2(view,line,event2):add2}return result}})}}),_NumberMarker=class extends GutterMarker{static{__name(this,"_NumberMarker")}constructor(number2){super(),this.number=number2}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}};__name2(_NumberMarker,"NumberMarker");let NumberMarker=_NumberMarker;function formatNumber(view,number2){return view.state.facet(lineNumberConfig).formatNumber(number2,view.state)}__name(formatNumber,"formatNumber"),__name2(formatNumber,"formatNumber");const lineNumberGutter=activeGutters.compute([lineNumberConfig],state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(view){return view.state.facet(lineNumberMarkers)},lineMarker(view,line,others){return others.some(m=>m.toDOM)?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number))},widgetMarker:()=>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}));function lineNumbers(config2={}){return[lineNumberConfig.of(config2),gutters(),lineNumberGutter]}__name(lineNumbers,"lineNumbers"),__name2(lineNumbers,"lineNumbers");function maxLineNumber(lines){let last2=9;for(;last2{let marks=[],last2=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last2&&(last2=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)});function highlightActiveLineGutter(){return activeLineGutterHighlighter}__name(highlightActiveLineGutter,"highlightActiveLineGutter"),__name2(highlightActiveLineGutter,"highlightActiveLineGutter");const DefaultBufferLength=1024;let nextPropID=0;const _Range=class{static{__name(this,"_Range")}constructor(from,to){this.from=from,this.to=to}};__name2(_Range,"Range");let Range=_Range;const _NodeProp=class{static{__name(this,"_NodeProp")}constructor(config2={}){this.id=nextPropID++,this.perNode=!!config2.perNode,this.deserialize=config2.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match2){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof match2!="function"&&(match2=NodeType.match(match2)),type=>{let result=match2(type);return result===void 0?null:[this,result]}}};__name2(_NodeProp,"NodeProp");let NodeProp=_NodeProp;NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null),_NodeType=class _NodeType2{static{__name(this,"_NodeType")}constructor(name2,props,id,flags=0){this.name=name2,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(spec.name==null?8:0),type=new _NodeType2(spec.name||"",props,spec.id,flags);if(spec.props){for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),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}prop(prop){return this.props[prop.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(name2){if(typeof name2=="string"){if(this.name==name2)return!0;let group=this.prop(NodeProp.group);return group?group.indexOf(name2)>-1:!1}return this.id==name2}static match(map2){let direct=Object.create(null);for(let prop in map2)for(let name2 of prop.split(" "))direct[name2]=map2[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}}}};__name2(_NodeType,"NodeType");let NodeType=_NodeType;NodeType.none=new NodeType("",Object.create(null),0,8);const _NodeSet=class _NodeSet2{static{__name(this,"_NodeSet")}constructor(types2){this.types=types2;for(let i=0;i0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||enter(c)!==!1)){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(config2={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,(children,positions,length)=>new _Tree2(this.type,children,positions,length,this.propValues),config2.makeTree||((children,positions,length)=>new _Tree2(NodeType.none,children,positions,length)))}static build(data){return buildTree(data)}};__name2(_Tree,"Tree");let Tree=_Tree;Tree.empty=new Tree(NodeType.none,[],[],0);const _FlatBufferCursor=class _FlatBufferCursor2{static{__name(this,"_FlatBufferCursor")}constructor(buffer,index2){this.buffer=buffer,this.index=index2}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 _FlatBufferCursor2(this.buffer,this.index)}};__name2(_FlatBufferCursor,"FlatBufferCursor");let FlatBufferCursor=_FlatBufferCursor;const _TreeBuffer=class _TreeBuffer2{static{__name(this,"_TreeBuffer")}constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index2=0;index20));i=buffer[i+3]);return pick2}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i=pos&&frompos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}__name(checkSide,"checkSide"),__name2(checkSide,"checkSide");function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last2=scan.lastChild;if(!last2||last2.to!=scan.to)break;last2.type.isError&&last2.from==last2.to?(node=scan,scan=last2.prevSibling):scan=last2}return node}__name(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore"),__name2(enterUnfinishedNodesBefore,"enterUnfinishedNodesBefore");function resolveNode(node,pos,side,overlays){for(var _a3;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length)){if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index2=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index2>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index2)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new _TreeNode2(mounted.tree,start,i,parent);let inner=new _TreeNode2(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous||(parent.index>=0?i=parent.index+dir:i=dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side,mode=0){let mounted;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from,to}of mounted.overlay)if((side>0?from<=rPos:from=rPos:to>rPos))return new _TreeNode2(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;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):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}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)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_TreeNode,"TreeNode");let TreeNode=_TreeNode;function getChildren(node,type,before,after){let cur2=node.cursor(),result=[];if(!cur2.firstChild())return result;if(before!=null){for(;!cur2.type.is(before);)if(!cur2.nextSibling())return result}for(;;){if(after!=null&&cur2.type.is(after))return result;if(cur2.type.is(type)&&result.push(cur2.node),!cur2.nextSibling())return after==null?result:[]}}__name(getChildren,"getChildren"),__name2(getChildren,"getChildren");function matchNodeContext(node,context,i=context.length-1){for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}__name(matchNodeContext,"matchNodeContext"),__name2(matchNodeContext,"matchNodeContext");const _BufferContext=class{static{__name(this,"_BufferContext")}constructor(parent,buffer,index2,start){this.parent=parent,this.buffer=buffer,this.index=index2,this.start=start}};__name2(_BufferContext,"BufferContext");let BufferContext=_BufferContext;const _BufferNode=class _BufferNode2{static{__name(this,"_BufferNode")}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,index2){this.context=context,this._parent=_parent,this.index=index2,this.type=context.buffer.set.types[context.buffer.buffer[index2]]}child(dir,pos,side){let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side,mode=0){if(mode&IterMode.ExcludeBuffers)return null;let{buffer}=this.context,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index2<0?null:new _BufferNode2(this.context,this,index2)}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)}get nextSibling(){let{buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new _BufferNode2(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new _BufferNode2(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(mode=0){return new TreeCursor(this,mode)}get tree(){return null}toTree(){let children=[],positions=[],{buffer}=this.context,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)}resolve(pos,side=0){return resolveNode(this,pos,side,!1)}resolveInner(pos,side=0){return resolveNode(this,pos,side,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}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)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}};__name2(_BufferNode,"BufferNode");let BufferNode=_BufferNode;const _TreeCursor=class{static{__name(this,"_TreeCursor")}get name(){return this.type.name}constructor(node,mode=0){if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n2=node._parent;n2;n2=n2._parent)this.stack.unshift(n2.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return node?(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0):!1}yieldBuf(index2,type){this.index=index2;let{start,buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index2]],this.from=start+buffer.buffer[index2+1],this.to=start+buffer.buffer[index2+2],!0}yield(node){return node?node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}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,index2=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return index2<0?!1:(this.stack.push(this.index),this.yieldBuf(index2))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side,mode=this.mode){return this.buffer?mode&IterMode.ExcludeBuffers?!1:this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}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();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode)):!1;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))}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,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index2,parent,{buffer}=this;if(buffer){if(dir>0){if(this.index-1)for(let i=index2+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!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(enter=!0){return this.move(1,enter)}prev(enter=!0){return this.move(-1,enter)}moveTo(pos,side=0){for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to=0;){for(let c=cache;c;c=c._parent)if(c.index==index2){if(index2==this.index)return c;result=c,depth=d+1;break scan}index2=this.stack[--d]}for(let i=depth;i=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types2[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}};__name2(_TreeCursor,"TreeCursor");let TreeCursor=_TreeCursor;function hasChild(tree){return tree.children.some(ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch))}__name(hasChild,"hasChild"),__name2(hasChild,"hasChild");function buildTree(data){var _a3;let{buffer,nodeSet,maxBufferLength=DefaultBufferLength,reused=[],minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types2=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children2,positions2,inRepeat){let{id,start,end,size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;)if(cursor.next(),size==-1){let node2=reused[id];children2.push(node2),positions2.push(start-parentStart);return}else if(size==-3){contextHash=id;return}else if(size==-4){lookAhead=id;return}else throw new RangeError(`Unrecognized record size: ${size}`);let type=types2[id],node,buffer2,startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer2=findBufferSize(cursor.pos-minPos,inRepeat))){let data2=new Uint16Array(buffer2.size-buffer2.skip),endPos=cursor.pos-buffer2.size,index2=data2.length;for(;cursor.pos>endPos;)index2=copyToBuffer(buffer2.start,data2,index2);node=new TreeBuffer(data2,end-buffer2.start,nodeSet),startPos=buffer2.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children2.push(node),positions2.push(startPos)}__name(takeNode,"takeNode"),__name2(takeNode,"takeNode");function makeBalanced(type){return(children2,positions2,length2)=>{let lookAhead2=0,lastI=children2.length-1,last2,lookAheadProp;if(lastI>=0&&(last2=children2[lastI])instanceof Tree){if(!lastI&&last2.type==type&&last2.length==length2)return last2;(lookAheadProp=last2.prop(NodeProp.lookAhead))&&(lookAhead2=positions2[lastI]+last2.length+lookAheadProp)}return makeTree(type,children2,positions2,length2,lookAhead2)}}__name(makeBalanced,"makeBalanced"),__name2(makeBalanced,"makeBalanced");function makeRepeatLeaf(children2,positions2,base2,i,from,to,type,lookAhead2){let localChildren=[],localPositions=[];for(;children2.length>i;)localChildren.push(children2.pop()),localPositions.push(positions2.pop()+base2-from);children2.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead2-to)),positions2.push(from-base2)}__name(makeRepeatLeaf,"makeRepeatLeaf"),__name2(makeRepeatLeaf,"makeRepeatLeaf");function makeTree(type,children2,positions2,length2,lookAhead2=0,props){if(contextHash){let pair2=[NodeProp.contextHash,contextHash];props=props?[pair2].concat(props):[pair2]}if(lookAhead2>25){let pair2=[NodeProp.lookAhead,lookAhead2];props=props?[pair2].concat(props):[pair2]}return new Tree(type,children2,positions2,length2,props)}__name(makeTree,"makeTree"),__name2(makeTree,"makeTree");function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize2=fork.size;if(fork.id==inRepeat&&nodeSize2>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize2;if(nodeSize2<0||startPos=minRepeatType?4:0,nodeStart2=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0)if(fork.size==-3)localSkipped+=4;else break scan;else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart2,size+=nodeSize2,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}__name(findBufferSize,"findBufferSize"),__name2(findBufferSize,"findBufferSize");function copyToBuffer(bufferStart,buffer2,index2){let{id,start,end,size}=cursor;if(cursor.next(),size>=0&&id4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index2=copyToBuffer(bufferStart,buffer2,index2)}buffer2[--index2]=startIndex,buffer2[--index2]=end-bufferStart,buffer2[--index2]=start-bufferStart,buffer2[--index2]=id}else size==-3?contextHash=id:size==-4&&(lookAhead=id);return index2}__name(copyToBuffer,"copyToBuffer"),__name2(copyToBuffer,"copyToBuffer");let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=(_a3=data.length)!==null&&_a3!==void 0?_a3:children.length?positions[0]+children[0].length:0;return new Tree(types2[data.topID],children.reverse(),positions.reverse(),length)}__name(buildTree,"buildTree"),__name2(buildTree,"buildTree");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}__name(nodeSize,"nodeSize"),__name2(nodeSize,"nodeSize");function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children2[groupFrom];divide(only.children,only.positions,0,only.children.length,positions2[groupFrom]+offset2);continue}localChildren.push(children2[groupFrom])}else{let length2=positions2[i-1]+children2[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children2,positions2,groupFrom,i,groupStart,length2,null,mkTree))}localPositions.push(groupStart+offset2-start)}}return __name(divide,"divide"),__name2(divide,"divide"),divide(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}__name(balanceRange,"balanceRange"),__name2(balanceRange,"balanceRange");const _TreeFragment=class _TreeFragment2{static{__name(this,"_TreeFragment")}constructor(from,to,tree,offset2,openStart=!1,openEnd=!1){this.from=from,this.to=to,this.tree=tree,this.offset=offset2,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(tree,fragments=[],partial=!1){let result=[new _TreeFragment2(0,tree.length,tree,0,!1,partial)];for(let f of fragments)f.to>tree.length&&result.push(f);return result}static applyChanges(fragments,changes,minGap=128){if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off2=0;;cI++){let nextC=cI=minGap)for(;nextF&&nextF.from=cut.from||nextPos<=cut.to||off2){let fFrom=Math.max(cut.from,pos)-off2,fTo=Math.min(cut.to,nextPos)-off2;cut=fFrom>=fTo?null:new _TreeFragment2(fFrom,fTo,cut.tree,cut.offset+off2,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fInew Range(r.from,r.to)):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse2=this.startParse(input,fragments,ranges);for(;;){let done=parse2.advance();if(done)return done}}};__name2(_Parser,"Parser");let Parser=_Parser;const _StringInput=class{static{__name(this,"_StringInput")}constructor(string2){this.string=string2}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}};__name2(_StringInput,"StringInput");let StringInput=_StringInput;new NodeProp({perNode:!0});let nextTagID=0;const _Tag=class _Tag2{static{__name(this,"_Tag")}constructor(set,base2,modified){this.set=set,this.base=base2,this.modified=modified,this.id=nextTagID++}static define(parent){if(parent?.base)throw new Error("Can not derive from a modified tag");let tag=new _Tag2([],null,[]);if(tag.set.push(tag),parent)for(let t2 of parent.set)tag.set.push(t2);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort((a,b)=>a.id-b.id))}};__name2(_Tag,"Tag");let Tag=_Tag,nextModifierID=0;const _Modifier=class _Modifier2{static{__name(this,"_Modifier")}constructor(){this.instances=[],this.id=nextModifierID++}static get(base2,mods){if(!mods.length)return base2;let exists=mods[0].instances.find(t2=>t2.base==base2&&sameArray(mods,t2.modified));if(exists)return exists;let set=[],tag=new Tag(set,base2,mods);for(let m of mods)m.instances.push(tag);let configs=powerSet(mods);for(let parent of base2.set)if(!parent.modified.length)for(let config2 of configs)set.push(_Modifier2.get(parent,config2));return tag}};__name2(_Modifier,"Modifier");let Modifier=_Modifier;function sameArray(a,b){return a.length==b.length&&a.every((x,i)=>x==b[i])}__name(sameArray,"sameArray"),__name2(sameArray,"sameArray");function powerSet(array){let sets=[[]];for(let i=0;ib.length-a.length)}__name(powerSet,"powerSet"),__name2(powerSet,"powerSet");function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags2=spec[prop];Array.isArray(tags2)||(tags2=[tags2]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if(rest=="..."&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push(m[0]=="*"?"":m[0][0]=='"'?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&next=="!"){mode=0;break}if(next!="/")throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last2=pieces.length-1,inner=pieces[last2];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags2,mode,last2>0?pieces.slice(0,last2):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}__name(styleTags,"styleTags"),__name2(styleTags,"styleTags");const ruleNodeProp=new NodeProp,_Rule=class{static{__name(this,"_Rule")}constructor(tags2,mode,context,next){this.tags=tags2,this.mode=mode,this.context=context,this.next=next}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(other){return!other||other.depth{let cls=all;for(let tag of tags3)for(let sub of tag.set){let tagClass=map2[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope2}}__name(tagHighlighter,"tagHighlighter"),__name2(tagHighlighter,"tagHighlighter");function highlightTags(highlighters,tags2){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags2);value&&(result=result?result+" "+value:value)}return result}__name(highlightTags,"highlightTags"),__name2(highlightTags,"highlightTags");function highlightTree(tree,highlighter,putStyle,from=0,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)}__name(highlightTree,"highlightTree"),__name2(highlightTree,"highlightTree");const _HighlightBuilder=class{static{__name(this,"_HighlightBuilder")}constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){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;type.isTop&&(highlighters=this.highlighters.filter(h=>!h.scope||h.scope(type)));let cls=inheritedClass,rule=getStyleTags(cursor)||Rule.empty,tagCls=highlightTags(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,rule.mode==1&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),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),innerHighlighters=this.highlighters.filter(h=>!h.scope||h.scope(mounted.tree.type)),hasChild2=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i=nextPos||!cursor.nextSibling())););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild2&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do if(!(cursor.to<=from)){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()}}};__name2(_HighlightBuilder,"HighlightBuilder");let HighlightBuilder=_HighlightBuilder;function getStyleTags(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}__name(getStyleTags,"getStyleTags"),__name2(getStyleTags,"getStyleTags");const t=Tag.define,comment=t(),name=t(),typeName=t(name),propertyName=t(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(),tags={comment,lineComment:t(comment),blockComment:t(comment),docComment:t(comment),name,variableName:t(name),typeName,tagName:t(typeName),propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal,string,docString:t(string),character:t(string),attributeValue:t(string),number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation,separator:t(punctuation),bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content,heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};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"}]);var _a$1;const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}__name(defineLanguageFacet,"defineLanguageFacet"),__name2(defineLanguageFacet,"defineLanguageFacet");const sublanguageProp=new NodeProp,_Language=class{static{__name(this,"_Language")}constructor(data,parser2,extraExtensions=[],name2=""){this.data=data,this.name=name2,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser2,this.extension=[language.of(this),EditorState.languageData.of((state,pos,side)=>{let top2=topNodeAt(state,pos,side),data2=top2.type.prop(languageDataProp);if(!data2)return[];let base2=state.facet(data2),sub=top2.type.prop(sublanguageProp);if(sub){let innerNode=top2.resolve(pos-top2.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data3=state.facet(sublang.facet);return sublang.type=="replace"?data3:data3.concat(base2)}}return base2})].concat(extraExtensions)}isActiveAt(state,pos,side=-1){return topNodeAt(state,pos,side).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if(lang?.data==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=__name2((tree,from)=>{if(tree.prop(languageDataProp)==this.data){result.push({from,to:from+tree.length});return}let mount2=tree.prop(NodeProp.mounted);if(mount2){if(mount2.tree.prop(languageDataProp)==this.data){if(mount2.overlay)for(let r of mount2.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from,to:from+tree.length});return}else if(mount2.overlay){let size=result.length;if(explore(mount2.tree,mount2.overlay[0].from+from),result.length>size)return}}for(let i=0;itype.isTop?data:void 0)]}),spec.name)}configure(options,name2){return new _LRLanguage2(this.data,this.parser.configure(options),name2||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};__name2(_LRLanguage,"LRLanguage");let LRLanguage=_LRLanguage;function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}__name(syntaxTree,"syntaxTree"),__name2(syntaxTree,"syntaxTree");const _DocInput=class{static{__name(this,"_DocInput")}constructor(doc2){this.doc=doc2,this.cursorPos=0,this.string="",this.cursor=doc2.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}};__name2(_DocInput,"DocInput");let DocInput=_DocInput,currentContext=null;const _ParseContext=class _ParseContext2{static{__name(this,"_ParseContext")}constructor(parser2,state,fragments=[],tree,treeLen,viewport,skipped,scheduleOn){this.parser=parser2,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser2,state,viewport){return new _ParseContext2(parser2,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return upto!=null&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(upto??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var _a3;if(typeof until=="number"){let endTime=Date.now()+until;until=__name2(()=>Date.now()>endTime,"until")}for(this.parse||(this.parse=this.startParse()),upto!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>upto)&&upto=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext(()=>{for(;!(tree=this.parse.advance()););}),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),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}changes(changes,newState){let{fragments,tree,treeLen,viewport,skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(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)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);fromviewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return this.skipped.length>=startLen?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from,to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}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}static get(){return currentContext}};__name2(_ParseContext,"ParseContext");let ParseContext=_ParseContext;function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}__name(cutFragments,"cutFragments"),__name2(cutFragments,"cutFragments");const _LanguageState=class _LanguageState2{static{__name(this,"_LanguageState")}constructor(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),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new _LanguageState2(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new _LanguageState2(parseState)}};__name2(_LanguageState,"LanguageState");let LanguageState=_LanguageState;Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=__name2(callback=>{let timeout=setTimeout(()=>callback(),500);return()=>clearTimeout(timeout)},"requestIdle");typeof requestIdleCallback<"u"&&(requestIdle=__name2(callback=>{let idle=-1,timeout=setTimeout(()=>{idle=requestIdleCallback(callback,{timeout:500-100})},100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)},"requestIdle"));const isInputPending=typeof navigator<"u"&&(!((_a$1=navigator.scheduling)===null||_a$1===void 0)&&_a$1.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass((_c=class{static{__name(this,"_c")}constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state}=this.view,field=state.field(Language.state);(field.tree!=field.context.tree||!field.context.isDone(state.doc.length))&&(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now2=Date.now();if(this.chunkEndvpTo+1e3,done=field.context.work(()=>isInputPending&&isInputPending()||Date.now()>endTime,vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now2,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&!(done&&!viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then(()=>this.scheduleWork()).catch(err=>logException(this.view.state,err)).then(()=>this.workScheduled--),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},__name2(_c,"ParseWorker"),_c),{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine(languages){return languages.length?languages[0]:null},enables:language2=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language2],state=>{let lang=state.facet(language2);return lang&&lang.name?{"data-language":lang.name}:{}})]}),_LanguageSupport=class{static{__name(this,"_LanguageSupport")}constructor(language2,support=[]){this.language=language2,this.support=support,this.extension=[language2,support]}};__name2(_LanguageSupport,"LanguageSupport");let LanguageSupport=_LanguageSupport;const indentService=Facet.define(),indentUnit=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}});function getIndentUnit(state){let unit=state.facet(indentUnit);return unit.charCodeAt(0)==9?state.tabSize*unit.length:unit.length}__name(getIndentUnit,"getIndentUnit"),__name2(getIndentUnit,"getIndentUnit");function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if(ch==" "){for(;cols>=ts;)result+=" ",cols-=ts;ch=" "}for(let i=0;i=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line,pos=line.length){return countColumn(line,this.state.tabSize,pos)}lineIndent(pos,bias=1){let{text,from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}};__name2(_IndentContext,"IndentContext");let IndentContext=_IndentContext;const indentNodeProp=new NodeProp;function syntaxIndentation(cx,ast,pos){return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),pos,cx)}__name(syntaxIndentation,"syntaxIndentation"),__name2(syntaxIndentation,"syntaxIndentation");function ignoreClosed(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}__name(ignoreClosed,"ignoreClosed"),__name2(ignoreClosed,"ignoreClosed");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 last2=tree.lastChild,closed=last2&&close.indexOf(last2.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!ignoreClosed(cx)?last2.from:void 0)}return tree.parent==null?topIndent:null}__name(indentStrategy,"indentStrategy"),__name2(indentStrategy,"indentStrategy");function indentFrom(node,pos,base2){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base2,pos,node))}return null}__name(indentFrom,"indentFrom"),__name2(indentFrom,"indentFrom");function topIndent(){return 0}__name(topIndent,"topIndent"),__name2(topIndent,"topIndent");const _TreeIndentContext=class _TreeIndentContext2 extends IndentContext{static{__name(this,"_TreeIndentContext")}constructor(base2,pos,node){super(base2.state,base2.options),this.base=base2,this.pos=pos,this.node=node}static create(base2,pos,node){return new _TreeIndentContext2(base2,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;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(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}};__name2(_TreeIndentContext,"TreeIndentContext");let TreeIndentContext=_TreeIndentContext;function isParent(parent,of){for(let cur2=of;cur2;cur2=cur2.parent)if(parent==cur2)return!0;return!1}__name(isParent,"isParent"),__name2(isParent,"isParent");function bracketedAligned(context){let tree=context.node,openToken=tree.childAfter(tree.from),last2=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),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==last2)return null;if(!next.type.isSkipped)return next.from{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}__name(continuedIndent,"continuedIndent"),__name2(continuedIndent,"continuedIndent");const DontIndentBeyond=200;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 doc2=tr.newDoc,{head}=tr.newSelection.main,line=doc2.lineAt(head);if(head>line.from+DontIndentBeyond)return tr;let lineStart=doc2.sliceString(line.from,head);if(!rules.some(r=>r.test(lineStart)))return tr;let{state}=tr,last2=-1,changes=[];for(let{head:head2}of state.selection.ranges){let line2=state.doc.lineAt(head2);if(line2.from==last2)continue;last2=line2.from;let indent=getIndentation(state,line2.from);if(indent==null)continue;let cur2=/^\s*/.exec(line2.text)[0],norm=indentString(state,indent);cur2!=norm&&changes.push({from:line2.from,to:line2.from+cur2.length,insert:norm})}return changes.length?[tr,{changes,sequential:!0}]:tr})}__name(indentOnInput,"indentOnInput"),__name2(indentOnInput,"indentOnInput");const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last2=node.lastChild;return first&&first.toend)continue;if(found&&cur2.from=start&&value.to>end&&(found=value)}}return found}__name(syntaxFolding,"syntaxFolding"),__name2(syntaxFolding,"syntaxFolding");function isUnfinished(node){let ch=node.lastChild;return ch&&ch.to==node.to&&ch.type.isError}__name(isUnfinished,"isUnfinished"),__name2(isUnfinished,"isUnfinished");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)}__name(foldable,"foldable"),__name2(foldable,"foldable");function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from,to}}__name(mapRange,"mapRange"),__name2(mapRange,"mapRange");const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head}of view.state.selection.ranges)lines.some(l2=>l2.from<=head&&l2.to>=head)||lines.push(view.lineBlockAt(head));return lines}__name(selectedLines,"selectedLines"),__name2(selectedLines,"selectedLines");const foldState=StateField.define({create(){return Decoration.none},update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):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}));if(tr.selection){let onSelection=!1,{head}=tr.selection.main;folded.between(head,head,(a,b)=>{ahead&&(onSelection=!0)}),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,(from,to)=>{ranges.push(from,to)}),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{(!found||found.from>from2)&&(found={from:from2,to:to2})}),found}__name(findFold,"findFold"),__name2(findFold,"findFold");function foldExists(folded,from,to){let found=!1;return folded.between(from,from,(a,b)=>{a==from&&b==to&&(found=!0)}),found}__name(foldExists,"foldExists"),__name2(foldExists,"foldExists");function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}__name(maybeEnable,"maybeEnable"),__name2(maybeEnable,"maybeEnable");const foldCode=__name2(view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1},"foldCode"),unfoldCode=__name2(view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects}),effects.length>0},"unfoldCode");function announceFold(view,range,fold=!0){let lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of(`${view.state.phrase(fold?"Folded lines":"Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`)}__name(announceFold,"announceFold"),__name2(announceFold,"announceFold");const foldAll=__name2(view=>{let{state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,(from,to)=>{effects.push(unfoldEffect.of({from,to}))}),view.dispatch({effects}),!0},"unfoldAll"),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}],defaultConfig={placeholderDOM:null,placeholderText:"\u2026"},foldConfig=Facet.define({combine(values){return combineConfig(values,defaultConfig)}});function codeFolding(config2){let result=[foldState,baseTheme$1$1];return config2&&result.push(foldConfig.of(config2)),result}__name(codeFolding,"codeFolding"),__name2(codeFolding,"codeFolding");const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state}=view,conf=state.facet(foldConfig),onclick=__name2(event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()},"onclick");if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},_FoldMarker=class extends GutterMarker{static{__name(this,"_FoldMarker")}constructor(config2,open){super(),this.config=config2,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");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}};__name2(_FoldMarker,"FoldMarker");let FoldMarker=_FoldMarker;function foldGutter(config2={}){let fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config2),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=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;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a3;return((_a3=view.plugin(markers))===null||_a3===void 0?void 0:_a3.markers)||RangeSet.empty},initialSpacer(){return new FoldMarker(fullConfig,!1)},domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return range?(view.dispatch({effects:foldEffect.of(range)}),!0):!1}})}),codeFolding()]}__name(foldGutter,"foldGutter"),__name2(foldGutter,"foldGutter");const baseTheme$1$1=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"}}),_HighlightStyle=class _HighlightStyle2{static{__name(this,"_HighlightStyle")}constructor(specs,options){this.specs=specs;let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}__name(def,"def"),__name2(def,"def");const all=typeof options.all=="string"?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map(style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))})),{all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new _HighlightStyle2(specs,options||{})}};__name2(_HighlightStyle,"HighlightStyle");let HighlightStyle=_HighlightStyle;const highlighterFacet=Facet.define(),fallbackHighlighter=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)}__name(getHighlighters,"getHighlighters"),__name2(getHighlighters,"getHighlighters");function syntaxHighlighting(highlighter,options){let ext=[treeHighlighter],themeType;return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),options?.fallback?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],state=>state.facet(EditorView.darkTheme)==(themeType=="dark")?[highlighter]:[])):ext.push(highlighterFacet.of(highlighter)),ext}__name(syntaxHighlighting,"syntaxHighlighting"),__name2(syntaxHighlighting,"syntaxHighlighting");const _TreeHighlighter=class{static{__name(this,"_TreeHighlighter")}constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length{builder.add(from2,to2,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))},from,to);return builder.finish()}};__name2(_TreeHighlighter,"TreeHighlighter");let TreeHighlighter=_TreeHighlighter;const treeHighlighter=Prec.high(ViewPlugin.fromClass(TreeHighlighter,{decorations:v=>v.decorations})),defaultHighlightStyle=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,tags.special(tags.string)],color:"#e40"},{tag:tags.definition(tags.variableName),color:"#00f"},{tag:tags.local(tags.variableName),color:"#30a"},{tag:[tags.typeName,tags.namespace],color:"#085"},{tag:tags.className,color:"#167"},{tag:[tags.special(tags.variableName),tags.macroName],color:"#256"},{tag:tags.definition(tags.propertyName),color:"#00c"},{tag:tags.comment,color:"#940"},{tag:tags.invalid,color:"#f00"}]),baseTheme$4=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),DefaultScanDist=1e4,DefaultBrackets="()[]{}",bracketMatchingConfig=Facet.define({combine(configs){return combineConfig(configs,{afterCursor:!0,brackets:DefaultBrackets,maxScanDistance:DefaultScanDist,renderMatch:defaultRenderMatch})}}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match2){let decorations2=[],mark=match2.matched?matchingMark:nonmatchingMark;return decorations2.push(mark.range(match2.start.from,match2.start.to)),match2.end&&decorations2.push(mark.range(match2.end.from,match2.end.to)),decorations2}__name(defaultRenderMatch,"defaultRenderMatch"),__name2(defaultRenderMatch,"defaultRenderMatch");const bracketMatchingState=StateField.define({create(){return Decoration.none},update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations2=[],config2=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match2=matchBrackets(tr.state,range.head,-1,config2)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config2)||config2.afterCursor&&(matchBrackets(tr.state,range.head,1,config2)||range.headEditorView.decorations.from(f)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$4];function bracketMatching(config2={}){return[bracketMatchingConfig.of(config2),bracketMatchingUnique]}__name(bracketMatching,"bracketMatching"),__name2(bracketMatching,"bracketMatching");const bracketMatchingHandle=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 index2=brackets.indexOf(node.name);if(index2>-1&&index2%2==(dir<0?1:0))return[brackets[index2+dir]]}return null}__name(matchingNodes,"matchingNodes"),__name2(matchingNodes,"matchingNodes");function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}__name(findHandle,"findHandle"),__name2(findHandle,"findHandle");function matchBrackets(state,pos,dir,config2={}){let maxScanDistance=config2.maxScanDistance||DefaultScanDist,brackets=config2.brackets||DefaultBrackets,tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur2=node;cur2;cur2=cur2.parent){let matches2=matchingNodes(cur2.type,dir,brackets);if(matches2&&cur2.from0?pos>=handle.from&&poshandle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur2,handle,matches2,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}__name(matchBrackets,"matchBrackets"),__name2(matchBrackets,"matchBrackets");function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=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.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},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;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos2=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos2!=end;pos2+=dir){let found=brackets.indexOf(text[pos2]);if(!(found<0||tree.resolveInner(basePos+pos2,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(depth==1)return{start:startToken,end:{from:basePos+pos2,to:basePos+pos2+1},matched:found>>1==bracket2>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}__name(matchPlainBrackets,"matchPlainBrackets"),__name2(matchPlainBrackets,"matchPlainBrackets");const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name2]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]=createTokenType(noTokens,name2);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}__name(warnForPart,"warnForPart"),__name2(warnForPart,"warnForPart");function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];value?typeof value=="function"?tag?tag=value(tag):warnForPart(part,`Modifier ${part} used at start of tag`):tag?warnForPart(part,`Tag ${part} used as modifier`):tag=value:warnForPart(part,`Unknown highlighting tag ${part}`)}if(!tag)return 0;let name2=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name2,props:[styleTags({[name2]:tag})]});return typeArray.push(type),type.id}__name(createTokenType,"createTokenType"),__name2(createTokenType,"createTokenType");const _CompletionContext=class{static{__name(this,"_CompletionContext")}constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types2){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types2.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}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return this.abortListeners==null}addEventListener(type,listener){type=="abort"&&this.abortListeners&&this.abortListeners.push(listener)}};__name2(_CompletionContext,"CompletionContext");let CompletionContext=_CompletionContext;function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),`[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`}__name(toSet,"toSet"),__name2(toSet,"toSet");function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=!0;for(let i=1;itypeof o=="string"?{label:o}:o),[validFor,match2]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match2);return token||context.explicit?{from:token?token.from:context.pos,options,validFor}:null}}__name(completeFromList,"completeFromList"),__name2(completeFromList,"completeFromList");const _Option=class{static{__name(this,"_Option")}constructor(completion,source,match2,score2){this.completion=completion,this.source=source,this.match=match2,this.score=score2}};__name2(_Option,"Option");let Option=_Option;function cur(state){return state.selection.main.from}__name(cur,"cur"),__name2(cur,"cur");function ensureAnchor(expr,start){var _a3;let{source}=expr,addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";return!addStart&&!addEnd?expr:new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a3=expr.flags)!==null&&_a3!==void 0?_a3:expr.ignoreCase?"i":"")}__name(ensureAnchor,"ensureAnchor"),__name2(ensureAnchor,"ensureAnchor");const pickedCompletion=Annotation.define();function insertCompletionText(state,text,from,to){let{main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange(range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)})),{scrollIntoView:!0,userEvent:"input.complete"})}__name(insertCompletionText,"insertCompletionText"),__name2(insertCompletionText,"insertCompletionText");const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}__name(asSource,"asSource"),__name2(asSource,"asSource");const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define(),_FuzzyMatcher=class{static{__name(this,"_FuzzyMatcher")}constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||type==1&&hasLower||prevType==0&&type!=0)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&byWord[0]==0&&wordAdjacent?this.result(-100+(byWordFolded?-200:0),byWord,word):adjacentTo==len&&adjacentStart==0?this.ret(-200-word.length+(adjacentEnd==word.length?0:-100),[0,adjacentEnd]):direct>-1?this.ret(-700-word.length,[direct,direct+this.pattern.length]):adjacentTo==len?this.ret(-200+-700-word.length,[adjacentStart,adjacentEnd]):byWordTo==len?this.result(-100+(byWordFolded?-200:0)+-700+(wordAdjacent?0:-1100),byWord,word):chars.length==2?!1:this.result((any[0]?-700:0)+-200+-1100,any,word)}result(score2,positions,word){let result=[],i=0;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return this.ret(score2-word.length,result)}};__name2(_FuzzyMatcher,"FuzzyMatcher");let FuzzyMatcher=_FuzzyMatcher;const completionConfig=Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75},{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)})}});function joinClass(a,b){return a?b?a+" "+b:a:b}__name(joinClass,"joinClass"),__name2(joinClass,"joinClass");function defaultPositionInfo(view,list,option2,info,space,tooltip){let rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",offset2,maxWidth,spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft=infoHeight||spaceBelow>list.top?offset2=option2.bottom-list.top:(side="bottom",offset2=list.bottom-option2.top)}let scaleY=(list.bottom-list.top)/tooltip.offsetHeight,scaleX=(list.right-list.left)/tooltip.offsetWidth;return{style:`${side}: ${offset2/scaleY}px; max-width: ${maxWidth/scaleX}px`,class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}__name(defaultPositionInfo,"defaultPositionInfo"),__name2(defaultPositionInfo,"defaultPositionInfo");function optionContent(config2){let content2=config2.addToOptions.slice();return config2.icons&&content2.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls)),icon.setAttribute("aria-hidden","true"),icon},position:20}),content2.push({render(completion,_s,match2){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let label=completion.displayLabel||completion.label,off2=0;for(let j=0;joff2&&labelElt.appendChild(document.createTextNode(label.slice(off2,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off2=to}return off2a.position-b.position).map(a=>a.render)}__name(optionContent,"optionContent"),__name2(optionContent,"optionContent");function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off3=Math.floor(selected/max);return{from:off3*max,to:(off3+1)*max}}let off2=Math.floor((total-selected)/max);return{from:total-(off2+1)*max,to:total-off2*max}}__name(rangeAroundSelected,"rangeAroundSelected"),__name2(rangeAroundSelected,"rangeAroundSelected");const _CompletionTooltip=class{static{__name(this,"_CompletionTooltip")}constructor(view,stateField,applyCompletion2){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion2,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),{options,selected}=cState.open,config2=view.state.facet(completionConfig);this.optionContent=optionContent(config2),this.optionClass=config2.optionClass,this.tooltipClass=config2.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config2.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match2;dom&&dom!=this.dom;dom=dom.parentNode)if(dom.nodeName=="LI"&&(match2=/-(\d+)$/.exec(dom.id))&&+match2[1]{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})}),this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}mount(){this.updateSel()}update(update){var _a3,_b2,_c2;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);this.updateTooltipClass(update.state),cState!=prevState&&(this.updateSel(),((_a3=cState.open)===null||_a3===void 0?void 0:_a3.disabled)!=((_b2=prevState.open)===null||_b2===void 0?void 0:_b2.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!(!((_c2=cState.open)===null||_c2===void 0)&&_c2.disabled)))}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,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.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion}=open.options[open.selected],{info}=completion;if(!info)return;let infoResult=typeof info=="string"?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then(obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)}).catch(e=>logException(this.view.state,e,"completion info")):this.addInfoPane(infoResult,completion)}}addInfoPane(content2,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",content2.nodeType!=null)wrap.appendChild(content2),this.infoDestroy=null;else{let{dom,destroy:destroy2}=content2;wrap.appendChild(dom),this.infoDestroy=destroy2||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++)opt.nodeName!="LI"||!opt.id?i--:i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected");return set&&scrollIntoView(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottomrange.from||range.from==0))if(curSection=name2,typeof section!="string"&§ion.header)ul.appendChild(section.header(section));else{let header=ul.appendChild(document.createElement("completion-section"));header.textContent=name2}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match2);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.tonew CompletionTooltip(view,stateField,applyCompletion2)}__name(completionTooltip,"completionTooltip"),__name2(completionTooltip,"completionTooltip");function scrollIntoView(container,element){let parent=container.getBoundingClientRect(),self2=element.getBoundingClientRect(),scaleY=parent.height/container.offsetHeight;self2.topparent.bottom&&(container.scrollTop+=(self2.bottom-parent.bottom)/scaleY)}__name(scrollIntoView,"scrollIntoView"),__name2(scrollIntoView,"scrollIntoView");function score(option2){return(option2.boost||0)*100+(option2.apply?10:0)+(option2.info?5:0)+(option2.type?1:0)}__name(score,"score"),__name2(score,"score");function sortOptions(active,state){let options=[],sections=null,addOption=__name2(option2=>{options.push(option2);let{section}=option2.completion;if(section){sections||(sections=[]);let name2=typeof section=="string"?section:section.name;sections.some(s2=>s2.name==name2)||sections.push(typeof section=="string"?{name:name2}:section)}},"addOption");for(let a of active)if(a.hasResult()){let getMatch=a.result.getMatch;if(a.result.filter===!1)for(let option2 of a.result.options)addOption(new Option(option2,a.source,getMatch?getMatch(option2):[],1e9-options.length));else{let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option2 of a.result.options)if(matcher.match(option2.label)){let matched=option2.displayLabel?getMatch?getMatch(option2,matcher.matched):[]:matcher.matched;addOption(new Option(option2,a.source,matched,matcher.score+(option2.boost||0)))}}}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=__name2((a,b)=>{var _a3,_b2;return((_a3=a.rank)!==null&&_a3!==void 0?_a3:1e9)-((_b2=b.rank)!==null&&_b2!==void 0?_b2:1e9)||(a.nameb.score-a.score||compare2(a.completion,b.completion))){let cur2=opt.completion;!prev||prev.label!=cur2.label||prev.detail!=cur2.detail||prev.type!=null&&cur2.type!=null&&prev.type!=cur2.type||prev.apply!=cur2.apply||prev.boost!=cur2.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}__name(sortOptions,"sortOptions"),__name2(sortOptions,"sortOptions");const _CompletionDialog=class _CompletionDialog2{static{__name(this,"_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 _CompletionDialog2(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return prev&&active.some(a=>a.state==1)?new _CompletionDialog2(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):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;ib.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState,applyCompletion),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new _CompletionDialog2(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}};__name2(_CompletionDialog,"CompletionDialog");let CompletionDialog=_CompletionDialog;const _CompletionState=class _CompletionState2{static{__name(this,"_CompletionState")}constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new _CompletionState2(none$1,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(tr){let{state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map(source=>(this.active.find(s2=>s2.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0)?1:0)).update(tr,conf));active.length==this.active.length&&active.every((a,i)=>a==this.active[i])&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?open=CompletionDialog.build(active,state,this.id,open,conf):open&&open.disabled&&!active.some(a=>a.state==1)&&(open=null),!open&&active.every(a=>a.state!=1)&&active.some(a=>a.hasResult())&&(active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0):a));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new _CompletionState2(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}};__name2(_CompletionState,"CompletionState");let CompletionState=_CompletionState;function sameResults(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA-1&&(result["aria-activedescendant"]=id+"-"+selected),result}__name(makeAttrs,"makeAttrs"),__name2(makeAttrs,"makeAttrs");const none$1=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}__name(getUserEvent,"getUserEvent"),__name2(getUserEvent,"getUserEvent");const _ActiveSource=class _ActiveSource2{static{__name(this,"_ActiveSource")}constructor(source,state,explicitPos=-1){this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&value.state!=0&&(value=new _ActiveSource2(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new _ActiveSource2(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new _ActiveSource2(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new _ActiveSource2(this.source,1)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new _ActiveSource2(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new _ActiveSource2(this.source,this.state,changes.mapPos(this.explicitPos))}};__name2(_ActiveSource,"ActiveSource");let ActiveSource=_ActiveSource;const _ActiveResult=class _ActiveResult2 extends ActiveSource{static{__name(this,"_ActiveResult")}constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a3;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1:0);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;return checkValid(this.result.validFor,tr.state,from,to)?new _ActiveResult2(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new _ActiveResult2(this.source,explicitPos,updated,updated.from,(_a3=updated.to)!==null&&_a3!==void 0?_a3:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new _ActiveResult2(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}};__name2(_ActiveResult,"ActiveResult");let ActiveResult=_ActiveResult;function checkValid(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}__name(checkValid,"checkValid"),__name2(checkValid,"checkValid");const setActiveEffect=StateEffect.define({map(sources,mapping){return sources.map(s2=>s2.map(mapping))}}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create(){return CompletionState.start()},update(value,tr){return value.update(tr)},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});function applyCompletion(view,option2){const apply=option2.completion.apply||option2.completion.label;let result=view.state.field(completionState).active.find(a=>a.source==option2.source);return result instanceof ActiveResult?(typeof apply=="string"?view.dispatch(Object.assign(Object.assign({},insertCompletionText(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option2.completion)})):apply(view,option2.completion,result.from,result.to),!0):!1}__name(applyCompletion,"applyCompletion"),__name2(applyCompletion,"applyCompletion");function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected=by=="page"?0:length-1:selected>=length&&(selected=by=="page"?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}__name(moveCompletionSelection,"moveCompletionSelection"),__name2(moveCompletionSelection,"moveCompletionSelection");const acceptCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestampview.state.field(completionState,!1)?(view.dispatch({effects:startCompletionEffect.of(!0)}),!0):!1,"startCompletion"),closeCompletion=__name2(view=>{let cState=view.state.field(completionState,!1);return!cState||!cState.active.some(a=>a.state!=0)?!1:(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)},"closeCompletion"),_RunningQuery=class{static{__name(this,"_RunningQuery")}constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}};__name2(_RunningQuery,"RunningQuery");let RunningQuery=_RunningQuery;const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1e3,completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)active.state==1&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr));for(let i=0;iMaxUpdateCount&&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),this.debounceUpdate=cState.active.some(a=>a.state==1&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1,this.composing!=0)for(let tr of update.transactions)getUserEvent(tr)=="input"?this.composing=2:this.composing==2&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active)active.state==1&&!this.running.some(r=>r.active.source==active.source)&&this.startQuery(active)}startQuery(active){let{state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then(result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)})}scheduleAccept(){this.running.every(q=>q.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime))}accept(){var _a3;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source);if(current&¤t.state==1)if(query.done==null){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);active.state!=1&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);(!dialog||!dialog.dom.contains(event.relatedTarget))&&this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(!1)}),20),this.composing=0}}}),baseTheme$3=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:.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:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&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:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return mapped??void 0}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create(){return RangeSet.empty},update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closeBrackets(){return[inputHandler,bracketState]}__name(closeBrackets,"closeBrackets"),__name2(closeBrackets,"closeBrackets");const definedClosing="()[]{}<>";function closing(ch){for(let i=0;i{if((android?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert2.length>2||insert2.length==2&&codePointSize(codePointAt(insert2,0))==1||from!=sel.from||to!=sel.to)return!1;let tr=insertBracket(view.state,insert2);return tr?(view.dispatch(tr),!0):!1}),deleteBracketPair=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,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(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}});return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont},"deleteBracketPair"),closeBracketsKeymap=[{key:"Backspace",run:deleteBracketPair}];function insertBracket(state,bracket2){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket2==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket2==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}__name(insertBracket,"insertBracket"),__name2(insertBracket,"insertBracket");function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,from=>{from==pos&&(found=!0)}),found}__name(closedBracketAt,"closedBracketAt"),__name2(closedBracketAt,"closedBracketAt");function nextChar(doc2,pos){let next=doc2.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}__name(nextChar,"nextChar"),__name2(nextChar,"nextChar");function prevChar(doc2,pos){let prev=doc2.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}__name(prevChar,"prevChar"),__name2(prevChar,"prevChar");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);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleOpen,"handleOpen"),__name2(handleOpen,"handleOpen");function handleClose(state,_open,close){let dont=null,changes=state.changeByRange(range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range});return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}__name(handleClose,"handleClose"),__name2(handleClose,"handleClose");function handleSame(state,token,allowTriple,config2){let stringPrefixes=config2.stringPrefixes||defaults.stringPrefixes,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)};if(closedBracketAt(state,pos)){let content2=allowTriple&&state.sliceDoc(pos,pos+token.length*3)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content2.length,insert:content2},range:EditorSelection.cursor(pos+content2.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)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&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:!0,userEvent:"input.type"})}__name(handleSame,"handleSame"),__name2(handleSame,"handleSame");function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}__name(nodeStart,"nodeStart"),__name2(nodeStart,"nodeStart");function probablyInString(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),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)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}__name(probablyInString,"probablyInString"),__name2(probablyInString,"probablyInString");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}__name(canStartStringAt,"canStartStringAt"),__name2(canStartStringAt,"canStartStringAt");function autocompletion(config2={}){return[completionState,completionConfig.of(config2),completionPlugin,completionKeymapExt,baseTheme$3]}__name(autocompletion,"autocompletion"),__name2(autocompletion,"autocompletion");const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:acceptCompletion}],completionKeymapExt=Prec.highest(keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[])),toggleComment=__name2(target=>{let{state}=target,line=state.doc.lineAt(state.selection.main.from),config2=getConfig(target.state,line.from);return config2.line?toggleLineComment(target):config2.block?toggleBlockCommentByLine(target):!1},"toggleComment");function command(f,option2){return({state,dispatch})=>{if(state.readOnly)return!1;let tr=f(option2,state);return tr?(dispatch(state.update(tr)),!0):!1}}__name(command,"command"),__name2(command,"command");const toggleLineComment=command(changeLineComment,0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command((o,s2)=>changeBlockComment(o,s2,selectedLineRanges(s2)),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}__name(getConfig,"getConfig"),__name2(getConfig,"getConfig");const SearchMargin=50;function findBlockComment(state,{open,close},from,to){let textBefore=state.sliceDoc(from-SearchMargin,from),textAfter=state.sliceDoc(to,to+SearchMargin),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,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;to-from<=2*SearchMargin?startText=endText=state.sliceDoc(from,to):(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,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{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}}:null}__name(findBlockComment,"findBlockComment"),__name2(findBlockComment,"findBlockComment");function selectedLineRanges(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last2=ranges.length-1;last2>=0&&ranges[last2].to>fromLine.from?ranges[last2].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}__name(selectedLineRanges,"selectedLineRanges"),__name2(selectedLineRanges,"selectedLineRanges");function changeBlockComment(option2,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(option2!=2&&!comments.every(c=>c))return{changes:state.changes(ranges.map((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}]))};if(option2!=1&&comments.some(c=>c)){let changes=[];for(let i=0,comment2;iprevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty2=indent==line.length,comment2=line.text.slice(indent,indent+token.length)==token?indent:-1;indentl2.comment<0&&(!l2.empty||l2.single))){let changes=[];for(let{line,token,indent,empty:empty2,single}of lines)(single||!empty2)&&changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}else if(option2!=1&&lines.some(l2=>l2.comment>=0)){let changes=[];for(let{line,comment:comment2,token}of lines)if(comment2>=0){let from=line.from+comment2,to=from+token.length;line.text[to-line.from]==" "&&to++,changes.push({from,to})}return{changes}}return null}__name(changeLineComment,"changeLineComment"),__name2(changeLineComment,"changeLineComment");const fromHistory=Annotation.define(),isolateHistory=Annotation.define(),invertedEffects=Facet.define(),historyConfig=Facet.define({combine(configs){return combineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent2)=>isAdjacent2},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})}});function changeEnd(changes){let end=0;return changes.iterChangedRanges((_,to)=>end=to),end}__name(changeEnd,"changeEnd"),__name2(changeEnd,"changeEnd");const historyField_=StateField.define({create(){return HistoryState.empty},update(state,tr){let config2=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(changeEnd(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=from==0?state.undone:state.done;return item?other=updateBranch(other,other.length,config2.minDepth,item):other=addSelection(other,tr.startState.selection),new HistoryState(from==0?fromHist.rest:other,from==0?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if((isolate=="full"||isolate=="before")&&(state=state.isolate()),tr.annotation(Transaction.addToHistory)===!1)return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config2,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config2.newGroupDelay)),(isolate=="full"||isolate=="after")&&(state=state.isolate()),state},toJSON(value){return{done:value.done.map(e=>e.toJSON()),undone:value.undone.map(e=>e.toJSON())}},fromJSON(json2){return new HistoryState(json2.done.map(HistEvent.fromJSON),json2.undone.map(HistEvent.fromJSON))}});function history(config2={}){return[historyField_,historyConfig.of(config2),EditorView.domEventHandlers({beforeinput(e,view){let command2=e.inputType=="historyUndo"?undo:e.inputType=="historyRedo"?redo:null;return command2?(e.preventDefault(),command2(view)):!1}})]}__name(history,"history"),__name2(history,"history");function cmd(side,selection){return function({state,dispatch}){if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return tr?(dispatch(tr),!0):!1}}__name(cmd,"cmd"),__name2(cmd,"cmd");const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0),_HistEvent=class _HistEvent2{static{__name(this,"_HistEvent")}constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new _HistEvent2(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a3,_b2,_c2;return{changes:(_a3=this.changes)===null||_a3===void 0?void 0:_a3.toJSON(),mapped:(_b2=this.mapped)===null||_b2===void 0?void 0:_b2.toJSON(),startSelection:(_c2=this.startSelection)===null||_c2===void 0?void 0:_c2.toJSON(),selectionsAfter:this.selectionsAfter.map(s2=>s2.toJSON())}}static fromJSON(json2){return new _HistEvent2(json2.changes&&ChangeSet.fromJSON(json2.changes),[],json2.mapped&&ChangeDesc.fromJSON(json2.mapped),json2.startSelection&&EditorSelection.fromJSON(json2.startSelection),json2.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new _HistEvent2(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none)}static selection(selections){return new _HistEvent2(void 0,none,void 0,void 0,selections)}};__name2(_HistEvent,"HistEvent");let HistEvent=_HistEvent;function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}__name(updateBranch,"updateBranch"),__name2(updateBranch,"updateBranch");function isAdjacent(a,b){let ranges=[],isAdjacent2=!1;return a.iterChangedRanges((f,t2)=>ranges.push(f,t2)),b.iterChangedRanges((_f,_t,f,t2)=>{for(let i=0;i=from&&f<=to&&(isAdjacent2=!0)}}),isAdjacent2}__name(isAdjacent,"isAdjacent"),__name2(isAdjacent,"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}__name(eqSelectionShape,"eqSelectionShape"),__name2(eqSelectionShape,"eqSelectionShape");function conc(a,b){return a.length?b.length?a.concat(b):a:b}__name(conc,"conc"),__name2(conc,"conc");const none=[],MaxSelectionsPerEvent=200;function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-MaxSelectionsPerEvent));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}else return[HistEvent.selection([selection])]}__name(addSelection,"addSelection"),__name2(addSelection,"addSelection");function popSelection(branch){let last2=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last2.setSelAfter(last2.selectionsAfter.slice(0,last2.selectionsAfter.length-1)),newBranch}__name(popSelection,"popSelection"),__name2(popSelection,"popSelection");function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}else mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none}__name(addMappingToBranch,"addMappingToBranch"),__name2(addMappingToBranch,"addMappingToBranch");function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map(s2=>s2.map(mapping)):none,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}__name(mapEvent,"mapEvent"),__name2(mapEvent,"mapEvent");const joinableUserEvent=/^(input\.type|delete)($|\.)/,_HistoryState=class _HistoryState2{static{__name(this,"_HistoryState")}constructor(done,undone,prevTime=0,prevUserEvent=void 0){this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new _HistoryState2(this.done,this.undone):this}addChanges(event,time,userEvent,config2,tr){let done=this.done,lastEvent=done[done.length-1];return lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTime0&&time-this.prevTimerange.empty?view.moveByChar(range,forward):rangeEnd(range,forward))}__name(cursorByChar,"cursorByChar"),__name2(cursorByChar,"cursorByChar");function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}__name(ltrAtCursor,"ltrAtCursor"),__name2(ltrAtCursor,"ltrAtCursor");const cursorCharLeft=__name2(view=>cursorByChar(view,!ltrAtCursor(view)),"cursorCharLeft"),cursorCharRight=__name2(view=>cursorByChar(view,ltrAtCursor(view)),"cursorCharRight");function cursorByGroup(view,forward){return moveSel(view,range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward))}__name(cursorByGroup,"cursorByGroup"),__name2(cursorByGroup,"cursorByGroup");const cursorGroupLeft=__name2(view=>cursorByGroup(view,!ltrAtCursor(view)),"cursorGroupLeft"),cursorGroupRight=__name2(view=>cursorByGroup(view,ltrAtCursor(view)),"cursorGroupRight");function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}__name(interestingNode,"interestingNode"),__name2(interestingNode,"interestingNode");function moveBySyntax(state,start,forward){let pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}let bracket2=pos.type.prop(bracketProp),match2,newPos;return bracket2&&(match2=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match2.matched?newPos=forward?match2.end.to:match2.end.from:newPos=forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}__name(moveBySyntax,"moveBySyntax"),__name2(moveBySyntax,"moveBySyntax");const cursorSyntaxLeft=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"cursorSyntaxLeft"),cursorSyntaxRight=__name2(view=>moveSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"cursorSyntaxRight");function cursorByLine(view,forward){return moveSel(view,range=>{if(!range.empty)return rangeEnd(range,forward);let moved2=view.moveVertically(range,forward);return moved2.head!=range.head?moved2:view.moveToLineBoundary(range,forward)})}__name(cursorByLine,"cursorByLine"),__name2(cursorByLine,"cursorByLine");const cursorLineUp=__name2(view=>cursorByLine(view,!1),"cursorLineUp"),cursorLineDown=__name2(view=>cursorByLine(view,!0),"cursorLineDown");function pageInfo(view){let selfScroll=view.scrollDOM.clientHeightrange.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward));if(selection.eq(state.selection))return!1;let effect;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottomcursorByPage(view,!1),"cursorPageUp"),cursorPageDown=__name2(view=>cursorByPage(view,!0),"cursorPageDown");function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved2=view.moveToLineBoundary(start,forward);if(moved2.head==start.head&&moved2.head!=(forward?line.to:line.from)&&(moved2=view.moveToLineBoundary(start,forward,!1)),!forward&&moved2.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved2=EditorSelection.cursor(line.from+space))}return moved2}__name(moveByLineBoundary,"moveByLineBoundary"),__name2(moveByLineBoundary,"moveByLineBoundary");const cursorLineBoundaryForward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!0)),"cursorLineBoundaryForward"),cursorLineBoundaryBackward=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!1)),"cursorLineBoundaryBackward"),cursorLineBoundaryLeft=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"cursorLineBoundaryLeft"),cursorLineBoundaryRight=__name2(view=>moveSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"cursorLineBoundaryRight"),cursorLineStart=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1)),"cursorLineStart"),cursorLineEnd=__name2(view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1)),"cursorLineEnd");function toMatchingBracket(state,dispatch,extend2){let found=!1,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.headtoMatchingBracket(state,dispatch,!1),"cursorMatchingBracket");function extendSel(view,how){let selection=updateSel(view.state.selection,range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)});return selection.eq(view.state.selection)?!1:(view.dispatch(setSel(view.state,selection)),!0)}__name(extendSel,"extendSel"),__name2(extendSel,"extendSel");function selectByChar(view,forward){return extendSel(view,range=>view.moveByChar(range,forward))}__name(selectByChar,"selectByChar"),__name2(selectByChar,"selectByChar");const selectCharLeft=__name2(view=>selectByChar(view,!ltrAtCursor(view)),"selectCharLeft"),selectCharRight=__name2(view=>selectByChar(view,ltrAtCursor(view)),"selectCharRight");function selectByGroup(view,forward){return extendSel(view,range=>view.moveByGroup(range,forward))}__name(selectByGroup,"selectByGroup"),__name2(selectByGroup,"selectByGroup");const selectGroupLeft=__name2(view=>selectByGroup(view,!ltrAtCursor(view)),"selectGroupLeft"),selectGroupRight=__name2(view=>selectByGroup(view,ltrAtCursor(view)),"selectGroupRight"),selectSyntaxLeft=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view))),"selectSyntaxLeft"),selectSyntaxRight=__name2(view=>extendSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view))),"selectSyntaxRight");function selectByLine(view,forward){return extendSel(view,range=>view.moveVertically(range,forward))}__name(selectByLine,"selectByLine"),__name2(selectByLine,"selectByLine");const selectLineUp=__name2(view=>selectByLine(view,!1),"selectLineUp"),selectLineDown=__name2(view=>selectByLine(view,!0),"selectLineDown");function selectByPage(view,forward){return extendSel(view,range=>view.moveVertically(range,forward,pageInfo(view).height))}__name(selectByPage,"selectByPage"),__name2(selectByPage,"selectByPage");const selectPageUp=__name2(view=>selectByPage(view,!1),"selectPageUp"),selectPageDown=__name2(view=>selectByPage(view,!0),"selectPageDown"),selectLineBoundaryForward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!0)),"selectLineBoundaryForward"),selectLineBoundaryBackward=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!1)),"selectLineBoundaryBackward"),selectLineBoundaryLeft=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view))),"selectLineBoundaryLeft"),selectLineBoundaryRight=__name2(view=>extendSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view))),"selectLineBoundaryRight"),selectLineStart=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)),"selectLineStart"),selectLineEnd=__name2(view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)),"selectLineEnd"),cursorDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:0})),!0),"cursorDocStart"),cursorDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.doc.length})),!0),"cursorDocEnd"),selectDocStart=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0),"selectDocStart"),selectDocEnd=__name2(({state,dispatch})=>(dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0),"selectDocEnd"),selectAll=__name2(({state,dispatch})=>(dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0),"selectAll"),selectLine=__name2(({state,dispatch})=>{let ranges=selectedLineBlocks(state).map(({from,to})=>EditorSelection.range(from,Math.min(to+1,state.doc.length)));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0},"selectLine"),selectParentSyntax=__name2(({state,dispatch})=>{let selection=updateSel(state.selection,range=>{var _a3;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from=range.to||context.to>range.to&&context.from<=range.from||!(!((_a3=context.parent)===null||_a3===void 0)&&_a3.parent));)context=context.parent;return EditorSelection.range(context.to,context.from)});return dispatch(setSel(state,selection)),!0},"selectParentSyntax"),simplifySelection=__name2(({state,dispatch})=>{let cur2=state.selection,selection=null;return cur2.ranges.length>1?selection=EditorSelection.create([cur2.main]):cur2.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur2.main.head)])),selection?(dispatch(setSel(state,selection)),!0):!1},"simplifySelection");function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state}=target,changes=state.changeByRange(range=>{let{from,to}=range;if(from==to){let towards=by(from);towardsfrom&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range}:{changes:{from,to},range:EditorSelection.cursor(from)}});return changes.changes.empty?!1:(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:event=="delete.selection"?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}__name(deleteBy,"deleteBy"),__name2(deleteBy,"deleteBy");function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map(f=>f(target)))ranges.between(pos,pos,(from,to)=>{frompos&&(pos=forward?to:from)});return pos}__name(skipAtomic,"skipAtomic"),__name2(skipAtomic,"skipAtomic");const deleteByChar=__name2((target,forward)=>deleteBy(target,pos=>{let{state}=target,line=state.doc.lineAt(pos),before,targetPos;if(!forward&&pos>line.from&&posdeleteByChar(view,!1),"deleteCharBackward"),deleteCharForward=__name2(view=>deleteByChar(view,!0),"deleteCharForward"),deleteByGroup=__name2((target,forward)=>deleteBy(target,start=>{let pos=start,{state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar2=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar2);if(cat!=null&&nextCat!=cat)break;(nextChar2!=" "||pos!=start)&&(cat=nextCat),pos=next}return pos}),"deleteByGroup"),deleteGroupBackward=__name2(target=>deleteByGroup(target,!1),"deleteGroupBackward"),deleteGroupForward=__name2(target=>deleteByGroup(target,!0),"deleteGroupForward"),deleteToLineEnd=__name2(view=>deleteBy(view,pos=>{let lineEnd=view.lineBlockAt(pos).to;return posdeleteBy(view,pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}),"deleteToLineStart"),splitLine=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)}));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0},"splitLine"),transposeChars=__name2(({state,dispatch})=>{if(state.readOnly)return!1;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),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from,to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}});return changes.changes.empty?!1:(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)},"transposeChars");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)),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}__name(selectedLineBlocks,"selectedLineBlocks"),__name2(selectedLineBlocks,"selectedLineBlocks");function moveLine(state,dispatch,forward){if(state.readOnly)return!1;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),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(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(EditorSelection.range(r.anchor-size,r.head-size))}}return changes.length?(dispatch(state.update({changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0):!1}__name(moveLine,"moveLine"),__name2(moveLine,"moveLine");const moveLineUp=__name2(({state,dispatch})=>moveLine(state,dispatch,!1),"moveLineUp"),moveLineDown=__name2(({state,dispatch})=>moveLine(state,dispatch,!0),"moveLineDown");function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}__name(copyLine,"copyLine"),__name2(copyLine,"copyLine");const copyLineUp=__name2(({state,dispatch})=>copyLine(state,dispatch,!1),"copyLineUp"),copyLineDown=__name2(({state,dispatch})=>copyLine(state,dispatch,!0),"copyLineDown"),deleteLine=__name2(view=>{if(view.state.readOnly)return!1;let{state}=view,changes=state.changes(selectedLineBlocks(state).map(({from,to})=>(from>0?from--:toview.moveVertically(range,!0)).map(changes);return view.dispatch({changes,selection,scrollIntoView:!0,userEvent:"delete.line"}),!0},"deleteLine");function isBetweenBrackets(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos),closedBy;return 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?{from:before.to,to:after.from}:null}__name(isBetweenBrackets,"isBetweenBrackets"),__name2(isBetweenBrackets,"isBetweenBrackets");const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return({state,dispatch})=>{if(state.readOnly)return!1;let changes=state.changeByRange(range=>{let{from,to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&isBetweenBrackets(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(indent==null&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);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:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}})}__name(changeBySelectedLine,"changeBySelectedLine"),__name2(changeBySelectedLine,"changeBySelectedLine");const indentSelection=__name2(({state,dispatch})=>{if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return found??-1}}),changes=changeBySelectedLine(state,(line,changes2,range)=>{let indent=getIndentation(context,line.from);if(indent==null)return;/\S/.test(line.text)||(indent=0);let cur2=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur2!=norm||range.fromstate.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})}),{userEvent:"input.indent"})),!0),"indentMore"),indentLess=__name2(({state,dispatch})=>state.readOnly?!1:(dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert2=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep({mac:b.key,run:b.run,shift:b.shift}))),defaultKeymap=[{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:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:!0},{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}].concat(standardKeymap),indentWithTab={key:"Tab",run:indentMore,shift:indentLess},_Stack=class _Stack2{static{__name(this,"_Stack")}constructor(p,stack,state,reducePos,pos,score2,buffer,bufferBase,curContext,lookAhead=0,parent){this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score2,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return`[${this.stack.filter((_,i)=>i%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(p,state,pos=0){let cx=p.parser.context;return new _Stack2(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a3;let depth=action>>19,type=action&65535,{parser:parser2}=this.p,dPrec=parser2.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),depth==0){this.pushState(parser2.getGoto(this.state,type,!0),this.reducePos),type=2e3&&!(!((_a3=this.p.parser.nodeSet.types[type])===null||_a3===void 0)&&_a3.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSizebase2;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end,size=4,isReduce=!1){if(term==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&cur2.buffer[top2-4]==0&&cur2.buffer[top2-1]>-1){if(start==end)return;if(cur2.buffer[top2-2]>=start){cur2.buffer[top2-2]=end;return}}}if(!isReduce||this.pos==end)this.buffer.push(term,start,end,size);else{let index2=this.buffer.length;if(index2>0&&this.buffer[index2-4]!=0)for(;index2>0&&this.buffer[index2-2]>end;)this.buffer[index2]=this.buffer[index2-4],this.buffer[index2+1]=this.buffer[index2-3],this.buffer[index2+2]=this.buffer[index2-2],this.buffer[index2+3]=this.buffer[index2-1],index2-=4,size>4&&(size-=4);this.buffer[index2]=term,this.buffer[index2+1]=start,this.buffer[index2+2]=end,this.buffer[index2+3]=size}}shift(action,next,nextEnd){let start=this.pos;if(action&131072)this.pushState(action&65535,this.pos);else if(action&262144)this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4);else{let nextState=action,{parser:parser2}=this.p;(nextEnd>this.pos||next<=parser2.maxNode)&&(this.pos=nextEnd,parser2.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser2.maxNode&&this.buffer.push(next,start,nextEnd,4)}}apply(action,next,nextEnd){action&65536?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index2=this.p.reused.length-1;(index2<0||this.p.reused[index2]!=value)&&(this.p.reused.push(value),index2++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index2,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off2=parent.buffer.length;for(;off2>0&&parent.buffer[off2-2]>parent.reducePos;)off2-=4;let buffer=parent.buffer.slice(off2),base2=parent.bufferBase+off2;for(;parent&&base2==parent.bufferBase;)parent=parent.parent;return new _Stack2(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base2,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(action==0)return!1;if(!(action&65536))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let i=0,s2;ii2&1&&v==s2)||best.push(nextStates[i],s2)}nextStates=best}let result=[];for(let i=0;i>19,term=reduce&65535,target=this.stack.length-depth*3;if(target<0||parser2.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(backup==null)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser2}=this.p,seen=[],explore=__name2((state,depth)=>{if(!seen.includes(state))return seen.push(state),parser2.allActions(state,action=>{if(!(action&393216))if(action&65536){let rDepth=(action>>19)-depth;if(rDepth>1){let term=action&65535,target=this.stack.length-rDepth*3;if(target>=0&&parser2.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(found!=null)return found}})},"explore");return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:parser2}=this.p;return parser2.data[parser2.stateSlot(this.state,1)]==65535&&!parser2.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;ithis.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}};__name2(_Stack,"Stack");let Stack=_Stack;const _StackContext=class{static{__name(this,"_StackContext")}constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}};__name2(_StackContext,"StackContext");let StackContext=_StackContext;var Recover;(function(Recover2){Recover2[Recover2.Insert=200]="Insert",Recover2[Recover2.Delete=190]="Delete",Recover2[Recover2.Reduce=100]="Reduce",Recover2[Recover2.MaxNext=4]="MaxNext",Recover2[Recover2.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover2[Recover2.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover2[Recover2.MinBigReduction=2e3]="MinBigReduction"})(Recover||(Recover={}));const _SimulatedStack=class{static{__name(this,"_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,depth=action>>19;depth==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(depth-1)*3;let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}};__name2(_SimulatedStack,"SimulatedStack");let SimulatedStack=_SimulatedStack;const _StackBufferCursor=class _StackBufferCursor2{static{__name(this,"_StackBufferCursor")}constructor(stack,pos,index2){this.stack=stack,this.pos=pos,this.index=index2,this.buffer=stack.buffer,this.index==0&&this.maybeNext()}static create(stack,pos=stack.bufferBase+stack.buffer.length){return new _StackBufferCursor2(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;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,this.index==0&&this.maybeNext()}fork(){return new _StackBufferCursor2(this.stack,this.pos,this.index)}};__name2(_StackBufferCursor,"StackBufferCursor");let StackBufferCursor=_StackBufferCursor;function decodeArray(input,Type=Uint16Array){if(typeof input!="string")return input;let array=null;for(let pos=0,out=0;pos=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}__name(decodeArray,"decodeArray"),__name2(decodeArray,"decodeArray");const _CachedToken=class{static{__name(this,"_CachedToken")}constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};__name2(_CachedToken,"CachedToken");let CachedToken=_CachedToken;const nullToken=new CachedToken,_InputStream=class{static{__name(this,"_InputStream")}constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,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()}resolveOffset(offset2,assoc){let range=this.range,index2=this.rangeIndex,pos=this.pos+offset2;for(;posrange.to:pos>=range.to;){if(index2==this.ranges.length-1)return null;let next=this.ranges[++index2];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pospos)return Math.max(pos,range.from);return this.end}peek(offset2){let idx=this.chunkOff+offset2,pos,result;if(idx>=0&&idx=this.chunk2Pos&&posrange.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token,endOffset=0){let end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(end==null||end=this.chunk2Pos&&this.posthis.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(n2=1){for(this.chunkOff+=n2;this.pos+n2>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n2-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n2,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos=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;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}};__name2(_InputStream,"InputStream");let InputStream=_InputStream;const _TokenGroup=class{static{__name(this,"_TokenGroup")}constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser2}=stack.p;readToken(this.data,input,stack,this.id,parser2.data,parser2.tokenPrecTable)}};__name2(_TokenGroup,"TokenGroup");let TokenGroup=_TokenGroup;TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1,TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<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];if(input.next<0&&high>low&&data[accEnd+high*3-3]==65535&&data[accEnd+high*3-3]==65535){state=data[accEnd+high*3-1];continue scan}for(;low>1,index2=accEnd+mid+(mid<<1),from=data[index2],to=data[index2+1]||65536;if(next=to)low=mid+1;else{state=data[index2+2],input.advance();continue scan}}break}}__name(readToken,"readToken"),__name2(readToken,"readToken");function findOffset(data,start,term){for(let i=start,next;(next=data[i])!=65535;i++)if(next==term)return i-start;return-1}__name(findOffset,"findOffset"),__name2(findOffset,"findOffset");function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}__name(cutAt,"cutAt"),__name2(cutAt,"cutAt");const _FragmentCursor=class{static{__name(this,"_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){for(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;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}nodeAt(pos){if(pospos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last2]++,this.nextStart=start+next.length}}};__name2(_FragmentCursor,"FragmentCursor");let FragmentCursor=_FragmentCursor;const _TokenCache=class{static{__name(this,"_TokenCache")}constructor(parser2,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser2.tokenizers.map(_=>new CachedToken)}getActions(stack){let actionIndex=0,main=null,{parser:parser2}=stack.p,{tokenizers}=parser2,mask=parser2.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;itoken.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),token.value!=0)){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),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),!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,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos,p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser2}=stack.p;for(let i=0;i=0&&stack.p.parser.dialect.allows(result>>1)){result&1?token.extended=result>>1:token.value=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index2){for(let i=0;iparser2.bufferLength*4?new FragmentCursor(fragments,parser2.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[],stopped,stoppedTokens;if(this.bigReductionCount>300&&stacks.length==1){let[s2]=stacks;for(;s2.forceReduce()&&s2.stack.length&&s2.stack[s2.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;ipos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{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)return this.stackToTree(finished);if(this.parser.strict)throw verbose&&stopped&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+pos);this.recovering||(this.recovering=5)}if(this.recovering&&stopped){let finished=this.stoppedAt!=null&&stopped[0].pos>this.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=this.recovering==1?1:this.recovering*3;if(newStacks.length>maxRemaining)for(newStacks.sort((a,b)=>b.score-a.score);newStacks.length>maxRemaining;)newStacks.pop();newStacks.some(s2=>s2.reducePos>pos)&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i500&&other.buffer.length>500)if((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)newStacks.splice(j--,1);else{newStacks.splice(i--,1);continue outer}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i ":"";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 match2=this.parser.nodeSet.types[cached.type.id]==cached.type?parser2.getGoto(stack.state,cached.type.id):-1;if(match2>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match2),verbose&&console.log(base2+this.stackID(stack)+` (via reuse of ${parser2.getName(cached.type.id)})`),!0;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=parser2.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base2+this.stackID(stack)+` (via always-reduce ${parser2.getName(defaultReduce&65535)})`),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;istart?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i ":"";if(stack.deadEnd&&(restarted||(restarted=!0,stack.restart(),verbose&&console.log(base2+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))))continue;let force=stack.split(),forceBase=base2;for(let j=0;force.forceReduce()&&j<10&&(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),!this.advanceFully(force,newStacks));j++)verbose&&(forceBase=this.stackID(force)+" -> ");for(let insert2 of stack.recoverByInsert(token))verbose&&console.log(base2+this.stackID(insert2)+" (via recover-insert)"),this.advanceFully(insert2,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base2+this.stackID(stack)+` (via recover-delete ${this.parser.getName(token)})`),pushStackDedup(stack,newStacks)):(!finished||finished.scorespec.topRules[r][1]),nodeProps=[];for(let i=0;i=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((name2,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name2,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:i==0,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1}))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,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;itypeof 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 parse2=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse2=w(parse2,input,fragments,ranges);return parse2}getGoto(state,term,loose=!1){let table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last2=groupTag&1,target=table[pos++];if(last2&&loose)return target;for(let end=pos+(groupTag>>1);pos0}validAction(state,action){return!!this.allActions(state,a=>a==action?!0:null)}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);result==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=pair(this.data,i+2);else break;if(!(this.data[i+2]&1)){let value=this.data[i+1];result.some((v,i2)=>i2&1&&v==value)||result.push(this.data[i],value)}}return result}configure(config2){let copy=Object.assign(Object.create(_LRParser2.prototype),this);if(config2.props&&(copy.nodeSet=this.nodeSet.extend(...config2.props)),config2.top){let info=this.topRules[config2.top];if(!info)throw new RangeError(`Invalid top rule name ${config2.top}`);copy.top=info}return config2.tokenizers&&(copy.tokenizers=this.tokenizers.map(t2=>{let found=config2.tokenizers.find(r=>r.from==t2);return found?found.to:t2})),config2.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map((s2,i)=>{let found=config2.specializers.find(r=>r.from==s2.external);if(!found)return s2;let spec=Object.assign(Object.assign({},s2),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec})),config2.contextTracker&&(copy.context=config2.contextTracker),config2.dialect&&(copy.dialect=this.parseDialect(config2.dialect)),config2.strict!=null&&(copy.strict=config2.strict),config2.wrap&&(copy.wrappers=copy.wrappers.concat(config2.wrap)),config2.bufferLength!=null&&(copy.bufferLength=config2.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec2=this.dynamicPrecedences;return prec2==null?0:prec2[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map(()=>!1);if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;istopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.scorespec.external(value,stack)<<1|mask}return spec.get}__name(getSpecializer,"getSpecializer"),__name2(getSpecializer,"getSpecializer");const jsonHighlighting=styleTags({String:tags.string,Number:tags.number,"True False":tags.bool,PropertyName:tags.propertyName,Null:tags.null,",":tags.separator,"[ ]":tags.squareBracket,"{ }":tags.brace}),parser=LRParser.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",stateData:"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",goto:"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"\u26A0 JsonText True False Null Number String } { Object Property PropertyName ] [ Array",maxTerm:25,nodeProps:[["openedBy",7,"{",12,"["],["closedBy",8,"}",13,"]"]],propSources:[jsonHighlighting],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),jsonParseLinter=__name2(()=>view=>{try{JSON.parse(view.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;const pos=getErrorPosition(e,view.state.doc);return[{from:pos,message:e.message,severity:"error",to:pos}]}return[]},"jsonParseLinter");function getErrorPosition(error,doc2){let m;return(m=error.message.match(/at position (\d+)/))?Math.min(+m[1],doc2.length):(m=error.message.match(/at line (\d+) column (\d+)/))?Math.min(doc2.line(+m[1]).from+ +m[2]-1,doc2.length):0}__name(getErrorPosition,"getErrorPosition"),__name2(getErrorPosition,"getErrorPosition");const jsonLanguage=LRLanguage.define({name:"json",parser:parser.configure({props:[indentNodeProp.add({Object:continuedIndent({except:/^\s*\}/}),Array:continuedIndent({except:/^\s*\]/})}),foldNodeProp.add({"Object Array":foldInside})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function json(){return new LanguageSupport(jsonLanguage)}__name(json,"json"),__name2(json,"json");function crelt(){var elt=arguments[0];typeof elt=="string"&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&typeof next=="object"&&next.nodeType==null&&!Array.isArray(next)){for(var name2 in next)if(Object.prototype.hasOwnProperty.call(next,name2)){var value=next[name2];typeof value=="string"?elt.setAttribute(name2,value):value!=null&&(elt[name2]=value)}i++}for(;id.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to)),!0);return new _LintState2(ranges,panel,findDiagnostic(ranges))}};__name2(_LintState,"LintState");let LintState=_LintState;function findDiagnostic(diagnostics,diagnostic=null,after=0){let found=null;return diagnostics.between(after,1e9,(from,to,{spec})=>{if(!(diagnostic&&spec.diagnostic!=diagnostic))return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1}),found}__name(findDiagnostic,"findDiagnostic"),__name2(findDiagnostic,"findDiagnostic");function hideTooltip(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!!(tr.effects.some(e=>e.is(setDiagnosticsEffect))||tr.changes.touchesRange(line.from,line.to))}__name(hideTooltip,"hideTooltip"),__name2(hideTooltip,"hideTooltip");function maybeEnableLint(state,effects){return state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions))}__name(maybeEnableLint,"maybeEnableLint"),__name2(maybeEnableLint,"maybeEnableLint");function setDiagnostics(state,diagnostics){return{effects:maybeEnableLint(state,[setDiagnosticsEffect.of(diagnostics)])}}__name(setDiagnostics,"setDiagnostics"),__name2(setDiagnostics,"setDiagnostics");const setDiagnosticsEffect=StateEffect.define(),togglePanel$1=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create(){return new LintState(Decoration.none,null,null)},update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel$1)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f=>[showPanel.from(f,val=>val.panel),EditorView.decorations.from(f,s2=>s2.diagnostics)]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function lintTooltip(view,pos,side){let{diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),(from,to,{spec})=>{pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(posrenderDiagnostic(view,d,!1)))}__name(diagnosticsTooltip,"diagnosticsTooltip"),__name2(diagnosticsTooltip,"diagnosticsTooltip");const openLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);(!field||!field.panel)&&view.dispatch({effects:maybeEnableLint(view.state,[togglePanel$1.of(!0)])});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},"openLintPanel"),closeLintPanel=__name2(view=>{let field=view.state.field(lintState,!1);return!field||!field.panel?!1:(view.dispatch({effects:togglePanel$1.of(!1)}),!0)},"closeLintPanel"),nextDiagnostic=__name2(view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to)?!1:(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)},"nextDiagnostic"),lintKeymap=[{key:"Mod-Shift-m",run:openLintPanel,preventDefault:!0},{key:"F8",run:nextDiagnostic}],lintPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.timeout=-1,this.set=!0;let{delay}=view.state.facet(lintConfig);this.lintTime=Date.now()+delay,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,delay)}run(){let now2=Date.now();if(now2Promise.resolve(source(this.view)))).then(annotations=>{let all=annotations.reduce((a,b)=>a.concat(b));this.view.state.doc==state.doc&&this.view.dispatch(setDiagnostics(this.view.state,all))},error=>{logException(this.view.state,error)})}}update(update){let config2=update.state.facet(lintConfig);(update.docChanged||config2!=update.startState.facet(lintConfig)||config2.needsRefresh&&config2.needsRefresh(update))&&(this.lintTime=Date.now()+config2.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,config2.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),lintConfig=Facet.define({combine(input){return Object.assign({sources:input.map(i=>i.source)},combineConfig(input.map(i=>i.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))}});function linter(source,config2={}){return[lintConfig.of({source,config:config2}),lintPlugin,lintExtensions]}__name(linter,"linter"),__name2(linter,"linter");function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name2}of actions){for(let i=0;ic.toLowerCase()==ch.toLowerCase())){assigned.push(ch);continue actions}}assigned.push("")}return assigned}__name(assignKeys,"assignKeys"),__name2(assignKeys,"assignKeys");function renderDiagnostic(view,diagnostic,inPanel){var _a3;let keys2=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),(_a3=diagnostic.actions)===null||_a3===void 0?void 0:_a3.map((action,i)=>{let fired=!1,click=__name2(e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},"click"),{name:name2}=action,keyIndex=keys2[i]?name2.indexOf(keys2[i]):-1,nameElt=keyIndex<0?name2:[name2.slice(0,keyIndex),crelt("u",name2.slice(keyIndex,keyIndex+1)),name2.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":` Action: ${name2}${keyIndex<0?"":` (access key "${keys2[i]})"`}.`},nameElt)}),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}__name(renderDiagnostic,"renderDiagnostic"),__name2(renderDiagnostic,"renderDiagnostic");const _DiagnosticWidget=class extends WidgetType{static{__name(this,"_DiagnosticWidget")}constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}};__name2(_DiagnosticWidget,"DiagnosticWidget");let DiagnosticWidget=_DiagnosticWidget;const _PanelItem=class{static{__name(this,"_PanelItem")}constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}};__name2(_PanelItem,"PanelItem");let PanelItem=_PanelItem;const _LintPanel=class _LintPanel2{static{__name(this,"_LintPanel")}constructor(view){this.view=view,this.items=[];let onkeydown=__name2(event=>{if(event.keyCode==27)closeLintPanel(this.view),this.view.focus();else if(event.keyCode==38||event.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(event.keyCode==40||event.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(event.keyCode==36)this.moveSelection(0);else if(event.keyCode==35)this.moveSelection(this.items.length-1);else if(event.keyCode==13)this.view.focus();else if(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0){let{diagnostic}=this.items[this.selectedIndex],keys2=assignKeys(diagnostic.actions);for(let i=0;i{for(let i=0;icloseLintPanel(this.view)},"\xD7")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i{let found=-1,item;for(let j=i;ji&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++});i({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel,panel})=>{sel.toppanel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm2(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}__name(rm2,"rm2"),__name2(rm2,"rm");for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm2();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm2()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let field=this.view.state.field(lintState),selection=findDiagnostic(field.diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new _LintPanel2(view)}};__name2(_LintPanel,"LintPanel");let LintPanel=_LintPanel;function svg(content2,attrs='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(content2)}')`}__name(svg,"svg"),__name2(svg,"svg");function underline(color){return svg(``,'width="6" height="3"')}__name(underline,"underline"),__name2(underline,"underline");const baseTheme$2=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],state=>{let{selected,panel}=state.field(lintState);return!selected||!panel||selected.from==selected.to?Decoration.none:Decoration.set([activeMark.range(selected.from,selected.to)])}),hoverTooltip(lintTooltip,{hideOn:hideTooltip}),baseTheme$2],basicNormalize=typeof String.prototype.normalize=="function"?x=>x.normalize("NFKD"):x=>x,_SearchCursor=class{static{__name(this,"_SearchCursor")}constructor(text,query,from=0,to=text.length,normalize,test){this.test=test,this.value={from:0,to:0},this.done=!1,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){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match2=this.match(code,pos);if(i==norm.length-1){if(match2)return this.value=match2,this;break}pos==start&&ithis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off2=this.matchPos-this.curLineStart;;){this.re.lastIndex=off2;let match2=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match2){let from=this.curLineStart+match2.index,to=from+match2[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(fromthis.value.to)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this;off2=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new _FlattenedDoc2(from,doc2.sliceString(from,to));return flattened.set(doc2,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc2.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off2=this.re.lastIndex=this.matchPos-this.flat.from,match2=this.re.exec(this.flat.text);if(match2&&!match2[0]&&match2.index==off2&&(this.re.lastIndex=off2+1,match2=this.re.exec(this.flat.text)),match2){let from=this.flat.from+match2.index,to=from+match2[0].length;if((this.flat.to>=this.to||match2.index+match2[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match2)))return this.value={from,to,match:match2},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};__name2(_MultilineRegExpCursor,"MultilineRegExpCursor");let MultilineRegExpCursor=_MultilineRegExpCursor;typeof Symbol<"u"&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});function validRegExp(source){try{return new RegExp(source,baseFlags),!0}catch{return!1}}__name(validRegExp,"validRegExp"),__name2(validRegExp,"validRegExp");function toCharEnd(text,pos){if(pos>=text.length)return pos;let line=text.lineAt(pos),next;for(;pos=56320&&next<57344;)pos++;return pos}__name(toCharEnd,"toCharEnd"),__name2(toCharEnd,"toCharEnd");function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"}),dom=crelt("form",{class:"cm-gotoLine",onkeydown:event=>{event.keyCode==27?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):event.keyCode==13&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")));function go(){let match2=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match2)return;let{state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match2,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*(sign=="-"?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*(sign=="-"?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line))),selection=EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length)));view.dispatch({effects:[dialogEffect.of(!1),EditorView.scrollIntoView(selection.from,{y:"center"})],selection}),view.focus()}return __name(go,"go"),__name2(go,"go"),{dom}}__name(createLineDialog,"createLineDialog"),__name2(createLineDialog,"createLineDialog");const dialogEffect=StateEffect.define(),dialogField=StateField.define({create(){return!0},update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f=>showPanel.from(f,val=>val?createLineDialog:null)}),gotoLine=__name2(view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];view.state.field(dialogField,!1)==null&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1])),view.dispatch({effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0},"gotoLine"),baseTheme$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine(options){return combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})}});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}__name(highlightSelectionMatches,"highlightSelectionMatches"),__name2(highlightSelectionMatches,"highlightSelectionMatches");const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return(from==0||check(state.sliceDoc(from-1,from))!=CharCategory.Word)&&(to==state.doc.length||check(state.sliceDoc(to,to+1))!=CharCategory.Word)}__name(insideWordBoundaries,"insideWordBoundaries"),__name2(insideWordBoundaries,"insideWordBoundaries");function insideWord(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}__name(insideWord,"insideWord"),__name2(insideWord,"insideWord");const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let range=sel.main,query,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!(insideWordBoundaries(check,state,range.from,range.to)&&insideWord(check,state,range.from,range.to)))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from,to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),selectWord=__name2(({state,dispatch})=>{let{selection}=state,newSel=EditorSelection.create(selection.ranges.map(range=>state.wordAt(range.head)||EditorSelection.cursor(range.head)),selection.mainIndex);return newSel.eq(selection)?!1:(dispatch(state.update({selection:newSel})),!0)},"selectWord");function findNextOccurrence(state,query){let{main,ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;)if(cursor.next(),cursor.done){if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}else{if(cycled&&ranges.some(r=>r.from==cursor.value.from))continue;if(fullWord){let word2=state.wordAt(cursor.value.from);if(!word2||word2.from!=cursor.value.from||word2.to!=cursor.value.to)continue}return cursor.value}}__name(findNextOccurrence,"findNextOccurrence"),__name2(findNextOccurrence,"findNextOccurrence");const selectNextOccurrence=__name2(({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!1;let range=findNextOccurrence(state,searchedText);return range?(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0):!1},"selectNextOccurrence"),searchConfigFacet=Facet.define({combine(configs){return combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})}}),_SearchQuery=class{static{__name(this,"_SearchQuery")}constructor(config2){this.search=config2.search,this.caseSensitive=!!config2.caseSensitive,this.literal=!!config2.literal,this.regexp=!!config2.regexp,this.replace=config2.replace||"",this.valid=!!this.search&&(!this.regexp||validRegExp(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config2.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,(_,ch)=>ch=="n"?` `:ch=="r"?"\r":ch=="t"?" ":"\\")}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state,from=0,to){let st=state.doc?state:EditorState.create({doc:state});return to==null&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}};__name2(_SearchQuery,"SearchQuery");let SearchQuery=_SearchQuery;const _QueryType=class{static{__name(this,"_QueryType")}constructor(spec){this.spec=spec}};__name2(_QueryType,"QueryType");let QueryType=_QueryType;function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?stringWordTest(state.doc,state.charCategorizer(state.selection.main.head)):void 0)}__name(stringCursor,"stringCursor"),__name2(stringCursor,"stringCursor");function stringWordTest(doc2,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_StringQuery,"StringQuery");let StringQuery=_StringQuery;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)):void 0},from,to)}__name(regexpCursor,"regexpCursor"),__name2(regexpCursor,"regexpCursor");function charBefore(str,index2){return str.slice(findClusterBreak(str,index2,!1),index2)}__name(charBefore,"charBefore"),__name2(charBefore,"charBefore");function charAfter(str,index2){return str.slice(index2,findClusterBreak(str,index2))}__name(charAfter,"charAfter"),__name2(charAfter,"charAfter");function regexpWordTest(categorizer){return(_from,_to,match2)=>!match2[0].length||(categorizer(charBefore(match2.input,match2.index))!=CharCategory.Word||categorizer(charAfter(match2.input,match2.index))!=CharCategory.Word)&&(categorizer(charAfter(match2.input,match2.index+match2[0].length))!=CharCategory.Word||categorizer(charBefore(match2.input,match2.index+match2[0].length))!=CharCategory.Word)}__name(regexpWordTest,"regexpWordTest"),__name2(regexpWordTest,"regexpWordTest");const _RegExpQuery=class extends QueryType{static{__name(this,"_RegExpQuery")}nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-size*1e4),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!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)=>i=="$"?"$":i=="&"?result.match[0]:i!="0"&&+i=limit2)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add2){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add2(cursor.value.from,cursor.value.to)}};__name2(_RegExpQuery,"RegExpQuery");let RegExpQuery=_RegExpQuery;const setSearchQuery=StateEffect.define(),togglePanel=StateEffect.define(),searchState=StateField.define({create(state){return new SearchState(defaultQuery(state).create(),null)},update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f=>showPanel.from(f,val=>val.panel)}),_SearchState=class{static{__name(this,"_SearchState")}constructor(query,panel){this.query=query,this.panel=panel}};__name2(_SearchState,"SearchState");let SearchState=_SearchState;const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(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 Decoration.none;let{view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l2=ranges.length;iranges[i+1].from-2*250;)to=ranges[++i].to;query.highlight(view.state,from,to,(from2,to2)=>{let selected=view.state.selection.ranges.some(r=>r.from==from2&&r.to==to2);builder.add(from2,to2,selected?selectedMatchMark:matchMark)})}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}__name(searchCommand,"searchCommand"),__name2(searchCommand,"searchCommand");const findNext=searchCommand((view,{query})=>{let{to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,next),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),findPrevious=searchCommand((view,{query})=>{let{state}=view,{from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config2=view.state.facet(searchConfigFacet);return view.dispatch({selection,effects:[announceMatch(view,prev),config2.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0}),selectMatches=searchCommand((view,{query})=>{let ranges=query.matchAll(view.state,1e3);return!ranges||!ranges.length?!1:(view.dispatch({selection:EditorSelection.create(ranges.map(r=>EditorSelection.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),selectSelectionMatches=__name2(({state,dispatch})=>{let sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from,to}=sel.main,ranges=[],main=0;for(let cur2=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur2.next().done;){if(ranges.length>1e3)return!1;cur2.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur2.value.from,cur2.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0},"selectSelectionMatches"),replaceNext=searchCommand((view,{query})=>{let{state}=view,{from,to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let changes=[],selection,replacement,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(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off2=changes.length==0||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off2,next.to-off2),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes,selection,effects,userEvent:"input.replace"}),!0}),replaceAll=searchCommand((view,{query})=>{if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map(match2=>{let{from,to}=match2;return{from,to,insert:query.getReplacement(match2)}});if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0});function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}__name(createSearchPanel,"createSearchPanel"),__name2(createSearchPanel,"createSearchPanel");function defaultQuery(state,fallback){var _a3,_b2,_c2,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config2=state.facet(searchConfigFacet);return new SearchQuery({search:((_a3=fallback?.literal)!==null&&_a3!==void 0?_a3:config2.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:(_b2=fallback?.caseSensitive)!==null&&_b2!==void 0?_b2:config2.caseSensitive,literal:(_c2=fallback?.literal)!==null&&_c2!==void 0?_c2:config2.literal,regexp:(_d=fallback?.regexp)!==null&&_d!==void 0?_d:config2.regexp,wholeWord:(_e=fallback?.wholeWord)!==null&&_e!==void 0?_e:config2.wholeWord})}__name(defaultQuery,"defaultQuery"),__name2(defaultQuery,"defaultQuery");function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}__name(getSearchInput,"getSearchInput"),__name2(getSearchInput,"getSearchInput");function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}__name(selectSearchInput,"selectSearchInput"),__name2(selectSearchInput,"selectSearchInput");const openSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},"openSearchPanel"),closeSearchPanel=__name2(view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel.of(!1)}),!0},"closeSearchPanel"),searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:selectSelectionMatches},{key:"Alt-g",run:gotoLine},{key:"Mod-d",run:selectNextOccurrence,preventDefault:!0}],_SearchPanel=class{static{__name(this,"_SearchPanel")}constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;this.commit=this.commit.bind(this),this.searchField=crelt("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=crelt("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=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit});function button(name2,onclick,content2){return crelt("button",{class:"cm-button",name:name2,onclick,type:"button"},content2)}__name(button,"button"),__name2(button,"button"),this.dom=crelt("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")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",()=>replaceNext(view),[phrase(view,"replace")]),button("replaceAll",()=>replaceAll(view),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["\xD7"])])}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});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){runScopeHandlers(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):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)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}};__name2(_SearchPanel,"SearchPanel");let SearchPanel=_SearchPanel;function phrase(view,phrase2){return view.state.phrase(phrase2)}__name(phrase,"phrase"),__name2(phrase,"phrase");const AnnounceMargin=30,Break=/[\s\.,:;?!]/;function announceMatch(view,{from,to}){let line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-AnnounceMargin),end=Math.min(lineEnd,to+AnnounceMargin),text=view.state.sliceDoc(start,end);if(start!=line.from){for(let i=0;itext.length-AnnounceMargin;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}}return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`)}__name(announceMatch,"announceMatch"),__name2(announceMatch,"announceMatch");const baseTheme=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"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme],basicSetup=(()=>[lineNumbers(),highlightActiveLineGutter(),highlightSpecialChars(),history(),foldGutter(),drawSelection(),dropCursor(),EditorState.allowMultipleSelections.of(!0),indentOnInput(),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),closeBrackets(),autocompletion(),rectangularSelection(),crosshairCursor(),highlightActiveLine(),highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])])();var PipsMode;(function(PipsMode2){PipsMode2.Range="range",PipsMode2.Steps="steps",PipsMode2.Positions="positions",PipsMode2.Count="count",PipsMode2.Values="values"})(PipsMode||(PipsMode={}));var PipsType;(function(PipsType2){PipsType2[PipsType2.None=-1]="None",PipsType2[PipsType2.NoValue=0]="NoValue",PipsType2[PipsType2.LargeValue=1]="LargeValue",PipsType2[PipsType2.SmallValue=2]="SmallValue"})(PipsType||(PipsType={}));function isValidFormatter(entry){return isValidPartialFormatter(entry)&&typeof entry.from=="function"}__name(isValidFormatter,"isValidFormatter"),__name2(isValidFormatter,"isValidFormatter");function isValidPartialFormatter(entry){return typeof entry=="object"&&typeof entry.to=="function"}__name(isValidPartialFormatter,"isValidPartialFormatter"),__name2(isValidPartialFormatter,"isValidPartialFormatter");function removeElement(el){el.parentElement.removeChild(el)}__name(removeElement,"removeElement"),__name2(removeElement,"removeElement");function isSet(value){return value!=null}__name(isSet,"isSet"),__name2(isSet,"isSet");function preventDefault(e){e.preventDefault()}__name(preventDefault,"preventDefault"),__name2(preventDefault,"preventDefault");function unique(array){return array.filter(function(a){return this[a]?!1:this[a]=!0},{})}__name(unique,"unique"),__name2(unique,"unique");function closest(value,to){return Math.round(value/to)*to}__name(closest,"closest"),__name2(closest,"closest");function offset(elem,orientation){var rect=elem.getBoundingClientRect(),doc2=elem.ownerDocument,docElem=doc2.documentElement,pageOffset=getPageOffset(doc2);return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(pageOffset.x=0),orientation?rect.top+pageOffset.y-docElem.clientTop:rect.left+pageOffset.x-docElem.clientLeft}__name(offset,"offset"),__name2(offset,"offset");function isNumeric(a){return typeof a=="number"&&!isNaN(a)&&isFinite(a)}__name(isNumeric,"isNumeric"),__name2(isNumeric,"isNumeric");function addClassFor(element,className,duration){duration>0&&(addClass(element,className),setTimeout(function(){removeClass(element,className)},duration))}__name(addClassFor,"addClassFor"),__name2(addClassFor,"addClassFor");function limit(a){return Math.max(Math.min(a,100),0)}__name(limit,"limit"),__name2(limit,"limit");function asArray(a){return Array.isArray(a)?a:[a]}__name(asArray,"asArray"),__name2(asArray,"asArray");function countDecimals(numStr){numStr=String(numStr);var pieces=numStr.split(".");return pieces.length>1?pieces[1].length:0}__name(countDecimals,"countDecimals"),__name2(countDecimals,"countDecimals");function addClass(el,className){el.classList&&!/\s/.test(className)?el.classList.add(className):el.className+=" "+className}__name(addClass,"addClass"),__name2(addClass,"addClass");function removeClass(el,className){el.classList&&!/\s/.test(className)?el.classList.remove(className):el.className=el.className.replace(new RegExp("(^|\\b)"+className.split(" ").join("|")+"(\\b|$)","gi")," ")}__name(removeClass,"removeClass"),__name2(removeClass,"removeClass");function hasClass(el,className){return el.classList?el.classList.contains(className):new RegExp("\\b"+className+"\\b").test(el.className)}__name(hasClass,"hasClass"),__name2(hasClass,"hasClass");function getPageOffset(doc2){var supportPageOffset=window.pageXOffset!==void 0,isCSS1Compat=(doc2.compatMode||"")==="CSS1Compat",x=supportPageOffset?window.pageXOffset:isCSS1Compat?doc2.documentElement.scrollLeft:doc2.body.scrollLeft,y=supportPageOffset?window.pageYOffset:isCSS1Compat?doc2.documentElement.scrollTop:doc2.body.scrollTop;return{x,y}}__name(getPageOffset,"getPageOffset"),__name2(getPageOffset,"getPageOffset");function getActions(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}__name(getActions,"getActions"),__name2(getActions,"getActions");function getSupportsPassive(){var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("test",null,opts)}catch{}return supportsPassive}__name(getSupportsPassive,"getSupportsPassive"),__name2(getSupportsPassive,"getSupportsPassive");function getSupportsTouchActionNone(){return window.CSS&&CSS.supports&&CSS.supports("touch-action","none")}__name(getSupportsTouchActionNone,"getSupportsTouchActionNone"),__name2(getSupportsTouchActionNone,"getSupportsTouchActionNone");function subRangeRatio(pa,pb){return 100/(pb-pa)}__name(subRangeRatio,"subRangeRatio"),__name2(subRangeRatio,"subRangeRatio");function fromPercentage(range,value,startRange){return value*100/(range[startRange+1]-range[startRange])}__name(fromPercentage,"fromPercentage"),__name2(fromPercentage,"fromPercentage");function toPercentage(range,value){return fromPercentage(range,range[0]<0?value+Math.abs(range[0]):value-range[0],0)}__name(toPercentage,"toPercentage"),__name2(toPercentage,"toPercentage");function isPercentage(range,value){return value*(range[1]-range[0])/100+range[0]}__name(isPercentage,"isPercentage"),__name2(isPercentage,"isPercentage");function getJ(value,arr){for(var j=1;value>=arr[j];)j+=1;return j}__name(getJ,"getJ"),__name2(getJ,"getJ");function toStepping(xVal,xPct,value){if(value>=xVal.slice(-1)[0])return 100;var j=getJ(value,xVal),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return pa+toPercentage([va,vb],value)/subRangeRatio(pa,pb)}__name(toStepping,"toStepping"),__name2(toStepping,"toStepping");function fromStepping(xVal,xPct,value){if(value>=100)return xVal.slice(-1)[0];var j=getJ(value,xPct),va=xVal[j-1],vb=xVal[j],pa=xPct[j-1],pb=xPct[j];return isPercentage([va,vb],(value-pa)*subRangeRatio(pa,pb))}__name(fromStepping,"fromStepping"),__name2(fromStepping,"fromStepping");function getStep(xPct,xSteps,snap,value){if(value===100)return value;var j=getJ(value,xPct),a=xPct[j-1],b=xPct[j];return snap?value-a>(b-a)/2?b:a:xSteps[j-1]?xPct[j-1]+closest(value-xPct[j-1],xSteps[j-1]):value}__name(getStep,"getStep"),__name2(getStep,"getStep");var Spectrum=function(){function Spectrum2(entry,snap,singleStep){this.xPct=[],this.xVal=[],this.xSteps=[],this.xNumSteps=[],this.xHighestCompleteStep=[],this.xSteps=[singleStep||!1],this.xNumSteps=[!1],this.snap=snap;var index2,ordered=[];for(Object.keys(entry).forEach(function(index3){ordered.push([asArray(entry[index3]),index3])}),ordered.sort(function(a,b){return a[0][0]-b[0][0]}),index2=0;index2this.xPct[xPct_index+1];)xPct_index++;else value===this.xPct[this.xPct.length-1]&&(xPct_index=this.xPct.length-2);!direction&&value===this.xPct[xPct_index+1]&&xPct_index++,distances===null&&(distances=[]);var start_factor,rest_factor=1,rest_rel_distance=distances[xPct_index],range_pct=0,rel_range_distance=0,abs_distance_counter=0,range_counter=0;for(direction?start_factor=(value-this.xPct[xPct_index])/(this.xPct[xPct_index+1]-this.xPct[xPct_index]):start_factor=(this.xPct[xPct_index+1]-value)/(this.xPct[xPct_index+1]-this.xPct[xPct_index]);rest_rel_distance>0;)range_pct=this.xPct[xPct_index+1+range_counter]-this.xPct[xPct_index+range_counter],distances[xPct_index+range_counter]*rest_factor+100-start_factor*100>100?(rel_range_distance=range_pct*start_factor,rest_factor=(rest_rel_distance-100*start_factor)/distances[xPct_index+range_counter],start_factor=1):(rel_range_distance=distances[xPct_index+range_counter]*range_pct/100*rest_factor,rest_factor=0),direction?(abs_distance_counter=abs_distance_counter-rel_range_distance,this.xPct.length+range_counter>=1&&range_counter--):(abs_distance_counter=abs_distance_counter+rel_range_distance,this.xPct.length-range_counter>=1&&range_counter++),rest_rel_distance=distances[xPct_index+range_counter]*rest_factor;return value+abs_distance_counter},Spectrum2.prototype.toStepping=function(value){return value=toStepping(this.xVal,this.xPct,value),value},Spectrum2.prototype.fromStepping=function(value){return fromStepping(this.xVal,this.xPct,value)},Spectrum2.prototype.getStep=function(value){return value=getStep(this.xPct,this.xSteps,this.snap,value),value},Spectrum2.prototype.getDefaultStep=function(value,isDown,size){var j=getJ(value,this.xPct);return(value===100||isDown&&value===this.xPct[j-1])&&(j=Math.max(j-1,1)),(this.xVal[j]-this.xVal[j-1])/size},Spectrum2.prototype.getNearbySteps=function(value){var j=getJ(value,this.xPct);return{stepBefore:{startValue:this.xVal[j-2],step:this.xNumSteps[j-2],highestStep:this.xHighestCompleteStep[j-2]},thisStep:{startValue:this.xVal[j-1],step:this.xNumSteps[j-1],highestStep:this.xHighestCompleteStep[j-1]},stepAfter:{startValue:this.xVal[j],step:this.xNumSteps[j],highestStep:this.xHighestCompleteStep[j]}}},Spectrum2.prototype.countStepDecimals=function(){var stepDecimals=this.xNumSteps.map(countDecimals);return Math.max.apply(null,stepDecimals)},Spectrum2.prototype.hasNoSize=function(){return this.xVal[0]===this.xVal[this.xVal.length-1]},Spectrum2.prototype.convert=function(value){return this.getStep(this.toStepping(value))},Spectrum2.prototype.handleEntryPoint=function(index2,value){var percentage;if(index2==="min"?percentage=0:index2==="max"?percentage=100:percentage=parseFloat(index2),!isNumeric(percentage)||!isNumeric(value[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");this.xPct.push(percentage),this.xVal.push(value[0]);var value1=Number(value[1]);percentage?this.xSteps.push(isNaN(value1)?!1:value1):isNaN(value1)||(this.xSteps[0]=value1),this.xHighestCompleteStep.push(0)},Spectrum2.prototype.handleStepPoint=function(i,n2){if(n2){if(this.xVal[i]===this.xVal[i+1]){this.xSteps[i]=this.xHighestCompleteStep[i]=this.xVal[i];return}this.xSteps[i]=fromPercentage([this.xVal[i],this.xVal[i+1]],n2,0)/subRangeRatio(this.xPct[i],this.xPct[i+1]);var totalSteps=(this.xVal[i+1]-this.xVal[i])/this.xNumSteps[i],highestStep=Math.ceil(Number(totalSteps.toFixed(3))-1),step=this.xVal[i]+this.xNumSteps[i]*highestStep;this.xHighestCompleteStep[i]=step}},Spectrum2}(),defaultFormatter={to:function(value){return value===void 0?"":value.toFixed(2)},from:Number},cssClasses={target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",touchArea:"touch-area",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",connects:"connects",ltr:"ltr",rtl:"rtl",textDirectionLtr:"txt-dir-ltr",textDirectionRtl:"txt-dir-rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"},INTERNAL_EVENT_NS={tooltips:".__tooltips",aria:".__aria"};function testStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'step' is not numeric.");parsed.singleStep=entry}__name(testStep,"testStep"),__name2(testStep,"testStep");function testKeyboardPageMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");parsed.keyboardPageMultiplier=entry}__name(testKeyboardPageMultiplier,"testKeyboardPageMultiplier"),__name2(testKeyboardPageMultiplier,"testKeyboardPageMultiplier");function testKeyboardMultiplier(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");parsed.keyboardMultiplier=entry}__name(testKeyboardMultiplier,"testKeyboardMultiplier"),__name2(testKeyboardMultiplier,"testKeyboardMultiplier");function testKeyboardDefaultStep(parsed,entry){if(!isNumeric(entry))throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");parsed.keyboardDefaultStep=entry}__name(testKeyboardDefaultStep,"testKeyboardDefaultStep"),__name2(testKeyboardDefaultStep,"testKeyboardDefaultStep");function testRange(parsed,entry){if(typeof entry!="object"||Array.isArray(entry))throw new Error("noUiSlider: 'range' is not an object.");if(entry.min===void 0||entry.max===void 0)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");parsed.spectrum=new Spectrum(entry,parsed.snap||!1,parsed.singleStep)}__name(testRange,"testRange"),__name2(testRange,"testRange");function testStart(parsed,entry){if(entry=asArray(entry),!Array.isArray(entry)||!entry.length)throw new Error("noUiSlider: 'start' option is incorrect.");parsed.handles=entry.length,parsed.start=entry}__name(testStart,"testStart"),__name2(testStart,"testStart");function testSnap(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'snap' option must be a boolean.");parsed.snap=entry}__name(testSnap,"testSnap"),__name2(testSnap,"testSnap");function testAnimate(parsed,entry){if(typeof entry!="boolean")throw new Error("noUiSlider: 'animate' option must be a boolean.");parsed.animate=entry}__name(testAnimate,"testAnimate"),__name2(testAnimate,"testAnimate");function testAnimationDuration(parsed,entry){if(typeof entry!="number")throw new Error("noUiSlider: 'animationDuration' option must be a number.");parsed.animationDuration=entry}__name(testAnimationDuration,"testAnimationDuration"),__name2(testAnimationDuration,"testAnimationDuration");function testConnect(parsed,entry){var connect=[!1],i;if(entry==="lower"?entry=[!0,!1]:entry==="upper"&&(entry=[!1,!0]),entry===!0||entry===!1){for(i=1;i1)throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.")}}__name(testPadding,"testPadding"),__name2(testPadding,"testPadding");function testDirection(parsed,entry){switch(entry){case"ltr":parsed.dir=0;break;case"rtl":parsed.dir=1;break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}__name(testDirection,"testDirection"),__name2(testDirection,"testDirection");function testBehaviour(parsed,entry){if(typeof entry!="string")throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var tap=entry.indexOf("tap")>=0,drag=entry.indexOf("drag")>=0,fixed=entry.indexOf("fixed")>=0,snap=entry.indexOf("snap")>=0,hover=entry.indexOf("hover")>=0,unconstrained=entry.indexOf("unconstrained")>=0,dragAll=entry.indexOf("drag-all")>=0,smoothSteps=entry.indexOf("smooth-steps")>=0;if(fixed){if(parsed.handles!==2)throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");testMargin(parsed,parsed.start[1]-parsed.start[0])}if(unconstrained&&(parsed.margin||parsed.limit))throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");parsed.events={tap:tap||snap,drag,dragAll,smoothSteps,fixed,snap,hover,unconstrained}}__name(testBehaviour,"testBehaviour"),__name2(testBehaviour,"testBehaviour");function testTooltips(parsed,entry){if(entry!==!1)if(entry===!0||isValidPartialFormatter(entry)){parsed.tooltips=[];for(var i=0;i= 2) required for mode 'count'.");for(var interval=pips2.values-1,spread=100/interval,values=[];interval--;)values[interval]=interval*spread;return values.push(100),mapToRange(values,pips2.stepped)}return pips2.mode===PipsMode.Positions?mapToRange(pips2.values,pips2.stepped):pips2.mode===PipsMode.Values?pips2.stepped?pips2.values.map(function(value){return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)))}):pips2.values:[]}__name(getGroup,"getGroup"),__name2(getGroup,"getGroup");function mapToRange(values,stepped){return values.map(function(value){return scope_Spectrum.fromStepping(stepped?scope_Spectrum.getStep(value):value)})}__name(mapToRange,"mapToRange"),__name2(mapToRange,"mapToRange");function generateSpread(pips2){function safeIncrement(value,increment){return Number((value+increment).toFixed(7))}__name(safeIncrement,"safeIncrement"),__name2(safeIncrement,"safeIncrement");var group=getGroup(pips2),indexes={},firstInRange=scope_Spectrum.xVal[0],lastInRange=scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],ignoreFirst=!1,ignoreLast=!1,prevPct=0;return group=unique(group.slice().sort(function(a,b){return a-b})),group[0]!==firstInRange&&(group.unshift(firstInRange),ignoreFirst=!0),group[group.length-1]!==lastInRange&&(group.push(lastInRange),ignoreLast=!0),group.forEach(function(current,index2){var step,i,q,low=current,high=group[index2+1],newPct,pctDifference,pctPos,type,steps,realSteps,stepSize,isSteps=pips2.mode===PipsMode.Steps;for(isSteps&&(step=scope_Spectrum.xNumSteps[index2]),step||(step=high-low),high===void 0&&(high=low),step=Math.max(step,1e-7),i=low;i<=high;i=safeIncrement(i,step)){for(newPct=scope_Spectrum.toStepping(i),pctDifference=newPct-prevPct,steps=pctDifference/(pips2.density||1),realSteps=Math.round(steps),stepSize=pctDifference/realSteps,q=1;q<=realSteps;q+=1)pctPos=prevPct+q*stepSize,indexes[pctPos.toFixed(5)]=[scope_Spectrum.fromStepping(pctPos),0];type=group.indexOf(i)>-1?PipsType.LargeValue:isSteps?PipsType.SmallValue:PipsType.NoValue,!index2&&ignoreFirst&&i!==high&&(type=0),i===high&&ignoreLast||(indexes[newPct.toFixed(5)]=[i,type]),prevPct=newPct}}),indexes}__name(generateSpread,"generateSpread"),__name2(generateSpread,"generateSpread");function addMarking(spread,filterFunc,formatter){var _a3,_b2,element=scope_Document.createElement("div"),valueSizeClasses=(_a3={},_a3[PipsType.None]="",_a3[PipsType.NoValue]=options.cssClasses.valueNormal,_a3[PipsType.LargeValue]=options.cssClasses.valueLarge,_a3[PipsType.SmallValue]=options.cssClasses.valueSub,_a3),markerSizeClasses=(_b2={},_b2[PipsType.None]="",_b2[PipsType.NoValue]=options.cssClasses.markerNormal,_b2[PipsType.LargeValue]=options.cssClasses.markerLarge,_b2[PipsType.SmallValue]=options.cssClasses.markerSub,_b2),valueOrientationClasses=[options.cssClasses.valueHorizontal,options.cssClasses.valueVertical],markerOrientationClasses=[options.cssClasses.markerHorizontal,options.cssClasses.markerVertical];addClass(element,options.cssClasses.pips),addClass(element,options.ort===0?options.cssClasses.pipsHorizontal:options.cssClasses.pipsVertical);function getClasses(type,source){var a=source===options.cssClasses.value,orientationClasses=a?valueOrientationClasses:markerOrientationClasses,sizeClasses=a?valueSizeClasses:markerSizeClasses;return source+" "+orientationClasses[options.ort]+" "+sizeClasses[type]}__name(getClasses,"getClasses"),__name2(getClasses,"getClasses");function addSpread(offset2,value,type){if(type=filterFunc?filterFunc(value,type):type,type!==PipsType.None){var node=addNodeTo(element,!1);node.className=getClasses(type,options.cssClasses.marker),node.style[options.style]=offset2+"%",type>PipsType.NoValue&&(node=addNodeTo(element,!1),node.className=getClasses(type,options.cssClasses.value),node.setAttribute("data-value",String(value)),node.style[options.style]=offset2+"%",node.innerHTML=String(formatter.to(value)))}}return __name(addSpread,"addSpread"),__name2(addSpread,"addSpread"),Object.keys(spread).forEach(function(offset2){addSpread(offset2,spread[offset2][0],spread[offset2][1])}),element}__name(addMarking,"addMarking"),__name2(addMarking,"addMarking");function removePips(){scope_Pips&&(removeElement(scope_Pips),scope_Pips=null)}__name(removePips,"removePips"),__name2(removePips,"removePips");function pips(pips2){removePips();var spread=generateSpread(pips2),filter2=pips2.filter,format=pips2.format||{to:function(value){return String(Math.round(value))}};return scope_Pips=scope_Target.appendChild(addMarking(spread,filter2,format)),scope_Pips}__name(pips,"pips"),__name2(pips,"pips");function baseSize(){var rect=scope_Base.getBoundingClientRect(),alt="offset"+["Width","Height"][options.ort];return options.ort===0?rect.width||scope_Base[alt]:rect.height||scope_Base[alt]}__name(baseSize,"baseSize"),__name2(baseSize,"baseSize");function attachEvent(events,element,callback,data){var method=__name2(function(event){var e=fixEvent(event,data.pageOffset,data.target||element);if(!e||isSliderDisabled()&&!data.doNotReject||hasClass(scope_Target,options.cssClasses.tap)&&!data.doNotReject||events===actions.start&&e.buttons!==void 0&&e.buttons>1||data.hover&&e.buttons)return!1;supportsPassive||e.preventDefault(),e.calcPoint=e.points[options.ort],callback(e,data)},"method"),methods=[];return events.split(" ").forEach(function(eventName){element.addEventListener(eventName,method,supportsPassive?{passive:!0}:!1),methods.push([eventName,method])}),methods}__name(attachEvent,"attachEvent"),__name2(attachEvent,"attachEvent");function fixEvent(e,pageOffset,eventTarget){var touch=e.type.indexOf("touch")===0,mouse=e.type.indexOf("mouse")===0,pointer=e.type.indexOf("pointer")===0,x=0,y=0;if(e.type.indexOf("MSPointer")===0&&(pointer=!0),e.type==="mousedown"&&!e.buttons&&!e.touches)return!1;if(touch){var isTouchOnTarget=__name2(function(checkTouch){var target2=checkTouch.target;return target2===eventTarget||eventTarget.contains(target2)||e.composed&&e.composedPath().shift()===eventTarget},"isTouchOnTarget");if(e.type==="touchstart"){var targetTouches=Array.prototype.filter.call(e.touches,isTouchOnTarget);if(targetTouches.length>1)return!1;x=targetTouches[0].pageX,y=targetTouches[0].pageY}else{var targetTouch=Array.prototype.find.call(e.changedTouches,isTouchOnTarget);if(!targetTouch)return!1;x=targetTouch.pageX,y=targetTouch.pageY}}return pageOffset=pageOffset||getPageOffset(scope_Document),(mouse||pointer)&&(x=e.clientX+pageOffset.x,y=e.clientY+pageOffset.y),e.pageOffset=pageOffset,e.points=[x,y],e.cursor=mouse||pointer,e}__name(fixEvent,"fixEvent"),__name2(fixEvent,"fixEvent");function calcPointToPercentage(calcPoint){var location=calcPoint-offset(scope_Base,options.ort),proposal=location*100/baseSize();return proposal=limit(proposal),options.dir?100-proposal:proposal}__name(calcPointToPercentage,"calcPointToPercentage"),__name2(calcPointToPercentage,"calcPointToPercentage");function getClosestHandle(clickedPosition){var smallestDifference=100,handleNumber=!1;return scope_Handles.forEach(function(handle,index2){if(!isHandleDisabled(index2)){var handlePosition=scope_Locations[index2],differenceWithThisHandle=Math.abs(handlePosition-clickedPosition),clickAtEdge=differenceWithThisHandle===100&&smallestDifference===100,isCloser=differenceWithThisHandlehandlePosition;(isCloser||isCloserAfter||clickAtEdge)&&(handleNumber=index2,smallestDifference=differenceWithThisHandle)}}),handleNumber}__name(getClosestHandle,"getClosestHandle"),__name2(getClosestHandle,"getClosestHandle");function documentLeave(event,data){event.type==="mouseout"&&event.target.nodeName==="HTML"&&event.relatedTarget===null&&eventEnd(event,data)}__name(documentLeave,"documentLeave"),__name2(documentLeave,"documentLeave");function eventMove(event,data){if(navigator.appVersion.indexOf("MSIE 9")===-1&&event.buttons===0&&data.buttonsProperty!==0)return eventEnd(event,data);var movement=(options.dir?-1:1)*(event.calcPoint-data.startCalcPoint),proposal=movement*100/data.baseSize;moveHandles(movement>0,proposal,data.locations,data.handleNumbers,data.connect)}__name(eventMove,"eventMove"),__name2(eventMove,"eventMove");function eventEnd(event,data){data.handle&&(removeClass(data.handle,options.cssClasses.active),scope_ActiveHandlesCount-=1),data.listeners.forEach(function(c){scope_DocumentElement.removeEventListener(c[0],c[1])}),scope_ActiveHandlesCount===0&&(removeClass(scope_Target,options.cssClasses.drag),setZindex(),event.cursor&&(scope_Body.style.cursor="",scope_Body.removeEventListener("selectstart",preventDefault))),options.events.smoothSteps&&(data.handleNumbers.forEach(function(handleNumber){setHandle(handleNumber,scope_Locations[handleNumber],!0,!0,!1,!1)}),data.handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber)})),data.handleNumbers.forEach(function(handleNumber){fireEvent("change",handleNumber),fireEvent("set",handleNumber),fireEvent("end",handleNumber)})}__name(eventEnd,"eventEnd"),__name2(eventEnd,"eventEnd");function eventStart(event,data){if(!data.handleNumbers.some(isHandleDisabled)){var handle;if(data.handleNumbers.length===1){var handleOrigin=scope_Handles[data.handleNumbers[0]];handle=handleOrigin.children[0],scope_ActiveHandlesCount+=1,addClass(handle,options.cssClasses.active)}event.stopPropagation();var listeners=[],moveEvent=attachEvent(actions.move,scope_DocumentElement,eventMove,{target:event.target,handle,connect:data.connect,listeners,startCalcPoint:event.calcPoint,baseSize:baseSize(),pageOffset:event.pageOffset,handleNumbers:data.handleNumbers,buttonsProperty:event.buttons,locations:scope_Locations.slice()}),endEvent=attachEvent(actions.end,scope_DocumentElement,eventEnd,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers}),outEvent=attachEvent("mouseout",scope_DocumentElement,documentLeave,{target:event.target,handle,listeners,doNotReject:!0,handleNumbers:data.handleNumbers});listeners.push.apply(listeners,moveEvent.concat(endEvent,outEvent)),event.cursor&&(scope_Body.style.cursor=getComputedStyle(event.target).cursor,scope_Handles.length>1&&addClass(scope_Target,options.cssClasses.drag),scope_Body.addEventListener("selectstart",preventDefault,!1)),data.handleNumbers.forEach(function(handleNumber){fireEvent("start",handleNumber)})}}__name(eventStart,"eventStart"),__name2(eventStart,"eventStart");function eventTap(event){event.stopPropagation();var proposal=calcPointToPercentage(event.calcPoint),handleNumber=getClosestHandle(proposal);handleNumber!==!1&&(options.events.snap||addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),setHandle(handleNumber,proposal,!0,!0),setZindex(),fireEvent("slide",handleNumber,!0),fireEvent("update",handleNumber,!0),options.events.snap?eventStart(event,{handleNumbers:[handleNumber]}):(fireEvent("change",handleNumber,!0),fireEvent("set",handleNumber,!0)))}__name(eventTap,"eventTap"),__name2(eventTap,"eventTap");function eventHover(event){var proposal=calcPointToPercentage(event.calcPoint),to=scope_Spectrum.getStep(proposal),value=scope_Spectrum.fromStepping(to);Object.keys(scope_Events).forEach(function(targetEvent){targetEvent.split(".")[0]==="hover"&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,value)})})}__name(eventHover,"eventHover"),__name2(eventHover,"eventHover");function eventKeydown(event,handleNumber){if(isSliderDisabled()||isHandleDisabled(handleNumber))return!1;var horizontalKeys=["Left","Right"],verticalKeys=["Down","Up"],largeStepKeys=["PageDown","PageUp"],edgeKeys=["Home","End"];options.dir&&!options.ort?horizontalKeys.reverse():options.ort&&!options.dir&&(verticalKeys.reverse(),largeStepKeys.reverse());var key=event.key.replace("Arrow",""),isLargeDown=key===largeStepKeys[0],isLargeUp=key===largeStepKeys[1],isDown=key===verticalKeys[0]||key===horizontalKeys[0]||isLargeDown,isUp=key===verticalKeys[1]||key===horizontalKeys[1]||isLargeUp,isMin=key===edgeKeys[0],isMax=key===edgeKeys[1];if(!isDown&&!isUp&&!isMin&&!isMax)return!0;event.preventDefault();var to;if(isUp||isDown){var direction=isDown?0:1,steps=getNextStepsForHandle(handleNumber),step=steps[direction];if(step===null)return!1;step===!1&&(step=scope_Spectrum.getDefaultStep(scope_Locations[handleNumber],isDown,options.keyboardDefaultStep)),isLargeUp||isLargeDown?step*=options.keyboardPageMultiplier:step*=options.keyboardMultiplier,step=Math.max(step,1e-7),step=(isDown?-1:1)*step,to=scope_Values[handleNumber]+step}else isMax?to=options.spectrum.xVal[options.spectrum.xVal.length-1]:to=options.spectrum.xVal[0];return setHandle(handleNumber,scope_Spectrum.toStepping(to),!0,!0),fireEvent("slide",handleNumber),fireEvent("update",handleNumber),fireEvent("change",handleNumber),fireEvent("set",handleNumber),!1}__name(eventKeydown,"eventKeydown"),__name2(eventKeydown,"eventKeydown");function bindSliderEvents(behaviour){behaviour.fixed||scope_Handles.forEach(function(handle,index2){attachEvent(actions.start,handle.children[0],eventStart,{handleNumbers:[index2]})}),behaviour.tap&&attachEvent(actions.start,scope_Base,eventTap,{}),behaviour.hover&&attachEvent(actions.move,scope_Base,eventHover,{hover:!0}),behaviour.drag&&scope_Connects.forEach(function(connect,index2){if(!(connect===!1||index2===0||index2===scope_Connects.length-1)){var handleBefore=scope_Handles[index2-1],handleAfter=scope_Handles[index2],eventHolders=[connect],handlesToDrag=[handleBefore,handleAfter],handleNumbersToDrag=[index2-1,index2];addClass(connect,options.cssClasses.draggable),behaviour.fixed&&(eventHolders.push(handleBefore.children[0]),eventHolders.push(handleAfter.children[0])),behaviour.dragAll&&(handlesToDrag=scope_Handles,handleNumbersToDrag=scope_HandleNumbers),eventHolders.forEach(function(eventHolder){attachEvent(actions.start,eventHolder,eventStart,{handles:handlesToDrag,handleNumbers:handleNumbersToDrag,connect})})}})}__name(bindSliderEvents,"bindSliderEvents"),__name2(bindSliderEvents,"bindSliderEvents");function bindEvent(namespacedEvent,callback){scope_Events[namespacedEvent]=scope_Events[namespacedEvent]||[],scope_Events[namespacedEvent].push(callback),namespacedEvent.split(".")[0]==="update"&&scope_Handles.forEach(function(a,index2){fireEvent("update",index2)})}__name(bindEvent,"bindEvent"),__name2(bindEvent,"bindEvent");function isInternalNamespace(namespace){return namespace===INTERNAL_EVENT_NS.aria||namespace===INTERNAL_EVENT_NS.tooltips}__name(isInternalNamespace,"isInternalNamespace"),__name2(isInternalNamespace,"isInternalNamespace");function removeEvent(namespacedEvent){var event=namespacedEvent&&namespacedEvent.split(".")[0],namespace=event?namespacedEvent.substring(event.length):namespacedEvent;Object.keys(scope_Events).forEach(function(bind){var tEvent=bind.split(".")[0],tNamespace=bind.substring(tEvent.length);(!event||event===tEvent)&&(!namespace||namespace===tNamespace)&&(!isInternalNamespace(tNamespace)||namespace===tNamespace)&&delete scope_Events[bind]})}__name(removeEvent,"removeEvent"),__name2(removeEvent,"removeEvent");function fireEvent(eventName,handleNumber,tap){Object.keys(scope_Events).forEach(function(targetEvent){var eventType=targetEvent.split(".")[0];eventName===eventType&&scope_Events[targetEvent].forEach(function(callback){callback.call(scope_Self,scope_Values.map(options.format.to),handleNumber,scope_Values.slice(),tap||!1,scope_Locations.slice(),scope_Self)})})}__name(fireEvent,"fireEvent"),__name2(fireEvent,"fireEvent");function checkHandlePosition(reference,handleNumber,to,lookBackward,lookForward,getValue,smoothSteps){var distance;return scope_Handles.length>1&&!options.events.unconstrained&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.margin,!1),to=Math.max(to,distance)),lookForward&&handleNumber1&&options.limit&&(lookBackward&&handleNumber>0&&(distance=scope_Spectrum.getAbsoluteDistance(reference[handleNumber-1],options.limit,!1),to=Math.min(to,distance)),lookForward&&handleNumber1?handleNumbers.forEach(function(handleNumber,o){var to=checkHandlePosition(proposals,handleNumber,proposals[handleNumber]+proposal,b[o],f[o],!1,smoothSteps);to===!1?proposal=0:(proposal=to-proposals[handleNumber],proposals[handleNumber]=to)}):b=f=[!0];var state=!1;handleNumbers.forEach(function(handleNumber,o){state=setHandle(handleNumber,locations[handleNumber]+proposal,b[o],f[o],!1,smoothSteps)||state}),state&&(handleNumbers.forEach(function(handleNumber){fireEvent("update",handleNumber),fireEvent("slide",handleNumber)}),connect!=null&&fireEvent("drag",firstHandle))}__name(moveHandles,"moveHandles"),__name2(moveHandles,"moveHandles");function transformDirection(a,b){return options.dir?100-a-b:a}__name(transformDirection,"transformDirection"),__name2(transformDirection,"transformDirection");function updateHandlePosition(handleNumber,to){scope_Locations[handleNumber]=to,scope_Values[handleNumber]=scope_Spectrum.fromStepping(to);var translation=transformDirection(to,0)-scope_DirOffset,translateRule="translate("+inRuleOrder(translation+"%","0")+")";scope_Handles[handleNumber].style[options.transformRule]=translateRule,updateConnect(handleNumber),updateConnect(handleNumber+1)}__name(updateHandlePosition,"updateHandlePosition"),__name2(updateHandlePosition,"updateHandlePosition");function setZindex(){scope_HandleNumbers.forEach(function(handleNumber){var dir=scope_Locations[handleNumber]>50?-1:1,zIndex=3+(scope_Handles.length+dir*handleNumber);scope_Handles[handleNumber].style.zIndex=String(zIndex)})}__name(setZindex,"setZindex"),__name2(setZindex,"setZindex");function setHandle(handleNumber,to,lookBackward,lookForward,exactInput,smoothSteps){return exactInput||(to=checkHandlePosition(scope_Locations,handleNumber,to,lookBackward,lookForward,!1,smoothSteps)),to===!1?!1:(updateHandlePosition(handleNumber,to),!0)}__name(setHandle,"setHandle"),__name2(setHandle,"setHandle");function updateConnect(index2){if(scope_Connects[index2]){var l2=0,h=100;index2!==0&&(l2=scope_Locations[index2-1]),index2!==scope_Connects.length-1&&(h=scope_Locations[index2]);var connectWidth=h-l2,translateRule="translate("+inRuleOrder(transformDirection(l2,connectWidth)+"%","0")+")",scaleRule="scale("+inRuleOrder(connectWidth/100,"1")+")";scope_Connects[index2].style[options.transformRule]=translateRule+" "+scaleRule}}__name(updateConnect,"updateConnect"),__name2(updateConnect,"updateConnect");function resolveToValue(to,handleNumber){return to===null||to===!1||to===void 0||(typeof to=="number"&&(to=String(to)),to=options.format.from(to),to!==!1&&(to=scope_Spectrum.toStepping(to)),to===!1||isNaN(to))?scope_Locations[handleNumber]:to}__name(resolveToValue,"resolveToValue"),__name2(resolveToValue,"resolveToValue");function valueSet(input,fireSetEvent,exactInput){var values=asArray(input),isInit=scope_Locations[0]===void 0;fireSetEvent=fireSetEvent===void 0?!0:fireSetEvent,options.animate&&!isInit&&addClassFor(scope_Target,options.cssClasses.tap,options.animationDuration),scope_HandleNumbers.forEach(function(handleNumber){setHandle(handleNumber,resolveToValue(values[handleNumber],handleNumber),!0,!1,exactInput)});var i=scope_HandleNumbers.length===1?0:1;if(isInit&&scope_Spectrum.hasNoSize()&&(exactInput=!0,scope_Locations[0]=0,scope_HandleNumbers.length>1)){var space_1=100/(scope_HandleNumbers.length-1);scope_HandleNumbers.forEach(function(handleNumber){scope_Locations[handleNumber]=handleNumber*space_1})}for(;i=0&&handleNumbernearbySteps.stepAfter.startValue&&(increment=nearbySteps.stepAfter.startValue-value),value>nearbySteps.thisStep.startValue?decrement=nearbySteps.thisStep.step:nearbySteps.stepBefore.step===!1?decrement=!1:decrement=value-nearbySteps.stepBefore.highestStep,location===100?increment=null:location===0&&(decrement=null);var stepDecimals=scope_Spectrum.countStepDecimals();return increment!==null&&increment!==!1&&(increment=Number(increment.toFixed(stepDecimals))),decrement!==null&&decrement!==!1&&(decrement=Number(decrement.toFixed(stepDecimals))),[decrement,increment]}__name(getNextStepsForHandle,"getNextStepsForHandle"),__name2(getNextStepsForHandle,"getNextStepsForHandle");function getNextSteps(){return scope_HandleNumbers.map(getNextStepsForHandle)}__name(getNextSteps,"getNextSteps"),__name2(getNextSteps,"getNextSteps");function updateOptions(optionsToUpdate,fireSetEvent){var v=valueGet(),updateAble=["margin","limit","padding","range","animate","snap","step","format","pips","tooltips"];updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(originalOptions[name2]=optionsToUpdate[name2])});var newOptions=testOptions(originalOptions);updateAble.forEach(function(name2){optionsToUpdate[name2]!==void 0&&(options[name2]=newOptions[name2])}),scope_Spectrum=newOptions.spectrum,options.margin=newOptions.margin,options.limit=newOptions.limit,options.padding=newOptions.padding,options.pips?pips(options.pips):removePips(),options.tooltips?tooltips():removeTooltips(),scope_Locations=[],valueSet(isSet(optionsToUpdate.start)?optionsToUpdate.start:v,fireSetEvent)}__name(updateOptions,"updateOptions"),__name2(updateOptions,"updateOptions");function setupSlider(){scope_Base=addSlider(scope_Target),addElements(options.connect,scope_Base),bindSliderEvents(options.events),valueSet(options.start),options.pips&&pips(options.pips),options.tooltips&&tooltips(),aria()}__name(setupSlider,"setupSlider"),__name2(setupSlider,"setupSlider"),setupSlider();var scope_Self={destroy:destroy2,steps:getNextSteps,on:bindEvent,off:removeEvent,get:valueGet,set:valueSet,setHandle:valueSetHandle,reset:valueReset,disable,enable,__moveHandles:function(upward,proposal,handleNumbers){moveHandles(upward,proposal,scope_Locations,handleNumbers)},options:originalOptions,updateOptions,target:scope_Target,removePips,removeTooltips,getPositions:function(){return scope_Locations.slice()},getTooltips:function(){return scope_Tooltips},getOrigins:function(){return scope_Handles},pips};return scope_Self}__name(scope,"scope"),__name2(scope,"scope");function initialize(target,originalOptions){if(!target||!target.nodeName)throw new Error("noUiSlider: create requires a single element, got: "+target);if(target.noUiSlider)throw new Error("noUiSlider: Slider was already initialized.");var options=testOptions(originalOptions),api=scope(target,options,originalOptions);return target.noUiSlider=api,api}__name(initialize,"initialize"),__name2(initialize,"initialize");const noUiSlider={__spectrum:Spectrum,cssClasses,create:initialize};var __assign=__name2(function(){return __assign=Object.assign||__name2(__name(function(t2){for(var s2,i=1,n2=arguments.length;i0&&t2[t2.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t2||op[1]>t2[0]&&op[1]=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}__name(__values,"__values"),__name2(__values,"__values");function __read(o,n2){var m=typeof Symbol=="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{for(;(n2===void 0||n2-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}__name(__read,"__read"),__name2(__read,"__read");var ENTRIES="ENTRIES",KEYS="KEYS",VALUES="VALUES",LEAF="",TreeIterator=function(){function TreeIterator2(set,type){var node=set._tree,keys2=Array.from(node.keys());this.set=set,this._type=type,this._path=keys2.length>0?[{node,keys:keys2}]:[]}return __name(TreeIterator2,"TreeIterator2"),__name2(TreeIterator2,"TreeIterator"),TreeIterator2.prototype.next=function(){var value=this.dive();return this.backtrack(),value},TreeIterator2.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var _a3=last$1(this._path),node=_a3.node,keys2=_a3.keys;if(last$1(keys2)===LEAF)return{done:!1,value:this.result()};var child=node.get(last$1(keys2));return this._path.push({node:child,keys:Array.from(child.keys())}),this.dive()},TreeIterator2.prototype.backtrack=function(){if(this._path.length!==0){var keys2=last$1(this._path).keys;keys2.pop(),!(keys2.length>0)&&(this._path.pop(),this.backtrack())}},TreeIterator2.prototype.key=function(){return this.set._prefix+this._path.map(function(_a3){var keys2=_a3.keys;return last$1(keys2)}).filter(function(key){return key!==LEAF}).join("")},TreeIterator2.prototype.value=function(){return last$1(this._path).node.get(LEAF)},TreeIterator2.prototype.result=function(){switch(this._type){case VALUES:return this.value();case KEYS:return this.key();default:return[this.key(),this.value()]}},TreeIterator2.prototype[Symbol.iterator]=function(){return this},TreeIterator2}(),last$1=__name2(function(array){return array[array.length-1]},"last$1"),fuzzySearch=__name2(function(node,query,maxDistance){var results=new Map;if(query===void 0)return results;for(var n2=query.length+1,m=n2+maxDistance,matrix2=new Uint8Array(m*n2).fill(maxDistance+1),j=0;jmaxDistance)continue key}recurse(node.get(key),query,maxDistance,results,matrix2,i,n2,prefix+key)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_1)throw e_1.error}}},"recurse"),SearchableMap=function(){function SearchableMap2(tree,prefix){tree===void 0&&(tree=new Map),prefix===void 0&&(prefix=""),this._size=void 0,this._tree=tree,this._prefix=prefix}return __name(SearchableMap2,"SearchableMap2"),__name2(SearchableMap2,"SearchableMap"),SearchableMap2.prototype.atPrefix=function(prefix){var e_1,_a3;if(!prefix.startsWith(this._prefix))throw new Error("Mismatched prefix");var _b2=__read(trackDown(this._tree,prefix.slice(this._prefix.length)),2),node=_b2[0],path=_b2[1];if(node===void 0){var _c2=__read(last(path),2),parentNode=_c2[0],key=_c2[1];try{for(var _d=__values(parentNode.keys()),_e=_d.next();!_e.done;_e=_d.next()){var k=_e.value;if(k!==LEAF&&k.startsWith(key)){var node_1=new Map;return node_1.set(k.slice(key.length),parentNode.get(k)),new SearchableMap2(node_1,prefix)}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_1)throw e_1.error}}}return new SearchableMap2(node,prefix)},SearchableMap2.prototype.clear=function(){this._size=void 0,this._tree.clear()},SearchableMap2.prototype.delete=function(key){return this._size=void 0,remove(this._tree,key)},SearchableMap2.prototype.entries=function(){return new TreeIterator(this,ENTRIES)},SearchableMap2.prototype.forEach=function(fn){var e_2,_a3;try{for(var _b2=__values(this),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var _d=__read(_c2.value,2),key=_d[0],value=_d[1];fn(key,value,this)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_2)throw e_2.error}}},SearchableMap2.prototype.fuzzyGet=function(key,maxEditDistance){return fuzzySearch(this._tree,key,maxEditDistance)},SearchableMap2.prototype.get=function(key){var node=lookup(this._tree,key);return node!==void 0?node.get(LEAF):void 0},SearchableMap2.prototype.has=function(key){var node=lookup(this._tree,key);return node!==void 0&&node.has(LEAF)},SearchableMap2.prototype.keys=function(){return new TreeIterator(this,KEYS)},SearchableMap2.prototype.set=function(key,value){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,value),this},Object.defineProperty(SearchableMap2.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var iter=this.entries();!iter.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),SearchableMap2.prototype.update=function(key,fn){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key);return node.set(LEAF,fn(node.get(LEAF))),this},SearchableMap2.prototype.fetch=function(key,initial){if(typeof key!="string")throw new Error("key must be a string");this._size=void 0;var node=createPath(this._tree,key),value=node.get(LEAF);return value===void 0&&node.set(LEAF,value=initial()),value},SearchableMap2.prototype.values=function(){return new TreeIterator(this,VALUES)},SearchableMap2.prototype[Symbol.iterator]=function(){return this.entries()},SearchableMap2.from=function(entries){var e_3,_a3,tree=new SearchableMap2;try{for(var entries_1=__values(entries),entries_1_1=entries_1.next();!entries_1_1.done;entries_1_1=entries_1.next()){var _b2=__read(entries_1_1.value,2),key=_b2[0],value=_b2[1];tree.set(key,value)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{entries_1_1&&!entries_1_1.done&&(_a3=entries_1.return)&&_a3.call(entries_1)}finally{if(e_3)throw e_3.error}}return tree},SearchableMap2.fromObject=function(object){return SearchableMap2.from(Object.entries(object))},SearchableMap2}(),trackDown=__name2(function(tree,key,path){var e_4,_a3;if(path===void 0&&(path=[]),key.length===0||tree==null)return[tree,path];try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return path.push([tree,k]),trackDown(tree.get(k),key.slice(k.length),path)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_4)throw e_4.error}}return path.push([tree,key]),trackDown(void 0,"",path)},"trackDown"),lookup=__name2(function(tree,key){var e_5,_a3;if(key.length===0||tree==null)return tree;try{for(var _b2=__values(tree.keys()),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var k=_c2.value;if(k!==LEAF&&key.startsWith(k))return lookup(tree.get(k),key.slice(k.length))}}catch(e_5_1){e_5={error:e_5_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_5)throw e_5.error}}},"lookup"),createPath=__name2(function(node,key){var e_6,_a3,keyLength=key.length;outer:for(var pos=0;node&&pos0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new SearchableMap,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},MiniSearch2.prototype.discard=function(id){var _this=this,shortId=this._idToShortId.get(id);if(shortId==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(id,": it is not in the index"));this._idToShortId.delete(id),this._documentIds.delete(shortId),this._storedFields.delete(shortId),(this._fieldLength.get(shortId)||[]).forEach(function(fieldLength,fieldId){_this.removeFieldLength(shortId,fieldId,_this._documentCount,fieldLength)}),this._fieldLength.delete(shortId),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},MiniSearch2.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var _a3=this._options.autoVacuum,minDirtFactor=_a3.minDirtFactor,minDirtCount=_a3.minDirtCount,batchSize=_a3.batchSize,batchWait=_a3.batchWait;this.conditionalVacuum({batchSize,batchWait},{minDirtCount,minDirtFactor})}},MiniSearch2.prototype.discardAll=function(ids){var e_9,_a3,autoVacuum=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var ids_1=__values(ids),ids_1_1=ids_1.next();!ids_1_1.done;ids_1_1=ids_1.next()){var id=ids_1_1.value;this.discard(id)}}catch(e_9_1){e_9={error:e_9_1}}finally{try{ids_1_1&&!ids_1_1.done&&(_a3=ids_1.return)&&_a3.call(ids_1)}finally{if(e_9)throw e_9.error}}}finally{this._options.autoVacuum=autoVacuum}this.maybeAutoVacuum()},MiniSearch2.prototype.replace=function(updatedDocument){var _a3=this._options,idField=_a3.idField,extractField=_a3.extractField,id=extractField(updatedDocument,idField);this.discard(id),this.add(updatedDocument)},MiniSearch2.prototype.vacuum=function(options){return options===void 0&&(options={}),this.conditionalVacuum(options)},MiniSearch2.prototype.conditionalVacuum=function(options,conditions){var _this=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&conditions,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var conditions2=_this._enqueuedVacuumConditions;return _this._enqueuedVacuumConditions=defaultVacuumConditions,_this.performVacuuming(options,conditions2)}),this._enqueuedVacuum)):this.vacuumConditionsMet(conditions)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(options),this._currentVacuum)},MiniSearch2.prototype.performVacuuming=function(options,conditions){return __awaiter(this,void 0,void 0,function(){var initialDirtCount,batchSize,batchWait_1,i,_a3,_b2,_c2,term,fieldsData,fieldsData_1,fieldsData_1_1,_d,fieldId,fieldIndex,fieldIndex_1,fieldIndex_1_1,_e,shortId,e_10_1,e_10,_f,e_11,_g,e_12,_h;return __generator(this,function(_j){switch(_j.label){case 0:if(initialDirtCount=this._dirtCount,!this.vacuumConditionsMet(conditions))return[3,10];batchSize=options.batchSize||defaultVacuumOptions.batchSize,batchWait_1=options.batchWait||defaultVacuumOptions.batchWait,i=1,_j.label=1;case 1:_j.trys.push([1,7,8,9]),_a3=__values(this._index),_b2=_a3.next(),_j.label=2;case 2:if(_b2.done)return[3,6];_c2=__read(_b2.value,2),term=_c2[0],fieldsData=_c2[1];try{for(fieldsData_1=(e_11=void 0,__values(fieldsData)),fieldsData_1_1=fieldsData_1.next();!fieldsData_1_1.done;fieldsData_1_1=fieldsData_1.next()){_d=__read(fieldsData_1_1.value,2),fieldId=_d[0],fieldIndex=_d[1];try{for(fieldIndex_1=(e_12=void 0,__values(fieldIndex)),fieldIndex_1_1=fieldIndex_1.next();!fieldIndex_1_1.done;fieldIndex_1_1=fieldIndex_1.next())_e=__read(fieldIndex_1_1.value,1),shortId=_e[0],!this._documentIds.has(shortId)&&(fieldIndex.size<=1?fieldsData.delete(fieldId):fieldIndex.delete(shortId))}catch(e_12_1){e_12={error:e_12_1}}finally{try{fieldIndex_1_1&&!fieldIndex_1_1.done&&(_h=fieldIndex_1.return)&&_h.call(fieldIndex_1)}finally{if(e_12)throw e_12.error}}}}catch(e_11_1){e_11={error:e_11_1}}finally{try{fieldsData_1_1&&!fieldsData_1_1.done&&(_g=fieldsData_1.return)&&_g.call(fieldsData_1)}finally{if(e_11)throw e_11.error}}return this._index.get(term).size===0&&this._index.delete(term),i%batchSize!==0?[3,4]:[4,new Promise(function(resolve){return setTimeout(resolve,batchWait_1)})];case 3:_j.sent(),_j.label=4;case 4:i+=1,_j.label=5;case 5:return _b2=_a3.next(),[3,2];case 6:return[3,9];case 7:return e_10_1=_j.sent(),e_10={error:e_10_1},[3,9];case 8:try{_b2&&!_b2.done&&(_f=_a3.return)&&_f.call(_a3)}finally{if(e_10)throw e_10.error}return[7];case 9:this._dirtCount-=initialDirtCount,_j.label=10;case 10:return[4,null];case 11:return _j.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},MiniSearch2.prototype.vacuumConditionsMet=function(conditions){if(conditions==null)return!0;var minDirtCount=conditions.minDirtCount,minDirtFactor=conditions.minDirtFactor;return minDirtCount=minDirtCount||defaultAutoVacuumOptions.minDirtCount,minDirtFactor=minDirtFactor||defaultAutoVacuumOptions.minDirtFactor,this.dirtCount>=minDirtCount&&this.dirtFactor>=minDirtFactor},Object.defineProperty(MiniSearch2.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),MiniSearch2.prototype.has=function(id){return this._idToShortId.has(id)},MiniSearch2.prototype.getStoredFields=function(id){var shortId=this._idToShortId.get(id);if(shortId!=null)return this._storedFields.get(shortId)},MiniSearch2.prototype.search=function(query,searchOptions){var e_13,_a3;searchOptions===void 0&&(searchOptions={});var combinedResults=this.executeQuery(query,searchOptions),results=[];try{for(var combinedResults_1=__values(combinedResults),combinedResults_1_1=combinedResults_1.next();!combinedResults_1_1.done;combinedResults_1_1=combinedResults_1.next()){var _b2=__read(combinedResults_1_1.value,2),docId=_b2[0],_c2=_b2[1],score2=_c2.score,terms=_c2.terms,match2=_c2.match,quality=terms.length,result={id:this._documentIds.get(docId),score:score2*quality,terms:Object.keys(match2),match:match2};Object.assign(result,this._storedFields.get(docId)),(searchOptions.filter==null||searchOptions.filter(result))&&results.push(result)}}catch(e_13_1){e_13={error:e_13_1}}finally{try{combinedResults_1_1&&!combinedResults_1_1.done&&(_a3=combinedResults_1.return)&&_a3.call(combinedResults_1)}finally{if(e_13)throw e_13.error}}return results.sort(byScore),results},MiniSearch2.prototype.autoSuggest=function(queryString,options){var e_14,_a3,e_15,_b2;options===void 0&&(options={}),options=__assign(__assign({},this._options.autoSuggestOptions),options);var suggestions=new Map;try{for(var _c2=__values(this.search(queryString,options)),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=_d.value,score2=_e.score,terms=_e.terms,phrase2=terms.join(" "),suggestion=suggestions.get(phrase2);suggestion!=null?(suggestion.score+=score2,suggestion.count+=1):suggestions.set(phrase2,{score:score2,terms,count:1})}}catch(e_14_1){e_14={error:e_14_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_14)throw e_14.error}}var results=[];try{for(var suggestions_1=__values(suggestions),suggestions_1_1=suggestions_1.next();!suggestions_1_1.done;suggestions_1_1=suggestions_1.next()){var _f=__read(suggestions_1_1.value,2),suggestion=_f[0],_g=_f[1],score2=_g.score,terms=_g.terms,count=_g.count;results.push({suggestion,terms,score:score2/count})}}catch(e_15_1){e_15={error:e_15_1}}finally{try{suggestions_1_1&&!suggestions_1_1.done&&(_b2=suggestions_1.return)&&_b2.call(suggestions_1)}finally{if(e_15)throw e_15.error}}return results.sort(byScore),results},Object.defineProperty(MiniSearch2.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(MiniSearch2.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),MiniSearch2.loadJSON=function(json2,options){if(options==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(json2),options)},MiniSearch2.getDefault=function(optionName){if(defaultOptions.hasOwnProperty(optionName))return getOwnProperty(defaultOptions,optionName);throw new Error('MiniSearch: unknown option "'.concat(optionName,'"'))},MiniSearch2.loadJS=function(js,options){var e_16,_a3,e_17,_b2,e_18,_c2,index2=js.index,documentCount=js.documentCount,nextId=js.nextId,documentIds=js.documentIds,fieldIds=js.fieldIds,fieldLength=js.fieldLength,averageFieldLength=js.averageFieldLength,storedFields=js.storedFields,dirtCount=js.dirtCount,serializationVersion=js.serializationVersion;if(serializationVersion!==1&&serializationVersion!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var miniSearch=new MiniSearch2(options);miniSearch._documentCount=documentCount,miniSearch._nextId=nextId,miniSearch._documentIds=objectToNumericMap(documentIds),miniSearch._idToShortId=new Map,miniSearch._fieldIds=fieldIds,miniSearch._fieldLength=objectToNumericMap(fieldLength),miniSearch._avgFieldLength=averageFieldLength,miniSearch._storedFields=objectToNumericMap(storedFields),miniSearch._dirtCount=dirtCount||0,miniSearch._index=new SearchableMap;try{for(var _d=__values(miniSearch._documentIds),_e=_d.next();!_e.done;_e=_d.next()){var _f=__read(_e.value,2),shortId=_f[0],id=_f[1];miniSearch._idToShortId.set(id,shortId)}}catch(e_16_1){e_16={error:e_16_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_16)throw e_16.error}}try{for(var index_1=__values(index2),index_1_1=index_1.next();!index_1_1.done;index_1_1=index_1.next()){var _g=__read(index_1_1.value,2),term=_g[0],data=_g[1],dataMap=new Map;try{for(var _h=(e_18=void 0,__values(Object.keys(data))),_j=_h.next();!_j.done;_j=_h.next()){var fieldId=_j.value,indexEntry=data[fieldId];serializationVersion===1&&(indexEntry=indexEntry.ds),dataMap.set(parseInt(fieldId,10),objectToNumericMap(indexEntry))}}catch(e_18_1){e_18={error:e_18_1}}finally{try{_j&&!_j.done&&(_c2=_h.return)&&_c2.call(_h)}finally{if(e_18)throw e_18.error}}miniSearch._index.set(term,dataMap)}}catch(e_17_1){e_17={error:e_17_1}}finally{try{index_1_1&&!index_1_1.done&&(_b2=index_1.return)&&_b2.call(index_1)}finally{if(e_17)throw e_17.error}}return miniSearch},MiniSearch2.prototype.executeQuery=function(query,searchOptions){var _this=this;if(searchOptions===void 0&&(searchOptions={}),typeof query!="string"){var options_1=__assign(__assign(__assign({},searchOptions),query),{queries:void 0}),results_1=query.queries.map(function(subquery){return _this.executeQuery(subquery,options_1)});return this.combineResults(results_1,options_1.combineWith)}var _a3=this._options,tokenize=_a3.tokenize,processTerm=_a3.processTerm,globalSearchOptions=_a3.searchOptions,options=__assign(__assign({tokenize,processTerm},globalSearchOptions),searchOptions),searchTokenize=options.tokenize,searchProcessTerm=options.processTerm,terms=searchTokenize(query).flatMap(function(term){return searchProcessTerm(term)}).filter(function(term){return!!term}),queries=terms.map(termToQuerySpec(options)),results=queries.map(function(query2){return _this.executeQuerySpec(query2,options)});return this.combineResults(results,options.combineWith)},MiniSearch2.prototype.executeQuerySpec=function(query,searchOptions){var e_19,_a3,e_20,_b2,options=__assign(__assign({},this._options.searchOptions),searchOptions),boosts=(options.fields||this._options.fields).reduce(function(boosts2,field){var _a4;return __assign(__assign({},boosts2),(_a4={},_a4[field]=getOwnProperty(options.boost,field)||1,_a4))},{}),boostDocument=options.boostDocument,weights=options.weights,maxFuzzy=options.maxFuzzy,bm25params=options.bm25,_c2=__assign(__assign({},defaultSearchOptions.weights),weights),fuzzyWeight=_c2.fuzzy,prefixWeight=_c2.prefix,data=this._index.get(query.term),results=this.termResults(query.term,query.term,1,data,boosts,boostDocument,bm25params),prefixMatches,fuzzyMatches;if(query.prefix&&(prefixMatches=this._index.atPrefix(query.term)),query.fuzzy){var fuzzy=query.fuzzy===!0?.2:query.fuzzy,maxDistance=fuzzy<1?Math.min(maxFuzzy,Math.round(query.term.length*fuzzy)):fuzzy;maxDistance&&(fuzzyMatches=this._index.fuzzyGet(query.term,maxDistance))}if(prefixMatches)try{for(var prefixMatches_1=__values(prefixMatches),prefixMatches_1_1=prefixMatches_1.next();!prefixMatches_1_1.done;prefixMatches_1_1=prefixMatches_1.next()){var _d=__read(prefixMatches_1_1.value,2),term=_d[0],data_1=_d[1],distance=term.length-query.term.length;if(distance){fuzzyMatches?.delete(term);var weight=prefixWeight*term.length/(term.length+.3*distance);this.termResults(query.term,term,weight,data_1,boosts,boostDocument,bm25params,results)}}}catch(e_19_1){e_19={error:e_19_1}}finally{try{prefixMatches_1_1&&!prefixMatches_1_1.done&&(_a3=prefixMatches_1.return)&&_a3.call(prefixMatches_1)}finally{if(e_19)throw e_19.error}}if(fuzzyMatches)try{for(var _e=__values(fuzzyMatches.keys()),_f=_e.next();!_f.done;_f=_e.next()){var term=_f.value,_g=__read(fuzzyMatches.get(term),2),data_2=_g[0],distance=_g[1];if(distance){var weight=fuzzyWeight*term.length/(term.length+distance);this.termResults(query.term,term,weight,data_2,boosts,boostDocument,bm25params,results)}}}catch(e_20_1){e_20={error:e_20_1}}finally{try{_f&&!_f.done&&(_b2=_e.return)&&_b2.call(_e)}finally{if(e_20)throw e_20.error}}return results},MiniSearch2.prototype.combineResults=function(results,combineWith){if(combineWith===void 0&&(combineWith=OR),results.length===0)return new Map;var operator2=combineWith.toLowerCase();return results.reduce(combinators[operator2])||new Map},MiniSearch2.prototype.toJSON=function(){var e_21,_a3,e_22,_b2,index2=[];try{for(var _c2=__values(this._index),_d=_c2.next();!_d.done;_d=_c2.next()){var _e=__read(_d.value,2),term=_e[0],fieldIndex=_e[1],data={};try{for(var fieldIndex_2=(e_22=void 0,__values(fieldIndex)),fieldIndex_2_1=fieldIndex_2.next();!fieldIndex_2_1.done;fieldIndex_2_1=fieldIndex_2.next()){var _f=__read(fieldIndex_2_1.value,2),fieldId=_f[0],freqs=_f[1];data[fieldId]=Object.fromEntries(freqs)}}catch(e_22_1){e_22={error:e_22_1}}finally{try{fieldIndex_2_1&&!fieldIndex_2_1.done&&(_b2=fieldIndex_2.return)&&_b2.call(fieldIndex_2)}finally{if(e_22)throw e_22.error}}index2.push([term,data])}}catch(e_21_1){e_21={error:e_21_1}}finally{try{_d&&!_d.done&&(_a3=_c2.return)&&_a3.call(_c2)}finally{if(e_21)throw e_21.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:index2,serializationVersion:2}},MiniSearch2.prototype.termResults=function(sourceTerm,derivedTerm,termWeight,fieldTermData,fieldBoosts,boostDocumentFn,bm25params,results){var e_23,_a3,e_24,_b2,_c2;if(results===void 0&&(results=new Map),fieldTermData==null)return results;try{for(var _d=__values(Object.keys(fieldBoosts)),_e=_d.next();!_e.done;_e=_d.next()){var field=_e.value,fieldBoost=fieldBoosts[field],fieldId=this._fieldIds[field],fieldTermFreqs=fieldTermData.get(fieldId);if(fieldTermFreqs!=null){var matchingFields=fieldTermFreqs.size,avgFieldLength=this._avgFieldLength[fieldId];try{for(var _f=(e_24=void 0,__values(fieldTermFreqs.keys())),_g=_f.next();!_g.done;_g=_f.next()){var docId=_g.value;if(!this._documentIds.has(docId)){this.removeTerm(fieldId,docId,derivedTerm),matchingFields-=1;continue}var docBoost=boostDocumentFn?boostDocumentFn(this._documentIds.get(docId),derivedTerm,this._storedFields.get(docId)):1;if(docBoost){var termFreq=fieldTermFreqs.get(docId),fieldLength=this._fieldLength.get(docId)[fieldId],rawScore=calcBM25Score(termFreq,matchingFields,this._documentCount,fieldLength,avgFieldLength,bm25params),weightedScore=termWeight*fieldBoost*docBoost*rawScore,result=results.get(docId);if(result){result.score+=weightedScore,assignUniqueTerm(result.terms,sourceTerm);var match2=getOwnProperty(result.match,derivedTerm);match2?match2.push(field):result.match[derivedTerm]=[field]}else results.set(docId,{score:weightedScore,terms:[sourceTerm],match:(_c2={},_c2[derivedTerm]=[field],_c2)})}}}catch(e_24_1){e_24={error:e_24_1}}finally{try{_g&&!_g.done&&(_b2=_f.return)&&_b2.call(_f)}finally{if(e_24)throw e_24.error}}}}}catch(e_23_1){e_23={error:e_23_1}}finally{try{_e&&!_e.done&&(_a3=_d.return)&&_a3.call(_d)}finally{if(e_23)throw e_23.error}}return results},MiniSearch2.prototype.addTerm=function(fieldId,documentId,term){var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);if(fieldIndex==null)fieldIndex=new Map,fieldIndex.set(documentId,1),indexData.set(fieldId,fieldIndex);else{var docs=fieldIndex.get(documentId);fieldIndex.set(documentId,(docs||0)+1)}},MiniSearch2.prototype.removeTerm=function(fieldId,documentId,term){if(!this._index.has(term)){this.warnDocumentChanged(documentId,fieldId,term);return}var indexData=this._index.fetch(term,createMap),fieldIndex=indexData.get(fieldId);fieldIndex==null||fieldIndex.get(documentId)==null?this.warnDocumentChanged(documentId,fieldId,term):fieldIndex.get(documentId)<=1?fieldIndex.size<=1?indexData.delete(fieldId):fieldIndex.delete(documentId):fieldIndex.set(documentId,fieldIndex.get(documentId)-1),this._index.get(term).size===0&&this._index.delete(term)},MiniSearch2.prototype.warnDocumentChanged=function(shortDocumentId,fieldId,term){var e_25,_a3;try{for(var _b2=__values(Object.keys(this._fieldIds)),_c2=_b2.next();!_c2.done;_c2=_b2.next()){var fieldName=_c2.value;if(this._fieldIds[fieldName]===fieldId){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(shortDocumentId),' has changed before removal: term "').concat(term,'" was not present in field "').concat(fieldName,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(e_25_1){e_25={error:e_25_1}}finally{try{_c2&&!_c2.done&&(_a3=_b2.return)&&_a3.call(_b2)}finally{if(e_25)throw e_25.error}}},MiniSearch2.prototype.addDocumentId=function(documentId){var shortDocumentId=this._nextId;return this._idToShortId.set(documentId,shortDocumentId),this._documentIds.set(shortDocumentId,documentId),this._documentCount+=1,this._nextId+=1,shortDocumentId},MiniSearch2.prototype.addFields=function(fields){for(var i=0;i