From 819c6ab2a3e21a51f7dc12dc3b387c7bf2190a75 Mon Sep 17 00:00:00 2001 From: voodoos <5031221+voodoos@users.noreply.github.com> Date: Mon, 21 Oct 2024 09:28:14 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20voodoos/?= =?UTF-8?q?ocamix@d19d90fbd7c129da3df62d1b2b55838156943acc=20=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- yjs/bundle.js | 18 +++++++++--------- yjs/bundle.js.map | 6 +++--- yjs/main.css | 15 ++++++++++++++- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/yjs/bundle.js b/yjs/bundle.js index e67e927..352942b 100644 --- a/yjs/bundle.js +++ b/yjs/bundle.js @@ -61,20 +61,20 @@ ${escapeText(this.code(index,length3))} `);e2.default=o},207:function(t2){t2.exports=function(){"use strict";let t3=/^\s+/,e2=/\s+$/;function r2(n3,i2){if(i2=i2||{},(n3=n3||"")instanceof r2)return n3;if(!(this instanceof r2))return new r2(n3,i2);var o2=function(r3){var n4={r:0,g:0,b:0},i3=1,o3=null,a2=null,s2=null,u2=!1,c2=!1;return typeof r3=="string"&&(r3=function(r4){r4=r4.replace(t3,"").replace(e2,"").toLowerCase();var n5,i4=!1;if(y[r4])r4=y[r4],i4=!0;else if(r4=="transparent")return{r:0,g:0,b:0,a:0,format:"name"};return(n5=T.rgb.exec(r4))?{r:n5[1],g:n5[2],b:n5[3]}:(n5=T.rgba.exec(r4))?{r:n5[1],g:n5[2],b:n5[3],a:n5[4]}:(n5=T.hsl.exec(r4))?{h:n5[1],s:n5[2],l:n5[3]}:(n5=T.hsla.exec(r4))?{h:n5[1],s:n5[2],l:n5[3],a:n5[4]}:(n5=T.hsv.exec(r4))?{h:n5[1],s:n5[2],v:n5[3]}:(n5=T.hsva.exec(r4))?{h:n5[1],s:n5[2],v:n5[3],a:n5[4]}:(n5=T.hex8.exec(r4))?{r:w(n5[1]),g:w(n5[2]),b:w(n5[3]),a:O(n5[4]),format:i4?"name":"hex8"}:(n5=T.hex6.exec(r4))?{r:w(n5[1]),g:w(n5[2]),b:w(n5[3]),format:i4?"name":"hex"}:(n5=T.hex4.exec(r4))?{r:w(n5[1]+""+n5[1]),g:w(n5[2]+""+n5[2]),b:w(n5[3]+""+n5[3]),a:O(n5[4]+""+n5[4]),format:i4?"name":"hex8"}:!!(n5=T.hex3.exec(r4))&&{r:w(n5[1]+""+n5[1]),g:w(n5[2]+""+n5[2]),b:w(n5[3]+""+n5[3]),format:i4?"name":"hex"}}(r3)),typeof r3=="object"&&(R(r3.r)&&R(r3.g)&&R(r3.b)?(l2=r3.r,f2=r3.g,h2=r3.b,n4={r:255*x(l2,255),g:255*x(f2,255),b:255*x(h2,255)},u2=!0,c2=String(r3.r).substr(-1)==="%"?"prgb":"rgb"):R(r3.h)&&R(r3.s)&&R(r3.v)?(o3=S(r3.s),a2=S(r3.v),n4=function(t4,e3,r4){t4=6*x(t4,360),e3=x(e3,100),r4=x(r4,100);var n5=Math.floor(t4),i4=t4-n5,o4=r4*(1-e3),a3=r4*(1-i4*e3),s3=r4*(1-(1-i4)*e3),u3=n5%6;return{r:255*[r4,a3,o4,o4,s3,r4][u3],g:255*[s3,r4,r4,a3,o4,o4][u3],b:255*[o4,o4,s3,r4,r4,a3][u3]}}(r3.h,o3,a2),u2=!0,c2="hsv"):R(r3.h)&&R(r3.s)&&R(r3.l)&&(o3=S(r3.s),s2=S(r3.l),n4=function(t4,e3,r4){var n5,i4,o4;function a3(t5,e4,r5){return r5<0&&(r5+=1),r5>1&&(r5-=1),r5<1/6?t5+6*(e4-t5)*r5:r5<.5?e4:r5<2/3?t5+(e4-t5)*(2/3-r5)*6:t5}if(t4=x(t4,360),e3=x(e3,100),r4=x(r4,100),e3===0)n5=i4=o4=r4;else{var s3=r4<.5?r4*(1+e3):r4+e3-r4*e3,u3=2*r4-s3;n5=a3(u3,s3,t4+1/3),i4=a3(u3,s3,t4),o4=a3(u3,s3,t4-1/3)}return{r:255*n5,g:255*i4,b:255*o4}}(r3.h,o3,s2),u2=!0,c2="hsl"),r3.hasOwnProperty("a")&&(i3=r3.a)),i3=A(i3),{ok:u2,format:r3.format||c2,r:Math.min(255,Math.max(n4.r,0)),g:Math.min(255,Math.max(n4.g,0)),b:Math.min(255,Math.max(n4.b,0)),a:i3};var l2,f2,h2}(n3);this._originalInput=n3,this._r=o2.r,this._g=o2.g,this._b=o2.b,this._a=o2.a,this._roundA=Math.round(100*this._a)/100,this._format=i2.format||o2.format,this._gradientType=i2.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=o2.ok}function n2(t4,e3,r3){t4=x(t4,255),e3=x(e3,255),r3=x(r3,255);var n3,i2,o2=Math.max(t4,e3,r3),a2=Math.min(t4,e3,r3),s2=(o2+a2)/2;if(o2==a2)n3=i2=0;else{var u2=o2-a2;switch(i2=s2>.5?u2/(2-o2-a2):u2/(o2+a2),o2){case t4:n3=(e3-r3)/u2+(e3>1)+720)%360;--e3;)i2.h=(i2.h+o2)%360,a2.push(r2(i2));return a2}function b(t4,e3){e3=e3||6;for(var n3=r2(t4).toHsv(),i2=n3.h,o2=n3.s,a2=n3.v,s2=[],u2=1/e3;e3--;)s2.push(r2({h:i2,s:o2,v:a2})),a2=(a2+u2)%1;return s2}r2.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t4=this.toRgb();return(299*t4.r+587*t4.g+114*t4.b)/1e3},getLuminance:function(){var t4,e3,r3,n3=this.toRgb();return t4=n3.r/255,e3=n3.g/255,r3=n3.b/255,.2126*(t4<=.03928?t4/12.92:Math.pow((t4+.055)/1.055,2.4))+.7152*(e3<=.03928?e3/12.92:Math.pow((e3+.055)/1.055,2.4))+.0722*(r3<=.03928?r3/12.92:Math.pow((r3+.055)/1.055,2.4))},setAlpha:function(t4){return this._a=A(t4),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t4=i(this._r,this._g,this._b);return{h:360*t4.h,s:t4.s,v:t4.v,a:this._a}},toHsvString:function(){var t4=i(this._r,this._g,this._b),e3=Math.round(360*t4.h),r3=Math.round(100*t4.s),n3=Math.round(100*t4.v);return this._a==1?"hsv("+e3+", "+r3+"%, "+n3+"%)":"hsva("+e3+", "+r3+"%, "+n3+"%, "+this._roundA+")"},toHsl:function(){var t4=n2(this._r,this._g,this._b);return{h:360*t4.h,s:t4.s,l:t4.l,a:this._a}},toHslString:function(){var t4=n2(this._r,this._g,this._b),e3=Math.round(360*t4.h),r3=Math.round(100*t4.s),i2=Math.round(100*t4.l);return this._a==1?"hsl("+e3+", "+r3+"%, "+i2+"%)":"hsla("+e3+", "+r3+"%, "+i2+"%, "+this._roundA+")"},toHex:function(t4){return o(this._r,this._g,this._b,t4)},toHexString:function(t4){return"#"+this.toHex(t4)},toHex8:function(t4){return function(t5,e3,r3,n3,i2){var o2=[E(Math.round(t5).toString(16)),E(Math.round(e3).toString(16)),E(Math.round(r3).toString(16)),E(M(n3))];return i2&&o2[0].charAt(0)==o2[0].charAt(1)&&o2[1].charAt(0)==o2[1].charAt(1)&&o2[2].charAt(0)==o2[2].charAt(1)&&o2[3].charAt(0)==o2[3].charAt(1)?o2[0].charAt(0)+o2[1].charAt(0)+o2[2].charAt(0)+o2[3].charAt(0):o2.join("")}(this._r,this._g,this._b,this._a,t4)},toHex8String:function(t4){return"#"+this.toHex8(t4)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return this._a==1?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*x(this._r,255))+"%",g:Math.round(100*x(this._g,255))+"%",b:Math.round(100*x(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return this._a==1?"rgb("+Math.round(100*x(this._r,255))+"%, "+Math.round(100*x(this._g,255))+"%, "+Math.round(100*x(this._b,255))+"%)":"rgba("+Math.round(100*x(this._r,255))+"%, "+Math.round(100*x(this._g,255))+"%, "+Math.round(100*x(this._b,255))+"%, "+this._roundA+")"},toName:function(){return this._a===0?"transparent":!(this._a<1)&&(m[o(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t4){var e3="#"+a(this._r,this._g,this._b,this._a),n3=e3,i2=this._gradientType?"GradientType = 1, ":"";if(t4){var o2=r2(t4);n3="#"+a(o2._r,o2._g,o2._b,o2._a)}return"progid:DXImageTransform.Microsoft.gradient("+i2+"startColorstr="+e3+",endColorstr="+n3+")"},toString:function(t4){var e3=!!t4;t4=t4||this._format;var r3=!1,n3=this._a<1&&this._a>=0;return e3||!n3||t4!=="hex"&&t4!=="hex6"&&t4!=="hex3"&&t4!=="hex4"&&t4!=="hex8"&&t4!=="name"?(t4==="rgb"&&(r3=this.toRgbString()),t4==="prgb"&&(r3=this.toPercentageRgbString()),t4!=="hex"&&t4!=="hex6"||(r3=this.toHexString()),t4==="hex3"&&(r3=this.toHexString(!0)),t4==="hex4"&&(r3=this.toHex8String(!0)),t4==="hex8"&&(r3=this.toHex8String()),t4==="name"&&(r3=this.toName()),t4==="hsl"&&(r3=this.toHslString()),t4==="hsv"&&(r3=this.toHsvString()),r3||this.toHexString()):t4==="name"&&this._a===0?this.toName():this.toRgbString()},clone:function(){return r2(this.toString())},_applyModification:function(t4,e3){var r3=t4.apply(null,[this].concat([].slice.call(e3)));return this._r=r3._r,this._g=r3._g,this._b=r3._b,this.setAlpha(r3._a),this},lighten:function(){return this._applyModification(l,arguments)},brighten:function(){return this._applyModification(f,arguments)},darken:function(){return this._applyModification(h,arguments)},desaturate:function(){return this._applyModification(s,arguments)},saturate:function(){return this._applyModification(u,arguments)},greyscale:function(){return this._applyModification(c,arguments)},spin:function(){return this._applyModification(d,arguments)},_applyCombination:function(t4,e3){return t4.apply(null,[this].concat([].slice.call(e3)))},analogous:function(){return this._applyCombination(v,arguments)},complement:function(){return this._applyCombination(p,arguments)},monochromatic:function(){return this._applyCombination(b,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(g,[3])},tetrad:function(){return this._applyCombination(g,[4])}},r2.fromRatio=function(t4,e3){if(typeof t4=="object"){var n3={};for(var i2 in t4)t4.hasOwnProperty(i2)&&(n3[i2]=i2==="a"?t4[i2]:S(t4[i2]));t4=n3}return r2(t4,e3)},r2.equals=function(t4,e3){return!(!t4||!e3)&&r2(t4).toRgbString()==r2(e3).toRgbString()},r2.random=function(){return r2.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},r2.mix=function(t4,e3,n3){n3=n3===0?0:n3||50;var i2=r2(t4).toRgb(),o2=r2(e3).toRgb(),a2=n3/100;return r2({r:(o2.r-i2.r)*a2+i2.r,g:(o2.g-i2.g)*a2+i2.g,b:(o2.b-i2.b)*a2+i2.b,a:(o2.a-i2.a)*a2+i2.a})},r2.readability=function(t4,e3){var n3=r2(t4),i2=r2(e3);return(Math.max(n3.getLuminance(),i2.getLuminance())+.05)/(Math.min(n3.getLuminance(),i2.getLuminance())+.05)},r2.isReadable=function(t4,e3,n3){var i2,o2,a2,s2,u2,c2=r2.readability(t4,e3);switch(o2=!1,(a2=n3,(s2=((a2=a2||{level:"AA",size:"small"}).level||"AA").toUpperCase())!=="AA"&&s2!=="AAA"&&(s2="AA"),(u2=(a2.size||"small").toLowerCase())!=="small"&&u2!=="large"&&(u2="small"),i2={level:s2,size:u2}).level+i2.size){case"AAsmall":case"AAAlarge":o2=c2>=4.5;break;case"AAlarge":o2=c2>=3;break;case"AAAsmall":o2=c2>=7}return o2},r2.mostReadable=function(t4,e3,n3){var i2,o2,a2,s2,u2=null,c2=0;o2=(n3=n3||{}).includeFallbackColors,a2=n3.level,s2=n3.size;for(var l2=0;l2c2&&(c2=i2,u2=r2(e3[l2]));return r2.isReadable(t4,u2,{level:a2,size:s2})||!o2?u2:(n3.includeFallbackColors=!1,r2.mostReadable(t4,["#fff","#000"],n3))};var y=r2.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},m=r2.hexNames=function(t4){var e3={};for(var r3 in t4)t4.hasOwnProperty(r3)&&(e3[t4[r3]]=r3);return e3}(y);function A(t4){return t4=parseFloat(t4),(isNaN(t4)||t4<0||t4>1)&&(t4=1),t4}function x(t4,e3){(function(t5){return typeof t5=="string"&&t5.indexOf(".")!=-1&&parseFloat(t5)===1})(t4)&&(t4="100%");var r3=function(t5){return typeof t5=="string"&&t5.indexOf("%")!=-1}(t4);return t4=Math.min(e3,Math.max(0,parseFloat(t4))),r3&&(t4=parseInt(t4*e3,10)/100),Math.abs(t4-e3)<1e-6?1:t4%e3/parseFloat(e3)}function C(t4){return Math.min(1,Math.max(0,t4))}function w(t4){return parseInt(t4,16)}function E(t4){return t4.length==1?"0"+t4:""+t4}function S(t4){return t4<=1&&(t4=100*t4+"%"),t4}function M(t4){return Math.round(255*parseFloat(t4)).toString(16)}function O(t4){return w(t4)/255}var j,L,k,T=(L="[\\s|\\(]+("+(j="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+j+")[,|\\s]+("+j+")\\s*\\)?",k="[\\s|\\(]+("+j+")[,|\\s]+("+j+")[,|\\s]+("+j+")[,|\\s]+("+j+")\\s*\\)?",{CSS_UNIT:new RegExp(j),rgb:new RegExp("rgb"+L),rgba:new RegExp("rgba"+k),hsl:new RegExp("hsl"+L),hsla:new RegExp("hsla"+k),hsv:new RegExp("hsv"+L),hsva:new RegExp("hsva"+k),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function R(t4){return!!T.CSS_UNIT.exec(t4)}return r2}()}},e={};function r(n2){var i=e[n2];if(i!==void 0)return i.exports;var o=e[n2]={id:n2,loaded:!1,exports:{}};return t[n2].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}r.n=t2=>{var e2=t2&&t2.__esModule?()=>t2.default:()=>t2;return r.d(e2,{a:e2}),e2},r.d=(t2,e2)=>{for(var n2 in e2)r.o(e2,n2)&&!r.o(t2,n2)&&Object.defineProperty(t2,n2,{enumerable:!0,get:e2[n2]})},r.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),r.o=(t2,e2)=>Object.prototype.hasOwnProperty.call(t2,e2),r.r=t2=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(t2,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t2,"__esModule",{value:!0})},r.nmd=t2=>(t2.paths=[],t2.children||(t2.children=[]),t2),r.nc=void 0;var n=r(607);return n.default})())}});var y_quill_exports={};__export(y_quill_exports,{QuillBinding:()=>QuillBinding,normQuillDelta:()=>normQuillDelta});var normQuillDelta,updateCursor,QuillBinding,init_y_quill=__esm({"node_modules/y-quill/src/y-quill.js"(){init_yjs();normQuillDelta=delta=>{if(delta.length>0){let d=delta[delta.length-1],insert=d.insert;if(d.attributes===void 0&&insert!==void 0&&insert.slice(-1)===` `){delta=delta.slice();let ins=insert.slice(0,-1);for(;ins.slice(-1)===` -`;)ins=ins.slice(0,-1);return delta[delta.length-1]={insert:ins},ins.length===0&&delta.pop(),delta}}return delta},updateCursor=(quillCursors,aw,clientId,doc2,type)=>{try{if(aw&&aw.cursor&&clientId!==doc2.clientID){let user=aw.user||{},color=user.color||"#ffa500",name=user.name||`User: ${clientId}`;quillCursors.createCursor(clientId.toString(),name,color);let anchor=createAbsolutePositionFromRelativePosition(createRelativePositionFromJSON(aw.cursor.anchor),doc2),head=createAbsolutePositionFromRelativePosition(createRelativePositionFromJSON(aw.cursor.head),doc2);anchor&&head&&anchor.type===type&&quillCursors.moveCursor(clientId.toString(),{index:anchor.index,length:head.index-anchor.index})}else quillCursors.removeCursor(clientId.toString())}catch(err){console.error(err)}},QuillBinding=class{constructor(type,quill,awareness){let doc2=type.doc;this.type=type,this.doc=doc2,this.quill=quill;let quillCursors=quill.getModule("cursors")||null;this.quillCursors=quillCursors,this._negatedUsedFormats={},this.awareness=awareness,this._awarenessChange=({added,removed,updated})=>{let states=awareness.getStates();added.forEach(id2=>{updateCursor(quillCursors,states.get(id2),id2,doc2,type)}),updated.forEach(id2=>{updateCursor(quillCursors,states.get(id2),id2,doc2,type)}),removed.forEach(id2=>{quillCursors.removeCursor(id2.toString())})},this._typeObserver=event=>{if(event.transaction.origin!==this){let eventDelta=event.delta,delta=[];for(let i=0;i{if(delta&&delta.ops){let ops=delta.ops;ops.forEach(op=>{if(op.attributes!==void 0)for(let key in op.attributes)this._negatedUsedFormats[key]===void 0&&(this._negatedUsedFormats[key]=!1)}),origin!==this&&doc2.transact(()=>{type.applyDelta(ops)},this)}if(awareness&&quillCursors){let sel=quill.getSelection(),aw=awareness.getLocalState();if(sel===null)awareness.getLocalState()!==null&&awareness.setLocalStateField("cursor",null);else{let anchor=createRelativePositionFromTypeIndex(type,sel.index),head=createRelativePositionFromTypeIndex(type,sel.index+sel.length);(!aw||!aw.cursor||!compareRelativePositions(anchor,aw.cursor.anchor)||!compareRelativePositions(head,aw.cursor.head))&&awareness.setLocalStateField("cursor",{anchor,head})}awareness.getStates().forEach((aw2,clientId)=>{updateCursor(quillCursors,aw2,clientId,doc2,type)})}},quill.on("editor-change",this._quillObserver),quill.setContents(type.toDelta(),this),quillCursors!==null&&awareness&&(awareness.getStates().forEach((aw,clientId)=>{updateCursor(quillCursors,aw,clientId,doc2,type)}),awareness.on("change",this._awarenessChange))}destroy(){this.type.unobserve(this._typeObserver),this.quill.off("editor-change",this._quillObserver),this.awareness&&this.awareness.off("change",this._awarenessChange)}}}});(function(a){typeof globalThis!="object"&&(this?b():(a.defineProperty(a.prototype,"_T_",{configurable:!0,get:b}),_T_));function b(){var b2=this||self;b2.globalThis=b2,delete a.prototype._T_}})(Object);(function(a){window.yjs=(init_yjs(),__toCommonJS(yjs_exports)),window.WebrtcProvider=(init_y_webrtc(),__toCommonJS(y_webrtc_exports)).WebrtcProvider,window.IndexeddbPersistence=(init_y_indexeddb(),__toCommonJS(y_indexeddb_exports)).IndexeddbPersistence})(globalThis);(function(a){require_quill_core(),require_quill_bubble(),require_quill_snow(),window.Quill=(init_quill2(),__toCommonJS(quill_exports)).default,window.QuillCursors=require_quill_cursors()})(globalThis);(function(a){window.QuillBinding=(init_y_quill(),__toCommonJS(y_quill_exports)).QuillBinding})(globalThis);(function(p){"use strict";var v=3850876,aE=" ",ad="0",fY="compare: functional value",fX="mkdir",cu=1e3,jF="delete",X="vendor/lwd/lib/lwd/lwd_seq.pp.ml",kq="@[",kp="window",kP="console",dO="int_of_string",fE="fs",j9="%u",ko="/static/",jE="%i",kO="%ni",aX=255,fW=749039939,kn="Assert_failure",aG=737455525,j8="camlinternalMod.ml",jD="0x",j7=32752,kN=218,jC=57343,j6="End_of_file",km="OCAMLRUNPARAM",jB=": closedir failed",kl=253,kM="Out_of_memory",jA="Not_found",f3="Failure",dN="Unix.Unix_error",jz="style",j5="^",bW="text",kL="length",fQ="ENOTDIR",kk="Lwd_seq.rank: node is marked",bv=936573133,jy="%Li",jw="flex",jx="Invalid_argument",dG=254,bV="+",dI="Set.bal",kK=", characters ",aV=16777215,j4=858694086,kj=120,ki=1027,ct=1024,dM="Map.bal",ba=246,j3="Pervasives.do_at_exit",kh=389604418,j2=65536,jv="submit",c="vendor/brr_lwd_ui/examples/yjs/main.ml",fP=15,T=16620,ju=", ",dF=512,fO=-588596599,kI="Match_failure",kJ="closedir",js="%li",jt=1026,kH=-32,jr=157,jq="b",fD="nan",e="",fC="rmdir",fV="Fatal error: exception ",j1="infinity",K="camlinternalFormat.ml",j0="fd ",kF="append",kG=": ",jp=174,q=248,jZ="em",jY="data",kE=224,kg=24029,jX=240,jW="Sys_error",ao=128,fN="vendor/brr_lwd_ui/bindings/yjs/doc.ml",kf="ENOTEMPTY",kD="EEXIST",fU=1255,jV=1073741823,dE="value",fB=" : flags Open_text and Open_binary are not compatible",kC="px",fM="e",kB=459,fA=": Not a directory",fL="ENOENT",ke="Stack_overflow",fK=-605101559,S=15681,jU="Array",kA="Undefined_recursive_module",kz=2147483647,aF=32768,cs="string",dH="table",jT=2048,kd=-48,jn="error",jo=" : is a directory",jR="@{",jS="Division_by_zero",jm="classList",a$=".",jQ=`(Program not linked with -g, cannot print stack backtrace) -`,cq="name",bb=63,ky=492,a_=737456202,fJ=" : file already exists",bu=128,dL=": No such file or directory",jO="vendor/lwd/lib/brr-lwd/elwd.ml",jP=255,dD="lwd-to-remove",cv=256,jl="checked",cr=-976970511,fI=100,jN="id",fz="index out of bounds",kc=-937474657,aH="/",fy=504440814,dC=252,kx="height: ",jk="lwdui-virtual-table-row",fx="%d",kw=383,jj=": file descriptor already closed",bs="-",fw="EBADF",jM="changes",aW=951901561,jL=102,fH=-97,kv="Printexc.handle_uncaught_exception",ji=12520,f2=" : flags Open_rdonly and Open_wronly are not compatible",a="vendor/lwd/lib/lwd/lwd_table.ml",fT=756711075,kb=`Fatal error: exception %s -`,fG=4100401,ku="class",jh="\xE2\x9D\x8C",aD=250,jK=199,dK="bool",f0=82908052,f1="kind",bt=611392745,fF="cell",kt=">",jJ="([^/]+)",ka="input",fS="jsError",jg=103,dB='"',aI=65535,fZ=127,fR=737308346,jf=56320,jI="documentElement",ks="Sys_blocked_io",b="vendor/lwd/lib/lwd/lwd.ml",j$="not implemented",je="buffer.ml",jH="Form submitted:",kr="_",fv="target",jG=-101336657,j_="rem",dJ="_bigarr02";function zh(a10,b10,c10,d10,e10){if(d10<=b10)for(var f10=1;f10<=e10;f10++)c10[d10+f10]=a10[b10+f10];else for(var f10=e10;f10>=1;f10--)c10[d10+f10]=a10[b10+f10];return 0}function zi(a10,b10,c10){var d10=new Array(c10+1);d10[0]=0;for(var e10=1,f10=b10+1;e10<=c10;e10++,f10++)d10[e10]=a10[f10];return d10}function cE(a10,b10,c10){var d10=String.fromCharCode;if(b10==0&&c10<=4096&&c10==a10.length)return d10.apply(null,a10);for(var f10=e;0=c10.l||c10.t==2&&e10>=c10.c.length))c10.c=a10.t==4?cE(a10.c,b10,e10):b10==0&&a10.c.length==e10?a10.c:a10.c.substr(b10,e10),c10.t=c10.c.length==c10.l?0:2;else if(c10.t==2&&d10==c10.c.length)c10.c+=a10.t==4?cE(a10.c,b10,e10):b10==0&&a10.c.length==e10?a10.c:a10.c.substr(b10,e10),c10.t=c10.c.length==c10.l?0:2;else{c10.t!=4&&dS(c10);var g10=a10.c,h10=c10.c;if(a10.t==4)if(d10<=b10)for(var f10=0;f10=0;f10--)h10[d10+f10]=g10[b10+f10];else{for(var i10=Math.min(e10,g10.length-b10),f10=0;f10>=1,a10==0)return d10;b10+=b10,c10++,c10==9&&b10.slice(0,1)}}function cz(a10){a10.t==2?a10.c+=b1(a10.l-a10.c.length,"\0"):a10.c=cE(a10.c,0,a10.c.length),a10.t=0}function gn(a10){if(a10.length<24){for(var b10=0;b10fZ)return!1;return!0}else return!/[^\x00-\x7f]/.test(a10)}function ll(a10){for(var k10=e,d10=e,h10,g10,i10,b10,c10=0,j10=a10.length;c10dF?(d10.substr(0,1),k10+=d10,d10=e,k10+=a10.slice(c10,f10)):d10+=a10.slice(c10,f10),f10==j10)break;c10=f10}b10=1,++c10=55295&&b10<57344)&&(b10=2)):(b10=3,++c101114111)&&(b10=3)))))),b10<4?(c10-=b10,d10+="\uFFFD"):b10>aI?d10+=String.fromCharCode(55232+(b10>>10),jf+(b10&1023)):d10+=String.fromCharCode(b10),d10.length>ct&&(d10.substr(0,1),k10+=d10,d10=e)}return k10+d10}function aY(a10,b10,c10){this.t=a10,this.c=b10,this.l=c10}aY.prototype.toString=function(){switch(this.t){case 9:return this.c;default:cz(this);case 0:if(gn(this.c))return this.t=9,this.c;this.t=8;case 8:return this.c}},aY.prototype.toUtf16=function(){var a10=this.toString();return this.t==9?a10:ll(a10)},aY.prototype.slice=function(){var a10=this.t==4?this.c.slice():this.c;return new aY(this.t,a10,this.l)};function kX(a10){return new aY(0,a10,a10.length)}function aJ(a10){return a10}function bd(a10){return kX(a10)}function cy(a10,b10,c10,d10,e10){return aZ(bd(a10),b10,c10,d10,e10),0}function ln(a10){var b10=p.process;if(b10&&b10.env&&b10.env[a10]!=null)return b10.env[a10];if(p.jsoo_static_env&&p.jsoo_static_env[a10])return p.jsoo_static_env[a10]}var gk=0;(function(){var c10=ln(km);if(c10!==void 0)for(var b10=c10.split(","),a10=0;a10=a10.c.length)return 0;case 0:return a10.c.charCodeAt(b10);case 4:return a10.c[b10]}}function zn(a10,b10){return b10>>>0>=a10.l&&f5(),bY(a10,b10)}function A(a10,b10,c10){if(c10&=aX,a10.t!=4){if(b10==a10.c.length)return a10.c+=String.fromCharCode(c10),b10+1==a10.l&&(a10.t=0),0;dS(a10)}return a10.c[b10]=c10,0}function a0(a10,b10,c10){return b10>>>0>=a10.l&&f5(),A(a10,b10,c10)}function bx(a10){return a10.toArray()}function zo(a10,b10,c10){b10>>>0>=a10.l-7&&f5();for(var e10=bx(c10),d10=0;d10<8;d10++)A(a10,b10+7-d10,e10[d10]);return 0}function be(d10,c10){var f10=d10.l>=0?d10.l:d10.l=d10.length,e10=c10.length,b10=f10-e10;if(b10==0)return d10.apply(null,c10);if(b10<0){var a10=d10.apply(null,c10.slice(0,f10));return typeof a10!="function"?a10:be(a10,c10.slice(f10))}else{switch(b10){case 1:{var a10=function(a11){for(var f11=new Array(e10+1),b11=0;b11>>0>=a10.length-1&&cx(),a10}function zp(a10){return isFinite(a10)?Math.abs(a10)>=22250738585072014e-324?0:a10!=0?1:2:isNaN(a10)?4:3}function k9(a10){return 0}var Ak=Math.log2&&Math.log2(11235582092889474e291)==1020;function Aj(a10){if(Ak)return Math.floor(Math.log2(a10));var b10=0;if(a10==0)return-1/0;if(a10>=1)for(;a10>=2;)a10/=2,b10++;else for(;a10<1;)a10*=2,b10--;return b10}function ga(a10){var b10=new Float32Array(1);b10[0]=a10;var c10=new Int32Array(b10.buffer);return c10[0]|0}var k4=Math.pow(2,-24);function lf(a10){throw a10}function gj(){lf(U.Division_by_zero)}function d(a10,b10,c10){this.lo=a10&aV,this.mi=b10&aV,this.hi=c10&aI}d.prototype.caml_custom="_j",d.prototype.copy=function(){return new d(this.lo,this.mi,this.hi)},d.prototype.ucompare=function(a10){return this.hi>a10.hi?1:this.hia10.mi?1:this.mia10.lo?1:this.loc10?1:b10a10.mi?1:this.mia10.lo?1:this.lo>24),c10=-this.hi+(b10>>24);return new d(a10,b10,c10)},d.prototype.add=function(a10){var b10=this.lo+a10.lo,c10=this.mi+a10.mi+(b10>>24),e10=this.hi+a10.hi+(c10>>24);return new d(b10,c10,e10)},d.prototype.sub=function(a10){var b10=this.lo-a10.lo,c10=this.mi-a10.mi+(b10>>24),e10=this.hi-a10.hi+(c10>>24);return new d(b10,c10,e10)},d.prototype.mul=function(a10){var b10=this.lo*a10.lo,c10=(b10*k4|0)+this.mi*a10.lo+this.lo*a10.mi,e10=(c10*k4|0)+this.hi*a10.lo+this.mi*a10.mi+this.lo*a10.hi;return new d(b10,c10,e10)},d.prototype.isZero=function(){return(this.lo|this.mi|this.hi)==0},d.prototype.isNeg=function(){return this.hi<<16<0},d.prototype.and=function(a10){return new d(this.lo&a10.lo,this.mi&a10.mi,this.hi&a10.hi)},d.prototype.or=function(a10){return new d(this.lo|a10.lo,this.mi|a10.mi,this.hi|a10.hi)},d.prototype.xor=function(a10){return new d(this.lo^a10.lo,this.mi^a10.mi,this.hi^a10.hi)},d.prototype.shift_left=function(a10){return a10=a10&63,a10==0?this:a10<24?new d(this.lo<>24-a10,this.hi<>24-a10):a10<48?new d(0,this.lo<>48-a10):new d(0,0,this.lo<>a10|this.mi<<24-a10,this.mi>>a10|this.hi<<24-a10,this.hi>>a10):a10<48?new d(this.mi>>a10-24|this.hi<<48-a10,this.hi>>a10-24,0):new d(this.hi>>a10-48,0,0)},d.prototype.shift_right=function(a10){if(a10=a10&63,a10==0)return this;var c10=this.hi<<16>>16;if(a10<24)return new d(this.lo>>a10|this.mi<<24-a10,this.mi>>a10|c10<<24-a10,this.hi<<16>>a10>>>16);var b10=this.hi<<16>>31;return a10<48?new d(this.mi>>a10-24|this.hi<<48-a10,this.hi<<16>>a10-24>>16,b10&aI):new d(this.hi<<16>>a10-32,b10,b10)},d.prototype.lsl1=function(){this.hi=this.hi<<1|this.mi>>23,this.mi=(this.mi<<1|this.lo>>23)&aV,this.lo=this.lo<<1&aV},d.prototype.lsr1=function(){this.lo=(this.lo>>>1|this.mi<<23)&aV,this.mi=(this.mi>>>1|this.hi<<23)&aV,this.hi=this.hi>>>1},d.prototype.udivmod=function(a10){for(var e10=0,c10=this.copy(),b10=a10.copy(),f10=new d(0,0,0);c10.ucompare(b10)>0;)e10++,b10.lsl1();for(;e10>=0;)e10--,f10.lsl1(),c10.ucompare(b10)>=0&&(f10.lo++,c10=c10.sub(b10)),b10.lsr1();return{quotient:f10,modulus:c10}},d.prototype.div=function(a10){var b10=this;a10.isZero()&&gj();var d10=b10.hi^a10.hi;b10.hi&aF&&(b10=b10.neg()),a10.hi&aF&&(a10=a10.neg());var c10=b10.udivmod(a10).quotient;return d10&aF&&(c10=c10.neg()),c10},d.prototype.mod=function(a10){var b10=this;a10.isZero()&&gj();var d10=b10.hi;b10.hi&aF&&(b10=b10.neg()),a10.hi&aF&&(a10=a10.neg());var c10=b10.udivmod(a10).modulus;return d10&aF&&(c10=c10.neg()),c10},d.prototype.toInt=function(){return this.lo|this.mi<<24},d.prototype.toFloat=function(){return(this.hi<<16)*Math.pow(2,32)+this.mi*Math.pow(2,24)+this.lo},d.prototype.toArray=function(){return[this.hi>>8,this.hi&aX,this.mi>>16,this.mi>>8&aX,this.mi&aX,this.lo>>16,this.lo>>8&aX,this.lo&aX]},d.prototype.lo32=function(){return this.lo|(this.mi&aX)<<24},d.prototype.hi32=function(){return this.mi>>>8&aI|this.hi<<16};function dV(a10,b10,c10){return new d(a10,b10,c10)}function dU(a10){if(!isFinite(a10))return isNaN(a10)?dV(1,0,j7):a10>0?dV(0,0,j7):dV(0,0,65520);var f10=a10==0&&1/a10==-1/0?aF:a10>=0?0:aF;f10&&(a10=-a10);var b10=Aj(a10)+1023;b10<=0?(b10=0,a10/=Math.pow(2,-jt)):(a10/=Math.pow(2,b10-ki),a10<16&&(a10*=2,b10-=1),b10==0&&(a10/=2));var d10=Math.pow(2,24),c10=a10|0;a10=(a10-c10)*d10;var e10=a10|0;a10=(a10-e10)*d10;var g10=a10|0;return c10=c10&fP|f10|b10<<4,dV(g10,e10,c10)}function kW(a10,b10,c10){if(a10.write(32,b10.dims.length),a10.write(32,b10.kind|b10.layout<<8),b10.caml_custom==dJ)for(var d10=0;d10>4;if(d10==2047)return f10|g10|c10&fP?NaN:c10&aF?-1/0:1/0;var e10=Math.pow(2,-24),b10=(f10*e10+g10)*e10+(c10&fP);return d10>0?(b10+=16,b10*=Math.pow(2,d10-ki)):b10*=Math.pow(2,-jt),c10&aF&&(b10=-b10),b10}function f4(a10){for(var d10=a10.length,c10=1,b10=0;b10>>24&aX|(b10&aI)<<8,b10>>>16&aI)}function gd(a10){return a10.hi32()}function ge(a10){return a10.lo32()}var zk=dJ;function bc(a10,b10,c10,d10){this.kind=a10,this.layout=b10,this.dims=c10,this.data=d10}bc.prototype.caml_custom=zk,bc.prototype.offset=function(a10){var c10=0;if(typeof a10=="number"&&(a10=[a10]),a10 instanceof Array||G("bigarray.js: invalid offset"),this.dims.length!=a10.length&&G("Bigarray.get/set: bad number of dimensions"),this.layout==0)for(var b10=0;b10=this.dims[b10])&&cx(),c10=c10*this.dims[b10]+a10[b10];else for(var b10=this.dims.length-1;b10>=0;b10--)(a10[b10]<1||a10[b10]>this.dims[b10])&&cx(),c10=c10*this.dims[b10]+(a10[b10]-1);return c10},bc.prototype.get=function(a10){switch(this.kind){case 7:var d10=this.data[a10*2+0],b10=this.data[a10*2+1];return zI(d10,b10);case 10:case 11:var e10=this.data[a10*2+0],c10=this.data[a10*2+1];return[dG,e10,c10];default:return this.data[a10]}},bc.prototype.set=function(a10,b10){switch(this.kind){case 7:this.data[a10*2+0]=ge(b10),this.data[a10*2+1]=gd(b10);break;case 10:case 11:this.data[a10*2+0]=b10[1],this.data[a10*2+1]=b10[2];break;default:this.data[a10]=b10;break}return 0},bc.prototype.fill=function(a10){switch(this.kind){case 7:var c10=ge(a10),e10=gd(a10);if(c10==e10)this.data.fill(c10);else for(var b10=0;b10e10)return 1;if(d10!=e10){if(!b10)return NaN;if(d10==d10)return 1;if(e10==e10)return-1}}break;case 7:for(var c10=0;c10a10.data[c10+1])return 1;if(this.data[c10]>>>0>>0)return-1;if(this.data[c10]>>>0>a10.data[c10]>>>0)return 1}break;case 2:case 3:case 4:case 5:case 6:case 8:case 9:case 12:for(var c10=0;c10a10.data[c10])return 1}break}return 0};function bX(a10,b10,c10,d10){this.kind=a10,this.layout=b10,this.dims=c10,this.data=d10}bX.prototype=new bc,bX.prototype.offset=function(a10){return typeof a10!="number"&&(a10 instanceof Array&&a10.length==1?a10=a10[0]:G("Ml_Bigarray_c_1_1.offset")),(a10<0||a10>=this.dims[0])&&cx(),a10},bX.prototype.get=function(a10){return this.data[a10]},bX.prototype.set=function(a10,b10){return this.data[a10]=b10,0},bX.prototype.fill=function(a10){return this.data.fill(a10),0};function kS(a10,b10,c10,d10){var e10=kU(a10);return f4(c10)*e10!=d10.length&&G("length doesn't match dims"),b10==0&&c10.length==1&&e10==1?new bX(a10,b10,c10,d10):new bc(a10,b10,c10,d10)}function aj(a10){U.Failure||(U.Failure=[q,f3,-3]),gi(U.Failure,a10)}function kT(a10,b10,c10){var k10=a10.read32s();(k10<0||k10>16)&&aj("input_value: wrong number of bigarray dimensions");var r10=a10.read32s(),l10=r10&aX,q10=r10>>8&1,j10=[];if(c10==dJ)for(var d10=0;d10>>17,b10=cC(b10,461845907),a10^=b10,a10=a10<<13|a10>>>19,(a10+(a10<<2)|0)+-430675100|0}function zC(a10,b10){return a10=V(a10,ge(b10)),a10=V(a10,gd(b10)),a10}function f_(a10,b10){return zC(a10,dU(b10))}function kV(a10){var c10=f4(a10.dims),d10=0;switch(a10.kind){case 2:case 3:case 12:c10>cv&&(c10=cv);var e10=0,b10=0;for(b10=0;b10+4<=a10.data.length;b10+=4)e10=a10.data[b10+0]|a10.data[b10+1]<<8|a10.data[b10+2]<<16|a10.data[b10+3]<<24,d10=V(d10,e10);switch(e10=0,c10&3){case 3:e10=a10.data[b10+2]<<16;case 2:e10|=a10.data[b10+1]<<8;case 1:e10|=a10.data[b10+0],d10=V(d10,e10)}break;case 4:case 5:c10>bu&&(c10=bu);var e10=0,b10=0;for(b10=0;b10+2<=a10.data.length;b10+=2)e10=a10.data[b10+0]|a10.data[b10+1]<<16,d10=V(d10,e10);c10&1&&(d10=V(d10,a10.data[b10]));break;case 6:c10>64&&(c10=64);for(var b10=0;b1064&&(c10=64);for(var b10=0;b1032&&(c10=32),c10*=2;for(var b10=0;b1064&&(c10=64);for(var b10=0;b1032&&(c10=32);for(var b10=0;b100?f10(b10,a10,d10):f10(a10,b10,d10);if(d10&&e10!=e10)return c10;if(+e10!=+e10)return+e10;if(e10|0)return e10|0}return c10}function dY(a10){return typeof a10=="string"&&!/[^\x00-\xff]/.test(a10)}function dX(a10){return a10 instanceof aY}function kZ(a10){if(typeof a10=="number")return cu;if(dX(a10))return dC;if(dY(a10))return 1252;if(a10 instanceof Array&&a10[0]===a10[0]>>>0&&a10[0]<=jP){var b10=a10[0]|0;return b10==dG?0:b10}else{if(a10 instanceof String)return ji;if(typeof a10=="string")return ji;if(a10 instanceof Number)return cu;if(a10&&a10.caml_custom)return fU;if(a10&&a10.compare)return 1256;if(typeof a10=="function")return 1247;if(typeof a10=="symbol")return 1251}return 1001}function k7(a10,b10){return a10b10?1:0}function zm(a10,b10){return a10.t&6&&cz(a10),b10.t&6&&cz(b10),a10.cb10.c?1:0}function dR(a10,b10,c10){for(var f10=[];;){if(!(c10&&a10===b10)){var e10=kZ(a10);if(e10==aD){a10=a10[1];continue}var g10=kZ(b10);if(g10==aD){b10=b10[1];continue}if(e10!==g10)return e10==cu?g10==fU?kY(a10,b10,-1,c10):-1:g10==cu?e10==fU?kY(b10,a10,1,c10):1:e10b10)return 1;if(a10!=b10){if(!c10)return NaN;if(a10==a10)return 1;if(b10==b10)return-1}break;case 1001:if(a10b10)return 1;if(a10!=b10){if(!c10)return NaN;if(a10==a10)return 1;if(b10==b10)return-1}break;case 1251:if(a10!==b10)return c10?1:NaN;break;case 1252:var a10=a10,b10=b10;if(a10!==b10){if(a10b10)return 1}break;case 12520:var a10=a10.toString(),b10=b10.toString();if(a10!==b10){if(a10b10)return 1}break;case 246:case 254:default:if(k9(e10)){G("compare: continuation value");break}if(a10.length!=b10.length)return a10.length1&&f10.push(a10,b10,1);break}}if(f10.length==0)return 0;var h10=f10.pop();b10=f10.pop(),a10=f10.pop(),h10+10)if(b10==0&&(c10>=a10.l||a10.t==2&&c10>=a10.c.length))d10==0?(a10.c=e,a10.t=2):(a10.c=b1(c10,String.fromCharCode(d10)),a10.t=c10==a10.l?0:2);else for(a10.t!=4&&dS(a10),c10+=b10;b100&&b10===b10||(a10=a10.replace(/_/g,e),b10=+a10,a10.length>0&&b10===b10||/^[+-]?nan$/i.test(a10)))return b10;var c10=/^ *([+-]?)0x([0-9a-f]+)\.?([0-9a-f]*)(p([+-]?[0-9]+))?/i.exec(a10);if(c10){var d10=c10[3].replace(/0+$/,e),g10=parseInt(c10[1]+c10[2]+d10,16),f10=(c10[5]|0)-4*d10.length;return b10=g10*Math.pow(2,f10),b10}if(/^\+?inf(inity)?$/i.test(a10))return 1/0;if(/^-inf(inity)?$/i.test(a10))return-1/0;aj("float_of_string")}function gh(a10){a10=a10;var e10=a10.length;e10>31&&G("format_int: format too long");for(var b10={justify:bV,signstyle:bs,filler:aE,alternate:!1,base:0,signedconv:!1,width:0,uppercase:!1,sign:1,prec:-1,conv:"f"},d10=0;d10=0&&c10<=9;)b10.width=b10.width*10+c10,d10++;d10--;break;case".":for(b10.prec=0,d10++;c10=a10.charCodeAt(d10)-48,c10>=0&&c10<=9;)b10.prec=b10.prec*10+c10,d10++;d10--;case"d":case"i":b10.signedconv=!0;case"u":b10.base=10;break;case"x":b10.base=16;break;case"X":b10.base=16,b10.uppercase=!0;break;case"o":b10.base=8;break;case"e":case"f":case"g":b10.signedconv=!0,b10.conv=c10;break;case"E":case"F":case"G":b10.signedconv=!0,b10.uppercase=!0,b10.conv=c10.toLowerCase();break}}return b10}function f8(a10,b10){a10.uppercase&&(b10=b10.toUpperCase());var f10=b10.length;a10.signedconv&&(a10.sign<0||a10.signstyle!=bs)&&f10++,a10.alternate&&(a10.base==8&&(f10+=1),a10.base==16&&(f10+=2));var c10=e;if(a10.justify==bV&&a10.filler==aE)for(var d10=f10;d1020?(c11-=20,a11/=Math.pow(10,c11),a11+=new Array(c11+1).join(ad),b11>0&&(a11=a11+a$+new Array(b11+1).join(ad)),a11):a11.toFixed(b11)}var c10,f10=gh(a10),e10=f10.prec<0?6:f10.prec;if((b10<0||b10==0&&1/b10==-1/0)&&(f10.sign=-1,b10=-b10),isNaN(b10))c10=fD,f10.filler=aE;else if(!isFinite(b10))c10="inf",f10.filler=aE;else switch(f10.conv){case"e":var c10=b10.toExponential(e10),d10=c10.length;c10.charAt(d10-3)==fM&&(c10=c10.slice(0,d10-1)+ad+c10.slice(d10-1));break;case"f":c10=j10(b10,e10);break;case"g":e10=e10||1,c10=b10.toExponential(e10-1);var i10=c10.indexOf(fM),h10=+c10.slice(i10+1);if(h10<-4||b10>=1e21||b10.toFixed(0).length>e10){for(var d10=i10-1;c10.charAt(d10)==ad;)d10--;c10.charAt(d10)==a$&&d10--,c10=c10.slice(0,d10+1)+c10.slice(i10),d10=c10.length,c10.charAt(d10-3)==fM&&(c10=c10.slice(0,d10-1)+ad+c10.slice(d10-1));break}else{var g10=e10;if(h10<0)g10-=h10+1,c10=b10.toFixed(g10);else for(;c10=b10.toFixed(g10),c10.length>e10+1;)g10--;if(g10){for(var d10=c10.length-1;c10.charAt(d10)==ad;)d10--;c10.charAt(d10)==a$&&d10--,c10=c10.slice(0,d10+1)}}break}return f8(f10,c10)}function dT(a10,b10){if(a10==fx)return e+b10;var c10=gh(a10);b10<0&&(c10.signedconv?(c10.sign=-1,b10=-b10):b10>>>=0);var d10=b10.toString(c10.base);if(c10.prec>=0){c10.filler=aE;var f10=c10.prec-d10.length;f10>0&&(d10=b1(f10,ad)+d10)}return f8(c10,d10)}var z_=0;function ae(){return z_++}function H(a10){return gn(a10)?a10:ll(a10)}function cF(){return typeof p.process<"u"&&typeof p.process.versions<"u"&&typeof p.process.versions.node<"u"}function Al(){function a10(a11){if(a11.charAt(0)===aH)return[e,a11.substring(1)]}function b10(a11){var h10=/^([a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?([\\/])?([\s\S]*?)$/,b11=h10.exec(a11),c10=b11[1]||e,f10=!!(c10&&c10.charAt(1)!==":");if(b11[2]||f10){var d10=b11[1]||e,g10=b11[2]||e;return[d10,a11.substring(d10.length+g10.length)]}}return cF()&&p.process&&p.process.platform&&p.process.platform==="win32"?b10:a10}var go=Al();function lj(a10){return a10.slice(-1)!==aH?a10+aH:a10}if(cF()&&p.process&&p.process.cwd)var cA=p.process.cwd().replace(/\\/g,aH);else var cA="/static";cA=lj(cA);function zX(a10){a10=H(a10),go(a10)||(a10=cA+a10);for(var e10=go(a10),d10=e10[1].split(aH),b10=[],c10=0;c101&&b10.pop();break;case".":break;case"":break;default:b10.push(d10[c10]);break}return b10.unshift(e10[0]),b10.orig=a10,b10}function Ai(a10){for(var g10=e,c10=g10,b10,i10,d10=0,h10=a10.length;d10dF?(c10.substr(0,1),g10+=c10,c10=e,g10+=a10.slice(d10,f10)):c10+=a10.slice(d10,f10),f10==h10)break;d10=f10}b10>6),c10+=String.fromCharCode(ao|b10&bb)):b10<55296||b10>=jC?c10+=String.fromCharCode(kE|b10>>12,ao|b10>>6&bb,ao|b10&bb):b10>=56319||d10+1==h10||(i10=a10.charCodeAt(d10+1))jC?c10+="\xEF\xBF\xBD":(d10++,b10=(b10<<10)+i10-56613888,c10+=String.fromCharCode(jX|b10>>18,ao|b10>>12&bb,ao|b10>>6&bb,ao|b10&bb)),c10.length>ct&&(c10.substr(0,1),g10+=c10,c10=e)}return g10+c10}function as(a10){return gn(a10)?a10:Ai(a10)}var Am=["E2BIG","EACCES","EAGAIN",fw,"EBUSY","ECHILD","EDEADLK","EDOM",kD,"EFAULT","EFBIG","EINTR","EINVAL","EIO","EISDIR","EMFILE","EMLINK","ENAMETOOLONG","ENFILE","ENODEV",fL,"ENOEXEC","ENOLCK","ENOMEM","ENOSPC","ENOSYS",fQ,kf,"ENOTTY","ENXIO","EPERM","EPIPE","ERANGE","EROFS","ESPIPE","ESRCH","EXDEV","EWOULDBLOCK","EINPROGRESS","EALREADY","ENOTSOCK","EDESTADDRREQ","EMSGSIZE","EPROTOTYPE","ENOPROTOOPT","EPROTONOSUPPORT","ESOCKTNOSUPPORT","EOPNOTSUPP","EPFNOSUPPORT","EAFNOSUPPORT","EADDRINUSE","EADDRNOTAVAIL","ENETDOWN","ENETUNREACH","ENETRESET","ECONNABORTED","ECONNRESET","ENOBUFS","EISCONN","ENOTCONN","ESHUTDOWN","ETOOMANYREFS","ETIMEDOUT","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ELOOP","EOVERFLOW"];function a2(a10,b10,c10,d10){var f10=Am.indexOf(a10);f10<0&&(d10==null&&(d10=-9999),f10=[0,d10]);var g10=[f10,as(b10||e),as(c10||e)];return g10}var ld={};function bg(a10){return ld[a10]}function a1(a10,b10){throw g([0,a10].concat(b10))}function f6(a10){return a10 instanceof Uint8Array||(a10=new Uint8Array(a10)),new aY(4,a10,a10.length)}function m(a10){gi(U.Sys_error,a10)}function lg(a10){m(a10+dL)}function gm(a10){return a10.t!=4&&dS(a10),a10.c}function aq(a10){return a10.l}function kQ(){}function Y(a10){this.data=a10}Y.prototype=new kQ,Y.prototype.constructor=Y,Y.prototype.truncate=function(a10){var b10=this.data;this.data=F(a10|0),aZ(b10,0,this.data,0,a10)},Y.prototype.length=function(){return aq(this.data)},Y.prototype.write=function(a10,b10,c10,d10){var e10=this.length();if(a10+d10>=e10){var f10=F(a10+d10),g10=this.data;this.data=f10,aZ(g10,0,this.data,0,e10)}return aZ(f6(b10),c10,this.data,a10,d10),0},Y.prototype.read=function(a10,b10,c10,d10){var e10=this.length();if(a10+d10>=e10&&(d10=e10-a10),d10){var f10=F(d10|0);aZ(this.data,a10,f10,0,d10),b10.set(gm(f10),c10)}return d10};function bw(a10,b10,c10){this.file=b10,this.name=a10,this.flags=c10}bw.prototype.err_closed=function(){m(this.name+jj)},bw.prototype.length=function(){if(this.file)return this.file.length();this.err_closed()},bw.prototype.write=function(a10,b10,c10,d10){if(this.file)return this.file.write(a10,b10,c10,d10);this.err_closed()},bw.prototype.read=function(a10,b10,c10,d10){if(this.file)return this.file.read(a10,b10,c10,d10);this.err_closed()},bw.prototype.close=function(){this.file=void 0};function N(a10,b10){this.content={},this.root=a10,this.lookupFun=b10}N.prototype.nm=function(a10){return this.root+a10},N.prototype.create_dir_if_needed=function(a10){for(var d10=a10.split(aH),c10=e,b10=0;b10>>16,a10=cC(a10,-2048144789),a10^=a10>>>13,a10=cC(a10,-1028477387),a10^=a10>>>16,a10}function zy(a10,b10,c10,d10){var j10,k10,l10,h10,g10,f10,e10,i10,m10;for(h10=b10,(h10<0||h10>cv)&&(h10=cv),g10=a10,f10=c10,j10=[d10],k10=0,l10=1;k100;)if(e10=j10[k10++],e10&&e10.caml_custom){if(cB[e10.caml_custom]&&cB[e10.caml_custom].hash){var n10=cB[e10.caml_custom].hash(e10);f10=V(f10,n10),g10--}}else if(e10 instanceof Array&&e10[0]===(e10[0]|0))switch(e10[0]){case 248:f10=V(f10,e10[2]),g10--;break;case 250:j10[--k10]=e10[1];break;default:if(k9(e10[0]))break;var o10=e10.length-1<<10|e10[0];for(f10=V(f10,o10),i10=1,m10=e10.length;i10=h10);i10++)j10[l10++]=e10[i10];break}else dX(e10)?(f10=zz(f10,e10),g10--):dY(e10)?(f10=zD(f10,e10),g10--):typeof e10=="string"?(f10=f$(f10,e10),g10--):e10===(e10|0)?(f10=V(f10,e10+e10+1),g10--):typeof e10=="number"&&(f10=f_(f10,e10),g10--);return f10=zB(f10),f10&1073741823}function zE(a10,b10,c10){if(!isFinite(a10))return isNaN(a10)?as(fD):as(a10>0?j1:"-infinity");var k10=a10==0&&1/a10==-1/0?1:a10>=0?0:1;k10&&(a10=-a10);var f10=0;if(a10!=0)if(a10<1)for(;a10<1&&f10>-1022;)a10*=2,f10--;else for(;a10>=2;)a10/=2,f10++;var l10=f10<0?e:bV,g10=e;if(k10)g10=bs;else switch(c10){case 43:g10=bV;break;case 32:g10=aE;break;default:break}if(b10>=0&&b10<13){var i10=Math.pow(2,b10*4);a10=Math.round(a10*i10)/i10}var d10=a10.toString(16);if(b10>=0){var j10=d10.indexOf(a$);if(j10<0)d10+=a$+b1(b10,ad);else{var h10=j10+1+b10;d10.length>24&aV,a10>>31&aI)}function zP(a10){return a10.toInt()}function zL(a10){return+a10.isNeg()}function zO(a10){return a10.neg()}function zJ(a10,b10){var c10=gh(a10);c10.signedconv&&zL(b10)&&(c10.sign=-1,b10=zO(b10));var d10=e,i10=dW(c10.base),h10="0123456789abcdef";do{var g10=b10.udivmod(i10);b10=g10.quotient,d10=h10.charAt(zP(g10.modulus))+d10}while(!zM(b10));if(c10.prec>=0){c10.filler=aE;var f10=c10.prec-d10.length;f10>0&&(d10=b1(f10,ad)+d10)}return f8(c10,d10)}function k5(a10,b10){return a10.or(b10)}function k6(a10,b10){return a10.shift_left(b10)}function gf(a10,b10){return a10.shift_right_unsigned(b10)}function z$(a10){var b10=0,e10=n(a10),c10=10,d10=1;if(e10>0)switch(_(a10,b10)){case 45:b10++,d10=-1;break;case 43:b10++,d10=1;break}if(b10+1=48&&a10<=57?a10-48:a10>=65&&a10<=90?a10-55:a10>=97&&a10<=122?a10-87:-1}function k8(a10){var h10=z$(a10),d10=h10[0],i10=h10[1],e10=h10[2],g10=n(a10),j10=-1>>>0,f10=d10=e10)&&aj(dO);var b10=c10;for(d10++;d10=e10)break;b10=e10*b10+c10,b10>j10&&aj(dO)}return d10!=g10&&aj(dO),b10=i10*b10,e10==10&&(b10|0)!=b10&&aj(dO),b10|0}function k_(a10){return a10.slice(1)}function dZ(a10,b10,c10){return a10[H(b10)].apply(a10,k_(c10))}function zS(a10,b10){switch(b10.length){case 1:return new a10;case 2:return new a10(b10[1]);case 3:return new a10(b10[1],b10[2]);case 4:return new a10(b10[1],b10[2],b10[3]);case 5:return new a10(b10[1],b10[2],b10[3],b10[4]);case 6:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5]);case 7:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5],b10[6]);case 8:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5],b10[6],b10[7])}function c10(){return a10.apply(this,k_(b10))}return c10.prototype=a10.prototype,new c10}function k$(a10){for(var c10={},b10=1;b10>>32-e10,c10)}function g10(a10,b10,c10,d10,e10,f10,g11){return l10(b10&c10|~b10&d10,a10,b10,e10,f10,g11)}function h10(a10,b10,c10,d10,e10,f10,g11){return l10(b10&d10|c10&~d10,a10,b10,e10,f10,g11)}function i10(a10,b10,c10,d10,e10,f10,g11){return l10(b10^c10^d10,a10,b10,e10,f10,g11)}function j10(a10,b10,c10,d10,e10,f10,g11){return l10(c10^(b10|~d10),a10,b10,e10,f10,g11)}return function(a10,b10){var c10=a10[0],d10=a10[1],e10=a10[2],f10=a10[3];c10=g10(c10,d10,e10,f10,b10[0],7,3614090360),f10=g10(f10,c10,d10,e10,b10[1],12,3905402710),e10=g10(e10,f10,c10,d10,b10[2],17,606105819),d10=g10(d10,e10,f10,c10,b10[3],22,3250441966),c10=g10(c10,d10,e10,f10,b10[4],7,4118548399),f10=g10(f10,c10,d10,e10,b10[5],12,1200080426),e10=g10(e10,f10,c10,d10,b10[6],17,2821735955),d10=g10(d10,e10,f10,c10,b10[7],22,4249261313),c10=g10(c10,d10,e10,f10,b10[8],7,1770035416),f10=g10(f10,c10,d10,e10,b10[9],12,2336552879),e10=g10(e10,f10,c10,d10,b10[10],17,4294925233),d10=g10(d10,e10,f10,c10,b10[11],22,2304563134),c10=g10(c10,d10,e10,f10,b10[12],7,1804603682),f10=g10(f10,c10,d10,e10,b10[13],12,4254626195),e10=g10(e10,f10,c10,d10,b10[14],17,2792965006),d10=g10(d10,e10,f10,c10,b10[15],22,1236535329),c10=h10(c10,d10,e10,f10,b10[1],5,4129170786),f10=h10(f10,c10,d10,e10,b10[6],9,3225465664),e10=h10(e10,f10,c10,d10,b10[11],14,643717713),d10=h10(d10,e10,f10,c10,b10[0],20,3921069994),c10=h10(c10,d10,e10,f10,b10[5],5,3593408605),f10=h10(f10,c10,d10,e10,b10[10],9,38016083),e10=h10(e10,f10,c10,d10,b10[15],14,3634488961),d10=h10(d10,e10,f10,c10,b10[4],20,3889429448),c10=h10(c10,d10,e10,f10,b10[9],5,568446438),f10=h10(f10,c10,d10,e10,b10[14],9,3275163606),e10=h10(e10,f10,c10,d10,b10[3],14,4107603335),d10=h10(d10,e10,f10,c10,b10[8],20,1163531501),c10=h10(c10,d10,e10,f10,b10[13],5,2850285829),f10=h10(f10,c10,d10,e10,b10[2],9,4243563512),e10=h10(e10,f10,c10,d10,b10[7],14,1735328473),d10=h10(d10,e10,f10,c10,b10[12],20,2368359562),c10=i10(c10,d10,e10,f10,b10[5],4,4294588738),f10=i10(f10,c10,d10,e10,b10[8],11,2272392833),e10=i10(e10,f10,c10,d10,b10[11],16,1839030562),d10=i10(d10,e10,f10,c10,b10[14],23,4259657740),c10=i10(c10,d10,e10,f10,b10[1],4,2763975236),f10=i10(f10,c10,d10,e10,b10[4],11,1272893353),e10=i10(e10,f10,c10,d10,b10[7],16,4139469664),d10=i10(d10,e10,f10,c10,b10[10],23,3200236656),c10=i10(c10,d10,e10,f10,b10[13],4,681279174),f10=i10(f10,c10,d10,e10,b10[0],11,3936430074),e10=i10(e10,f10,c10,d10,b10[3],16,3572445317),d10=i10(d10,e10,f10,c10,b10[6],23,76029189),c10=i10(c10,d10,e10,f10,b10[9],4,3654602809),f10=i10(f10,c10,d10,e10,b10[12],11,3873151461),e10=i10(e10,f10,c10,d10,b10[15],16,530742520),d10=i10(d10,e10,f10,c10,b10[2],23,3299628645),c10=j10(c10,d10,e10,f10,b10[0],6,4096336452),f10=j10(f10,c10,d10,e10,b10[7],10,1126891415),e10=j10(e10,f10,c10,d10,b10[14],15,2878612391),d10=j10(d10,e10,f10,c10,b10[5],21,4237533241),c10=j10(c10,d10,e10,f10,b10[12],6,1700485571),f10=j10(f10,c10,d10,e10,b10[3],10,2399980690),e10=j10(e10,f10,c10,d10,b10[10],15,4293915773),d10=j10(d10,e10,f10,c10,b10[1],21,2240044497),c10=j10(c10,d10,e10,f10,b10[8],6,1873313359),f10=j10(f10,c10,d10,e10,b10[15],10,4264355552),e10=j10(e10,f10,c10,d10,b10[6],15,2734768916),d10=j10(d10,e10,f10,c10,b10[13],21,1309151649),c10=j10(c10,d10,e10,f10,b10[4],6,4149444226),f10=j10(f10,c10,d10,e10,b10[11],10,3174756917),e10=j10(e10,f10,c10,d10,b10[2],15,718787259),d10=j10(d10,e10,f10,c10,b10[9],21,3951481745),a10[0]=k10(c10,a10[0]),a10[1]=k10(d10,a10[1]),a10[2]=k10(e10,a10[2]),a10[3]=k10(f10,a10[3])}}();function zg(a10,b10,c10){var e10=a10.len&bb,d10=0;if(a10.len+=c10,e10){var f10=64-e10;if(c10=64;)a10.b8.set(b10.subarray(d10,d10+64),0),dP(a10.w,a10.b32),c10-=64,d10+=64;c10&&a10.b8.set(b10.subarray(d10,d10+c10),0)}function ze(a10){var c10=a10.len&bb;if(a10.b8[c10]=ao,c10++,c10>56){for(var b10=c10;b10<64;b10++)a10.b8[b10]=0;dP(a10.w,a10.b32);for(var b10=0;b10<56;b10++)a10.b8[b10]=0}else for(var b10=c10;b10<56;b10++)a10.b8[b10]=0;a10.b32[14]=a10.len<<3,a10.b32[15]=a10.len>>29&536870911,dP(a10.w,a10.b32);for(var e10=new Uint8Array(16),d10=0;d10<4;d10++)for(var b10=0;b10<4;b10++)e10[d10*4+b10]=a10.w[d10]>>8*b10&255;return e10}function Ae(a10){return cE(a10,0,a10.length)}function zY(a10,b10,c10){var d10=zf(),e10=gm(a10);return zg(d10,e10.subarray(b10,b10+c10),c10),Ae(ze(d10))}function zZ(a10,b10,c10){return zY(bd(a10),b10,c10)}function z1(){return 0}var bf=new Array;function la(a10){return bf[a10]}function bz(a10){var b10=la(a10);return b10.opened||m("Cannot flush a closed channel"),!b10.buffer||b10.buffer_curr==0||(b10.output?b10.output(cE(b10.buffer,0,b10.buffer_curr)):b10.file.write(b10.offset,b10.buffer,0,b10.buffer_curr),b10.offset+=b10.buffer_curr,b10.buffer_curr=0),0}function Ag(a10,b10){if(b10.name)try{var d10=__require(fE),c10=d10.openSync(b10.name,"rs");return new av(c10,b10)}catch{}return new av(a10,b10)}var d2=new Array(3);function cw(a10,b10){Y.call(this,F(0)),this.log=function(a11){return 0},a10==1&&typeof console.log=="function"?this.log=console.log:a10==2&&typeof console.error=="function"?this.log=console.error:typeof console.log=="function"&&(this.log=console.log),this.flags=b10}cw.prototype.length=function(){return 0},cw.prototype.write=function(a10,b10,c10,d10){if(this.log){d10>0&&c10>=0&&c10+d10<=b10.length&&b10[c10+d10-1]==10&&d10--;var e10=F(d10);return aZ(f6(b10),c10,e10,0,d10),this.log(e10.toUtf16()),0}m(this.fd+jj)},cw.prototype.read=function(a10,b10,c10,d10){m(this.fd+": file descriptor is write only")},cw.prototype.close=function(){this.log=void 0};function d3(a10,b10){return b10==null&&(b10=d2.length),d2[b10]=a10,b10|0}function Ao(a10,b10,c10){for(var d10={};b10;){switch(b10[1]){case 0:d10.rdonly=1;break;case 1:d10.wronly=1;break;case 2:d10.append=1;break;case 3:d10.create=1;break;case 4:d10.truncate=1;break;case 5:d10.excl=1;break;case 6:d10.binary=1;break;case 7:d10.text=1;break;case 8:d10.nonblock=1;break}b10=b10[2]}d10.rdonly&&d10.wronly&&m(a10+f2),d10.text&&d10.binary&&m(a10+fB);var e10=lo(a10),f10=e10.device.open(e10.rest,d10);return d3(f10,void 0)}(function(){function a10(a11,b10){return cF()?Ag(a11,b10):new cw(a11,b10)}d3(a10(0,{rdonly:1,altname:"/dev/stdin",isCharacterDevice:!0}),0),d3(a10(1,{buffered:2,wronly:1,isCharacterDevice:!0}),1),d3(a10(2,{buffered:2,wronly:1,isCharacterDevice:!0}),2)})();function z2(a10){var b10=d2[a10];b10.flags.wronly&&m(j0+a10+" is writeonly");var d10=null,c10={file:b10,offset:b10.flags.append?b10.length():0,fd:a10,opened:!0,out:!1,buffer_curr:0,buffer_max:0,buffer:new Uint8Array(j2),refill:d10};return bf[c10.fd]=c10,c10.fd}function lb(a10){var b10=d2[a10];b10.flags.rdonly&&m(j0+a10+" is readonly");var d10=b10.flags.buffered!==void 0?b10.flags.buffered:1,c10={file:b10,offset:b10.flags.append?b10.length():0,fd:a10,opened:!0,out:!0,buffer_curr:0,buffer:new Uint8Array(j2),buffered:d10};return bf[c10.fd]=c10,c10.fd}function z3(){for(var b10=0,a10=0;a10e10.buffer.length){var g10=new Uint8Array(e10.buffer_curr+b10.length);g10.set(e10.buffer),e10.buffer=g10}switch(e10.buffered){case 0:e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,bz(a10);break;case 1:e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,e10.buffer_curr>=e10.buffer.length&&bz(a10);break;case 2:var f10=b10.lastIndexOf(10);f10<0?(e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,e10.buffer_curr>=e10.buffer.length&&bz(a10)):(e10.buffer.set(b10.subarray(0,f10+1),e10.buffer_curr),e10.buffer_curr+=f10+1,bz(a10),e10.buffer.set(b10.subarray(f10+1),e10.buffer_curr),e10.buffer_curr+=b10.length-f10-1);break}return 0}function z4(a10,b10,c10,d10){var b10=gm(b10);return z5(a10,b10,c10,d10)}function gg(a10,b10,c10,d10){return z4(a10,bd(b10),c10,d10)}function lc(a10,b10){var c10=String.fromCharCode(b10);return gg(a10,c10,0,1),0}function z6(a10,b10){return b10==0&&gj(),a10%b10}function cD(a10,b10){return+(dR(a10,b10,!1)!=0)}function z8(a10,b10){var d10=new Array(b10+1);d10[0]=a10;for(var c10=1;c10<=b10;c10++)d10[c10]=0;return d10}function z9(a10,b10){return a10[0]=aD,a10[1]=b10,0}function aw(a10){return a10 instanceof Array&&a10[0]==a10[0]>>>0?a10[0]:dX(a10)||dY(a10)?dC:a10 instanceof Function||typeof a10=="function"?247:a10&&a10.caml_custom?jP:cu}function zl(a10){var c10={};if(a10)for(var b10=1;b10=0?a10=e10:aj("caml_register_global: cannot locate "+d10)}}U[a10+1]=b10,c10&&(U[c10]=b10)}function gl(a10,b10){return ld[a10]=b10,0}function Ad(){G(fz)}function y(a10,b10){return b10>>>0>=n(a10)&&Ad(),_(a10,b10)}function d1(a10){return a10.t&6&&cz(a10),a10.c}function Af(){return 2147483647/4|0}function Aa(){lf(U.Not_found)}function li(a10){var b10=ln(H(a10));return b10===void 0&&Aa(),as(b10)}function Ah(){if(p.crypto){if(p.crypto.getRandomValues){var a10=p.crypto.getRandomValues(new Int32Array(4));return[0,a10[0],a10[1],a10[2],a10[3]]}else if(p.crypto.randomBytes){var a10=new Int32Array(p.crypto.randomBytes(16).buffer);return[0,a10[0],a10[1],a10[2],a10[3]]}}var b10=new Date().getTime(),c10=b10^4294967295*Math.random();return[0,c10]}function bA(a10){for(var b10=1;a10&&a10.joo_tramp;)a10=a10.joo_tramp.apply(null,a10.joo_args),b10++;return a10}function r(a10,b10){return{joo_tramp:a10,joo_args:b10}}function lk(a10,b10){if(b10.fun)return a10.fun=b10.fun,0;if(typeof b10=="function")return a10.fun=b10,0;for(var c10=b10.length;c10--;)a10[c10]=b10[c10];return 0}function L(a10){{if(a10 instanceof Array)return a10;var b10;return p.RangeError&&a10 instanceof p.RangeError&&a10.message&&a10.message.match(/maximum call stack/i)||p.InternalError&&a10 instanceof p.InternalError&&a10.message&&a10.message.match(/too much recursion/i)?b10=U.Stack_overflow:a10 instanceof p.Error&&bg(fS)?b10=[0,bg(fS),a10]:b10=[0,U.Failure,as(String(a10))],a10 instanceof p.Error&&(b10.js_error=a10),b10}}function zR(a10){switch(a10[2]){case-8:case-11:case-12:return 1;default:return 0}}function zv(a10){var b10=e;if(a10[0]==0){if(b10+=a10[1][1],a10.length==3&&a10[2][0]==0&&zR(a10[1]))var f10=a10[2],g10=1;else var g10=2,f10=a10;b10+="(";for(var d10=g10;d10g10&&(b10+=ju);var c10=f10[d10];typeof c10=="number"?b10+=c10.toString():c10 instanceof aY||typeof c10=="string"?b10+=dB+c10.toString()+dB:b10+=kr}b10+=")"}else a10[0]==q&&(b10+=a10[1]);return b10}function k1(a10){if(a10 instanceof Array&&(a10[0]==0||a10[0]==q)){var c10=bg(kv);if(c10)dQ(c10,[a10,!1]);else{var d10=zv(a10),b10=bg(j3);if(b10&&dQ(b10,[0]),console.error(fV+d10),a10.js_error)throw a10.js_error}}else throw a10}function Ac(){var c10=p.process;c10&&c10.on?c10.on("uncaughtException",function(a10,b10){k1(a10),c10.exit(2)}):p.addEventListener&&p.addEventListener(jn,function(a10){a10.error&&k1(a10.error)})}Ac();function h(a10,b10){return(a10.l>=0?a10.l:a10.l=a10.length)==1?a10(b10):be(a10,[b10])}function i(a10,b10,c10){return(a10.l>=0?a10.l:a10.l=a10.length)==2?a10(b10,c10):be(a10,[b10,c10])}function x(a10,b10,c10,d10){return(a10.l>=0?a10.l:a10.l=a10.length)==3?a10(b10,c10,d10):be(a10,[b10,c10,d10])}function fu(a10,b10,c10,d10,e10,f10){return(a10.l>=0?a10.l:a10.l=a10.length)==5?a10(b10,c10,d10,e10,f10):be(a10,[b10,c10,d10,e10,f10])}function zd(a10,b10,c10,d10,e10,f10,g10,h10){return(a10.l>=0?a10.l:a10.l=a10.length)==7?a10(b10,c10,d10,e10,f10,g10,h10):be(a10,[b10,c10,d10,e10,f10,g10,h10])}var An=void 0;zw();var d6=[q,kM,-1],gr=[q,jW,-2],b3=[q,f3,-3],cH=[q,jx,-4],ax=[q,jA,-7],gp=[q,kI,-8],gq=[q,ke,-9],f=[q,kn,-11],b4=[q,kA,-12],zc=[4,0,0,0,[12,45,[4,0,0,0,0]]],eq2=[0,[11,'File "',[2,0,[11,'", line ',[4,0,0,0,[11,kK,[4,0,0,0,[12,45,[4,0,0,0,[11,kG,[2,0,0]]]]]]]]]],'File "%s", line %d, characters %d-%d: %s'],i1=f1,br="content",i7="columns",i8="rows",fo=jN,fp=f1,i9=cq,i_="page_content";ar(11,b4,kA),ar(10,f,kn),ar(9,[q,ks,-10],ks),ar(8,gq,ke),ar(7,gp,kI),ar(6,ax,jA),ar(5,[q,jS,-6],jS),ar(4,[q,j6,-5],j6),ar(3,cH,jx),ar(2,b3,f3),ar(1,gr,jW),ar(0,d6,kM);var ly="output_substring",lu=a$,lr="true",ls="false",lC="CamlinternalLazy.Undefined",lG="option is None",lK="\\\\",lL="\\'",lM="\\b",lN="\\t",lO="\\n",lP="\\r",lX="List.init",lU="hd",l9="String.blit / Bytes.blit_string",l8="Bytes.blit",l7="String.sub / Bytes.sub",mg="String.contains_from / Bytes.contains_from",mn="Array.blit",mm="Array.sub",mk="Array.init",mu=[0,"set.ml",570,18],mq=dI,mr=dI,ms=dI,mt=dI,mB="Map.remove_min_elt",mx=dM,my=dM,mz=dM,mA=dM,mC="Stdlib.Stack.Empty",mG="Stdlib.Queue.Empty",mS="Buffer.add_substring/add_subbytes",mP="Buffer.add: cannot grow buffer",mO=[0,je,93,2],mN=[0,je,94,2],mL="Buffer.sub",m3="%c",m4="%s",m5=jE,m6=js,m7=kO,m8=jy,m9="%f",m_="%B",m$="%{",na="%}",nb="%(",nc="%)",nd="%a",ne="%t",nf="%?",ng="%r",nh="%_r",ni=[0,K,850,23],nt=[0,K,814,21],nl=[0,K,815,21],nu=[0,K,818,21],nm=[0,K,819,21],nv=[0,K,822,19],nn=[0,K,823,19],nw=[0,K,826,22],no=[0,K,827,22],nx=[0,K,831,30],np=[0,K,832,30],nr=[0,K,836,26],nj=[0,K,837,26],ns=[0,K,846,28],nk=[0,K,847,28],nq=[0,K,851,23],oJ=[0,K,1558,4],oK="Printf: bad conversion %[",oL=[0,K,1626,39],oM=[0,K,1649,31],oN=[0,K,1650,31],oO="Printf: bad conversion %_",oP=jR,oQ=kq,oR=jR,oS=kq,oW=[0,[11,"invalid box description ",[3,0,0]],"invalid box description %S"],oV=[0,0,4],oE=fD,oC="neg_infinity",oD=j1,oB=a$,ow=[0,jg],ok="%+nd",ol="% nd",on="%+ni",oo="% ni",op="%nx",oq="%#nx",or="%nX",os="%#nX",ot="%no",ou="%#no",oj="%nd",om=kO,ov="%nu",n8="%+ld",n9="% ld",n$="%+li",oa="% li",ob="%lx",oc="%#lx",od="%lX",oe="%#lX",of="%lo",og="%#lo",n7="%ld",n_=js,oh="%lu",nU="%+Ld",nV="% Ld",nX="%+Li",nY="% Li",nZ="%Lx",n0="%#Lx",n1="%LX",n2="%#LX",n3="%Lo",n4="%#Lo",nT="%Ld",nW=jy,n5="%Lu",nG="%+d",nH="% d",nJ="%+i",nK="% i",nL="%x",nM="%#x",nN="%X",nO="%#X",nP="%o",nQ="%#o",nF=fx,nI=jE,nR=j9,mV="@]",mW="@}",mX="@?",mY=`@ -`,mZ="@.",m0="@@",m1="@%",m2="@",ny="CamlinternalFormat.Type_mismatch",o1=e,o2=[0,[11,ju,[2,0,[2,0,0]]],", %s%s"],py=[0,[11,fV,[2,0,[12,10,0]]],kb],pz=[0,[11,"Fatal error in uncaught exception handler: exception ",[2,0,[12,10,0]]],`Fatal error in uncaught exception handler: exception %s -`],px="Fatal error: out of memory in uncaught exception handler",pu=[0,[11,fV,[2,0,[12,10,0]]],kb],po=[0,[2,0,[12,10,0]],`%s -`],pp=[0,[11,jQ,0],jQ],pf="Raised at",pg="Re-raised at",ph="Raised by primitive operation at",pi="Called from",pj=" (inlined)",pl=e,pk=[0,[2,0,[12,32,[2,0,[11,' in file "',[2,0,[12,34,[2,0,[11,", line ",[4,0,0,0,[11,kK,zc]]]]]]]]]],'%s %s in file "%s"%s, line %d, characters %d-%d'],pm=[0,[2,0,[11," unknown location",0]],"%s unknown location"],o_="Out of memory",o$="Stack overflow",pa="Pattern matching failed",pb="Assertion failed",pc="Undefined recursive module",o4=[0,[12,40,[2,0,[2,0,[12,41,0]]]],"(%s%s)"],o5=e,o6=e,o7=[0,[12,40,[2,0,[12,41,0]]],"(%s)"],o0=[0,[4,0,0,0,0],fx],oY=[0,[3,0,0],"%S"],oZ=kr,pr=[0,e,`(Cannot print locations: +`;)ins=ins.slice(0,-1);return delta[delta.length-1]={insert:ins},ins.length===0&&delta.pop(),delta}}return delta},updateCursor=(quillCursors,aw,clientId,doc2,type)=>{try{if(aw&&aw.cursor&&clientId!==doc2.clientID){let user=aw.user||{},color=user.color||"#ffa500",name=user.name||`User: ${clientId}`;quillCursors.createCursor(clientId.toString(),name,color);let anchor=createAbsolutePositionFromRelativePosition(createRelativePositionFromJSON(aw.cursor.anchor),doc2),head=createAbsolutePositionFromRelativePosition(createRelativePositionFromJSON(aw.cursor.head),doc2);anchor&&head&&anchor.type===type&&quillCursors.moveCursor(clientId.toString(),{index:anchor.index,length:head.index-anchor.index})}else quillCursors.removeCursor(clientId.toString())}catch(err){console.error(err)}},QuillBinding=class{constructor(type,quill,awareness){let doc2=type.doc;this.type=type,this.doc=doc2,this.quill=quill;let quillCursors=quill.getModule("cursors")||null;this.quillCursors=quillCursors,this._negatedUsedFormats={},this.awareness=awareness,this._awarenessChange=({added,removed,updated})=>{let states=awareness.getStates();added.forEach(id2=>{updateCursor(quillCursors,states.get(id2),id2,doc2,type)}),updated.forEach(id2=>{updateCursor(quillCursors,states.get(id2),id2,doc2,type)}),removed.forEach(id2=>{quillCursors.removeCursor(id2.toString())})},this._typeObserver=event=>{if(event.transaction.origin!==this){let eventDelta=event.delta,delta=[];for(let i=0;i{if(delta&&delta.ops){let ops=delta.ops;ops.forEach(op=>{if(op.attributes!==void 0)for(let key in op.attributes)this._negatedUsedFormats[key]===void 0&&(this._negatedUsedFormats[key]=!1)}),origin!==this&&doc2.transact(()=>{type.applyDelta(ops)},this)}if(awareness&&quillCursors){let sel=quill.getSelection(),aw=awareness.getLocalState();if(sel===null)awareness.getLocalState()!==null&&awareness.setLocalStateField("cursor",null);else{let anchor=createRelativePositionFromTypeIndex(type,sel.index),head=createRelativePositionFromTypeIndex(type,sel.index+sel.length);(!aw||!aw.cursor||!compareRelativePositions(anchor,aw.cursor.anchor)||!compareRelativePositions(head,aw.cursor.head))&&awareness.setLocalStateField("cursor",{anchor,head})}awareness.getStates().forEach((aw2,clientId)=>{updateCursor(quillCursors,aw2,clientId,doc2,type)})}},quill.on("editor-change",this._quillObserver),quill.setContents(type.toDelta(),this),quillCursors!==null&&awareness&&(awareness.getStates().forEach((aw,clientId)=>{updateCursor(quillCursors,aw,clientId,doc2,type)}),awareness.on("change",this._awarenessChange))}destroy(){this.type.unobserve(this._typeObserver),this.quill.off("editor-change",this._quillObserver),this.awareness&&this.awareness.off("change",this._awarenessChange)}}}});(function(a){typeof globalThis!="object"&&(this?b():(a.defineProperty(a.prototype,"_T_",{configurable:!0,get:b}),_T_));function b(){var b2=this||self;b2.globalThis=b2,delete a.prototype._T_}})(Object);(function(a){window.yjs=(init_yjs(),__toCommonJS(yjs_exports)),window.WebrtcProvider=(init_y_webrtc(),__toCommonJS(y_webrtc_exports)).WebrtcProvider,window.IndexeddbPersistence=(init_y_indexeddb(),__toCommonJS(y_indexeddb_exports)).IndexeddbPersistence})(globalThis);(function(a){require_quill_core(),require_quill_bubble(),require_quill_snow(),window.Quill=(init_quill2(),__toCommonJS(quill_exports)).default,window.QuillCursors=require_quill_cursors()})(globalThis);(function(a){window.QuillBinding=(init_y_quill(),__toCommonJS(y_quill_exports)).QuillBinding})(globalThis);(function(p){"use strict";var v=3850876,aE=" ",ad="0",f1="compare: functional value",f0="mkdir",cu=1e3,jI="delete",X="vendor/lwd/lib/lwd/lwd_seq.pp.ml",kt="@[",ks="window",kS="console",dO="int_of_string",fH="fs",ka="%u",kr="/static/",jH="%i",kR="%ni",aX=255,fZ=749039939,kq="Assert_failure",aG=737455525,j$="camlinternalMod.ml",jG="0x",j_=32752,kQ=218,jF=57343,j9="End_of_file",kp="OCAMLRUNPARAM",jE=": closedir failed",ko=253,kP="Out_of_memory",jD="Not_found",f6="Failure",dN="Unix.Unix_error",jC="style",j8="^",bW="text",kO="length",fT="ENOTDIR",kn="Lwd_seq.rank: node is marked",bv=936573133,jB="%Li",jz="flex",jA="Invalid_argument",dG=254,bV="+",dI="Set.bal",kN=", characters ",aV=16777215,j7=858694086,km=120,kl=1027,ct=1024,dM="Map.bal",ba=246,j6="Pervasives.do_at_exit",kk=389604418,j5=65536,jy="submit",c="vendor/brr_lwd_ui/examples/yjs/main.ml",fS=15,T=16620,jx=", ",dF=512,fR=-588596599,kL="Match_failure",kM="closedir",jv="%li",jw=1026,kK=-32,ju=157,jt="b",fG="nan",e="",fF="rmdir",fY="Fatal error: exception ",j4="infinity",K="camlinternalFormat.ml",j3="fd ",kI="append",kJ=": ",js=174,q=248,j2="em",j1="data",kH=224,kj=24029,j0=240,jZ="Sys_error",ao=128,fQ="vendor/brr_lwd_ui/bindings/yjs/doc.ml",ki="ENOTEMPTY",kG="EEXIST",fX=1255,jY=1073741823,dE="value",fE=" : flags Open_text and Open_binary are not compatible",kF="px",fP="e",kE=459,fD=": Not a directory",fO="ENOENT",kh="Stack_overflow",fN=-605101559,S=15681,jX="Array",kD="Undefined_recursive_module",kC=2147483647,aF=32768,cs="string",dH="table",jW=2048,kg=-48,jq="error",jr=" : is a directory",jU="@{",jV="Division_by_zero",jp="classList",a$=".",jT=`(Program not linked with -g, cannot print stack backtrace) +`,cq="name",bb=63,kB=492,a_=737456202,fM=" : file already exists",bu=128,dL=": No such file or directory",jR="vendor/lwd/lib/brr-lwd/elwd.ml",jS=255,dD="lwd-to-remove",cv=256,jo="checked",cr=-976970511,fL=100,jQ="id",fC="index out of bounds",kf=-937474657,aH="/",fB=504440814,dC=252,kA="height: ",jn="lwdui-virtual-table-row",fA="%d",kz=383,jl="bold",jm=": file descriptor already closed",bs="-",fz="EBADF",jP="changes",aW=951901561,jO=102,fK=-97,ky="Printexc.handle_uncaught_exception",jk=12520,f5=" : flags Open_rdonly and Open_wronly are not compatible",a="vendor/lwd/lib/lwd/lwd_table.ml",fW=756711075,ke=`Fatal error: exception %s +`,fJ=4100401,kx="class",jj="\xE2\x9D\x8C",aD=250,jN=199,dK="bool",f3=82908052,f4="kind",bt=611392745,fI="cell",kw=">",jM="([^/]+)",kd="input",fV="jsError",ji=103,dB='"',aI=65535,f2=127,fU=737308346,jh=56320,jL="documentElement",kv="Sys_blocked_io",b="vendor/lwd/lib/lwd/lwd.ml",kc="not implemented",jg="buffer.ml",jK="Form submitted:",ku="_",fy="target",jJ=-101336657,kb="rem",dJ="_bigarr02";function zq(a10,b10,c10,d10,e10){if(d10<=b10)for(var f10=1;f10<=e10;f10++)c10[d10+f10]=a10[b10+f10];else for(var f10=e10;f10>=1;f10--)c10[d10+f10]=a10[b10+f10];return 0}function zr(a10,b10,c10){var d10=new Array(c10+1);d10[0]=0;for(var e10=1,f10=b10+1;e10<=c10;e10++,f10++)d10[e10]=a10[f10];return d10}function cE(a10,b10,c10){var d10=String.fromCharCode;if(b10==0&&c10<=4096&&c10==a10.length)return d10.apply(null,a10);for(var f10=e;0=c10.l||c10.t==2&&e10>=c10.c.length))c10.c=a10.t==4?cE(a10.c,b10,e10):b10==0&&a10.c.length==e10?a10.c:a10.c.substr(b10,e10),c10.t=c10.c.length==c10.l?0:2;else if(c10.t==2&&d10==c10.c.length)c10.c+=a10.t==4?cE(a10.c,b10,e10):b10==0&&a10.c.length==e10?a10.c:a10.c.substr(b10,e10),c10.t=c10.c.length==c10.l?0:2;else{c10.t!=4&&dS(c10);var g10=a10.c,h10=c10.c;if(a10.t==4)if(d10<=b10)for(var f10=0;f10=0;f10--)h10[d10+f10]=g10[b10+f10];else{for(var i10=Math.min(e10,g10.length-b10),f10=0;f10>=1,a10==0)return d10;b10+=b10,c10++,c10==9&&b10.slice(0,1)}}function cz(a10){a10.t==2?a10.c+=b1(a10.l-a10.c.length,"\0"):a10.c=cE(a10.c,0,a10.c.length),a10.t=0}function gq(a10){if(a10.length<24){for(var b10=0;b10f2)return!1;return!0}else return!/[^\x00-\x7f]/.test(a10)}function lo(a10){for(var k10=e,d10=e,h10,g10,i10,b10,c10=0,j10=a10.length;c10dF?(d10.substr(0,1),k10+=d10,d10=e,k10+=a10.slice(c10,f10)):d10+=a10.slice(c10,f10),f10==j10)break;c10=f10}b10=1,++c10=55295&&b10<57344)&&(b10=2)):(b10=3,++c101114111)&&(b10=3)))))),b10<4?(c10-=b10,d10+="\uFFFD"):b10>aI?d10+=String.fromCharCode(55232+(b10>>10),jh+(b10&1023)):d10+=String.fromCharCode(b10),d10.length>ct&&(d10.substr(0,1),k10+=d10,d10=e)}return k10+d10}function aY(a10,b10,c10){this.t=a10,this.c=b10,this.l=c10}aY.prototype.toString=function(){switch(this.t){case 9:return this.c;default:cz(this);case 0:if(gq(this.c))return this.t=9,this.c;this.t=8;case 8:return this.c}},aY.prototype.toUtf16=function(){var a10=this.toString();return this.t==9?a10:lo(a10)},aY.prototype.slice=function(){var a10=this.t==4?this.c.slice():this.c;return new aY(this.t,a10,this.l)};function k0(a10){return new aY(0,a10,a10.length)}function aJ(a10){return a10}function bd(a10){return k0(a10)}function cy(a10,b10,c10,d10,e10){return aZ(bd(a10),b10,c10,d10,e10),0}function lq(a10){var b10=p.process;if(b10&&b10.env&&b10.env[a10]!=null)return b10.env[a10];if(p.jsoo_static_env&&p.jsoo_static_env[a10])return p.jsoo_static_env[a10]}var gn=0;(function(){var c10=lq(kp);if(c10!==void 0)for(var b10=c10.split(","),a10=0;a10=a10.c.length)return 0;case 0:return a10.c.charCodeAt(b10);case 4:return a10.c[b10]}}function zw(a10,b10){return b10>>>0>=a10.l&&f8(),bY(a10,b10)}function B(a10,b10,c10){if(c10&=aX,a10.t!=4){if(b10==a10.c.length)return a10.c+=String.fromCharCode(c10),b10+1==a10.l&&(a10.t=0),0;dS(a10)}return a10.c[b10]=c10,0}function a0(a10,b10,c10){return b10>>>0>=a10.l&&f8(),B(a10,b10,c10)}function bx(a10){return a10.toArray()}function zx(a10,b10,c10){b10>>>0>=a10.l-7&&f8();for(var e10=bx(c10),d10=0;d10<8;d10++)B(a10,b10+7-d10,e10[d10]);return 0}function be(d10,c10){var f10=d10.l>=0?d10.l:d10.l=d10.length,e10=c10.length,b10=f10-e10;if(b10==0)return d10.apply(null,c10);if(b10<0){var a10=d10.apply(null,c10.slice(0,f10));return typeof a10!="function"?a10:be(a10,c10.slice(f10))}else{switch(b10){case 1:{var a10=function(a11){for(var f11=new Array(e10+1),b11=0;b11>>0>=a10.length-1&&cx(),a10}function zy(a10){return isFinite(a10)?Math.abs(a10)>=22250738585072014e-324?0:a10!=0?1:2:isNaN(a10)?4:3}function la(a10){return 0}var At=Math.log2&&Math.log2(11235582092889474e291)==1020;function As(a10){if(At)return Math.floor(Math.log2(a10));var b10=0;if(a10==0)return-1/0;if(a10>=1)for(;a10>=2;)a10/=2,b10++;else for(;a10<1;)a10*=2,b10--;return b10}function gd(a10){var b10=new Float32Array(1);b10[0]=a10;var c10=new Int32Array(b10.buffer);return c10[0]|0}var k7=Math.pow(2,-24);function li(a10){throw a10}function gm(){li(U.Division_by_zero)}function d(a10,b10,c10){this.lo=a10&aV,this.mi=b10&aV,this.hi=c10&aI}d.prototype.caml_custom="_j",d.prototype.copy=function(){return new d(this.lo,this.mi,this.hi)},d.prototype.ucompare=function(a10){return this.hi>a10.hi?1:this.hia10.mi?1:this.mia10.lo?1:this.loc10?1:b10a10.mi?1:this.mia10.lo?1:this.lo>24),c10=-this.hi+(b10>>24);return new d(a10,b10,c10)},d.prototype.add=function(a10){var b10=this.lo+a10.lo,c10=this.mi+a10.mi+(b10>>24),e10=this.hi+a10.hi+(c10>>24);return new d(b10,c10,e10)},d.prototype.sub=function(a10){var b10=this.lo-a10.lo,c10=this.mi-a10.mi+(b10>>24),e10=this.hi-a10.hi+(c10>>24);return new d(b10,c10,e10)},d.prototype.mul=function(a10){var b10=this.lo*a10.lo,c10=(b10*k7|0)+this.mi*a10.lo+this.lo*a10.mi,e10=(c10*k7|0)+this.hi*a10.lo+this.mi*a10.mi+this.lo*a10.hi;return new d(b10,c10,e10)},d.prototype.isZero=function(){return(this.lo|this.mi|this.hi)==0},d.prototype.isNeg=function(){return this.hi<<16<0},d.prototype.and=function(a10){return new d(this.lo&a10.lo,this.mi&a10.mi,this.hi&a10.hi)},d.prototype.or=function(a10){return new d(this.lo|a10.lo,this.mi|a10.mi,this.hi|a10.hi)},d.prototype.xor=function(a10){return new d(this.lo^a10.lo,this.mi^a10.mi,this.hi^a10.hi)},d.prototype.shift_left=function(a10){return a10=a10&63,a10==0?this:a10<24?new d(this.lo<>24-a10,this.hi<>24-a10):a10<48?new d(0,this.lo<>48-a10):new d(0,0,this.lo<>a10|this.mi<<24-a10,this.mi>>a10|this.hi<<24-a10,this.hi>>a10):a10<48?new d(this.mi>>a10-24|this.hi<<48-a10,this.hi>>a10-24,0):new d(this.hi>>a10-48,0,0)},d.prototype.shift_right=function(a10){if(a10=a10&63,a10==0)return this;var c10=this.hi<<16>>16;if(a10<24)return new d(this.lo>>a10|this.mi<<24-a10,this.mi>>a10|c10<<24-a10,this.hi<<16>>a10>>>16);var b10=this.hi<<16>>31;return a10<48?new d(this.mi>>a10-24|this.hi<<48-a10,this.hi<<16>>a10-24>>16,b10&aI):new d(this.hi<<16>>a10-32,b10,b10)},d.prototype.lsl1=function(){this.hi=this.hi<<1|this.mi>>23,this.mi=(this.mi<<1|this.lo>>23)&aV,this.lo=this.lo<<1&aV},d.prototype.lsr1=function(){this.lo=(this.lo>>>1|this.mi<<23)&aV,this.mi=(this.mi>>>1|this.hi<<23)&aV,this.hi=this.hi>>>1},d.prototype.udivmod=function(a10){for(var e10=0,c10=this.copy(),b10=a10.copy(),f10=new d(0,0,0);c10.ucompare(b10)>0;)e10++,b10.lsl1();for(;e10>=0;)e10--,f10.lsl1(),c10.ucompare(b10)>=0&&(f10.lo++,c10=c10.sub(b10)),b10.lsr1();return{quotient:f10,modulus:c10}},d.prototype.div=function(a10){var b10=this;a10.isZero()&&gm();var d10=b10.hi^a10.hi;b10.hi&aF&&(b10=b10.neg()),a10.hi&aF&&(a10=a10.neg());var c10=b10.udivmod(a10).quotient;return d10&aF&&(c10=c10.neg()),c10},d.prototype.mod=function(a10){var b10=this;a10.isZero()&&gm();var d10=b10.hi;b10.hi&aF&&(b10=b10.neg()),a10.hi&aF&&(a10=a10.neg());var c10=b10.udivmod(a10).modulus;return d10&aF&&(c10=c10.neg()),c10},d.prototype.toInt=function(){return this.lo|this.mi<<24},d.prototype.toFloat=function(){return(this.hi<<16)*Math.pow(2,32)+this.mi*Math.pow(2,24)+this.lo},d.prototype.toArray=function(){return[this.hi>>8,this.hi&aX,this.mi>>16,this.mi>>8&aX,this.mi&aX,this.lo>>16,this.lo>>8&aX,this.lo&aX]},d.prototype.lo32=function(){return this.lo|(this.mi&aX)<<24},d.prototype.hi32=function(){return this.mi>>>8&aI|this.hi<<16};function dV(a10,b10,c10){return new d(a10,b10,c10)}function dU(a10){if(!isFinite(a10))return isNaN(a10)?dV(1,0,j_):a10>0?dV(0,0,j_):dV(0,0,65520);var f10=a10==0&&1/a10==-1/0?aF:a10>=0?0:aF;f10&&(a10=-a10);var b10=As(a10)+1023;b10<=0?(b10=0,a10/=Math.pow(2,-jw)):(a10/=Math.pow(2,b10-kl),a10<16&&(a10*=2,b10-=1),b10==0&&(a10/=2));var d10=Math.pow(2,24),c10=a10|0;a10=(a10-c10)*d10;var e10=a10|0;a10=(a10-e10)*d10;var g10=a10|0;return c10=c10&fS|f10|b10<<4,dV(g10,e10,c10)}function kZ(a10,b10,c10){if(a10.write(32,b10.dims.length),a10.write(32,b10.kind|b10.layout<<8),b10.caml_custom==dJ)for(var d10=0;d10>4;if(d10==2047)return f10|g10|c10&fS?NaN:c10&aF?-1/0:1/0;var e10=Math.pow(2,-24),b10=(f10*e10+g10)*e10+(c10&fS);return d10>0?(b10+=16,b10*=Math.pow(2,d10-kl)):b10*=Math.pow(2,-jw),c10&aF&&(b10=-b10),b10}function f7(a10){for(var d10=a10.length,c10=1,b10=0;b10>>24&aX|(b10&aI)<<8,b10>>>16&aI)}function gg(a10){return a10.hi32()}function gh(a10){return a10.lo32()}var zt=dJ;function bc(a10,b10,c10,d10){this.kind=a10,this.layout=b10,this.dims=c10,this.data=d10}bc.prototype.caml_custom=zt,bc.prototype.offset=function(a10){var c10=0;if(typeof a10=="number"&&(a10=[a10]),a10 instanceof Array||G("bigarray.js: invalid offset"),this.dims.length!=a10.length&&G("Bigarray.get/set: bad number of dimensions"),this.layout==0)for(var b10=0;b10=this.dims[b10])&&cx(),c10=c10*this.dims[b10]+a10[b10];else for(var b10=this.dims.length-1;b10>=0;b10--)(a10[b10]<1||a10[b10]>this.dims[b10])&&cx(),c10=c10*this.dims[b10]+(a10[b10]-1);return c10},bc.prototype.get=function(a10){switch(this.kind){case 7:var d10=this.data[a10*2+0],b10=this.data[a10*2+1];return zR(d10,b10);case 10:case 11:var e10=this.data[a10*2+0],c10=this.data[a10*2+1];return[dG,e10,c10];default:return this.data[a10]}},bc.prototype.set=function(a10,b10){switch(this.kind){case 7:this.data[a10*2+0]=gh(b10),this.data[a10*2+1]=gg(b10);break;case 10:case 11:this.data[a10*2+0]=b10[1],this.data[a10*2+1]=b10[2];break;default:this.data[a10]=b10;break}return 0},bc.prototype.fill=function(a10){switch(this.kind){case 7:var c10=gh(a10),e10=gg(a10);if(c10==e10)this.data.fill(c10);else for(var b10=0;b10e10)return 1;if(d10!=e10){if(!b10)return NaN;if(d10==d10)return 1;if(e10==e10)return-1}}break;case 7:for(var c10=0;c10a10.data[c10+1])return 1;if(this.data[c10]>>>0>>0)return-1;if(this.data[c10]>>>0>a10.data[c10]>>>0)return 1}break;case 2:case 3:case 4:case 5:case 6:case 8:case 9:case 12:for(var c10=0;c10a10.data[c10])return 1}break}return 0};function bX(a10,b10,c10,d10){this.kind=a10,this.layout=b10,this.dims=c10,this.data=d10}bX.prototype=new bc,bX.prototype.offset=function(a10){return typeof a10!="number"&&(a10 instanceof Array&&a10.length==1?a10=a10[0]:G("Ml_Bigarray_c_1_1.offset")),(a10<0||a10>=this.dims[0])&&cx(),a10},bX.prototype.get=function(a10){return this.data[a10]},bX.prototype.set=function(a10,b10){return this.data[a10]=b10,0},bX.prototype.fill=function(a10){return this.data.fill(a10),0};function kV(a10,b10,c10,d10){var e10=kX(a10);return f7(c10)*e10!=d10.length&&G("length doesn't match dims"),b10==0&&c10.length==1&&e10==1?new bX(a10,b10,c10,d10):new bc(a10,b10,c10,d10)}function aj(a10){U.Failure||(U.Failure=[q,f6,-3]),gl(U.Failure,a10)}function kW(a10,b10,c10){var k10=a10.read32s();(k10<0||k10>16)&&aj("input_value: wrong number of bigarray dimensions");var r10=a10.read32s(),l10=r10&aX,q10=r10>>8&1,j10=[];if(c10==dJ)for(var d10=0;d10>>17,b10=cC(b10,461845907),a10^=b10,a10=a10<<13|a10>>>19,(a10+(a10<<2)|0)+-430675100|0}function zL(a10,b10){return a10=V(a10,gh(b10)),a10=V(a10,gg(b10)),a10}function gb(a10,b10){return zL(a10,dU(b10))}function kY(a10){var c10=f7(a10.dims),d10=0;switch(a10.kind){case 2:case 3:case 12:c10>cv&&(c10=cv);var e10=0,b10=0;for(b10=0;b10+4<=a10.data.length;b10+=4)e10=a10.data[b10+0]|a10.data[b10+1]<<8|a10.data[b10+2]<<16|a10.data[b10+3]<<24,d10=V(d10,e10);switch(e10=0,c10&3){case 3:e10=a10.data[b10+2]<<16;case 2:e10|=a10.data[b10+1]<<8;case 1:e10|=a10.data[b10+0],d10=V(d10,e10)}break;case 4:case 5:c10>bu&&(c10=bu);var e10=0,b10=0;for(b10=0;b10+2<=a10.data.length;b10+=2)e10=a10.data[b10+0]|a10.data[b10+1]<<16,d10=V(d10,e10);c10&1&&(d10=V(d10,a10.data[b10]));break;case 6:c10>64&&(c10=64);for(var b10=0;b1064&&(c10=64);for(var b10=0;b1032&&(c10=32),c10*=2;for(var b10=0;b1064&&(c10=64);for(var b10=0;b1032&&(c10=32);for(var b10=0;b100?f10(b10,a10,d10):f10(a10,b10,d10);if(d10&&e10!=e10)return c10;if(+e10!=+e10)return+e10;if(e10|0)return e10|0}return c10}function dY(a10){return typeof a10=="string"&&!/[^\x00-\xff]/.test(a10)}function dX(a10){return a10 instanceof aY}function k2(a10){if(typeof a10=="number")return cu;if(dX(a10))return dC;if(dY(a10))return 1252;if(a10 instanceof Array&&a10[0]===a10[0]>>>0&&a10[0]<=jS){var b10=a10[0]|0;return b10==dG?0:b10}else{if(a10 instanceof String)return jk;if(typeof a10=="string")return jk;if(a10 instanceof Number)return cu;if(a10&&a10.caml_custom)return fX;if(a10&&a10.compare)return 1256;if(typeof a10=="function")return 1247;if(typeof a10=="symbol")return 1251}return 1001}function k_(a10,b10){return a10b10?1:0}function zv(a10,b10){return a10.t&6&&cz(a10),b10.t&6&&cz(b10),a10.cb10.c?1:0}function dR(a10,b10,c10){for(var f10=[];;){if(!(c10&&a10===b10)){var e10=k2(a10);if(e10==aD){a10=a10[1];continue}var g10=k2(b10);if(g10==aD){b10=b10[1];continue}if(e10!==g10)return e10==cu?g10==fX?k1(a10,b10,-1,c10):-1:g10==cu?e10==fX?k1(b10,a10,1,c10):1:e10b10)return 1;if(a10!=b10){if(!c10)return NaN;if(a10==a10)return 1;if(b10==b10)return-1}break;case 1001:if(a10b10)return 1;if(a10!=b10){if(!c10)return NaN;if(a10==a10)return 1;if(b10==b10)return-1}break;case 1251:if(a10!==b10)return c10?1:NaN;break;case 1252:var a10=a10,b10=b10;if(a10!==b10){if(a10b10)return 1}break;case 12520:var a10=a10.toString(),b10=b10.toString();if(a10!==b10){if(a10b10)return 1}break;case 246:case 254:default:if(la(e10)){G("compare: continuation value");break}if(a10.length!=b10.length)return a10.length1&&f10.push(a10,b10,1);break}}if(f10.length==0)return 0;var h10=f10.pop();b10=f10.pop(),a10=f10.pop(),h10+10)if(b10==0&&(c10>=a10.l||a10.t==2&&c10>=a10.c.length))d10==0?(a10.c=e,a10.t=2):(a10.c=b1(c10,String.fromCharCode(d10)),a10.t=c10==a10.l?0:2);else for(a10.t!=4&&dS(a10),c10+=b10;b100&&b10===b10||(a10=a10.replace(/_/g,e),b10=+a10,a10.length>0&&b10===b10||/^[+-]?nan$/i.test(a10)))return b10;var c10=/^ *([+-]?)0x([0-9a-f]+)\.?([0-9a-f]*)(p([+-]?[0-9]+))?/i.exec(a10);if(c10){var d10=c10[3].replace(/0+$/,e),g10=parseInt(c10[1]+c10[2]+d10,16),f10=(c10[5]|0)-4*d10.length;return b10=g10*Math.pow(2,f10),b10}if(/^\+?inf(inity)?$/i.test(a10))return 1/0;if(/^-inf(inity)?$/i.test(a10))return-1/0;aj("float_of_string")}function gk(a10){a10=a10;var e10=a10.length;e10>31&&G("format_int: format too long");for(var b10={justify:bV,signstyle:bs,filler:aE,alternate:!1,base:0,signedconv:!1,width:0,uppercase:!1,sign:1,prec:-1,conv:"f"},d10=0;d10=0&&c10<=9;)b10.width=b10.width*10+c10,d10++;d10--;break;case".":for(b10.prec=0,d10++;c10=a10.charCodeAt(d10)-48,c10>=0&&c10<=9;)b10.prec=b10.prec*10+c10,d10++;d10--;case"d":case"i":b10.signedconv=!0;case"u":b10.base=10;break;case"x":b10.base=16;break;case"X":b10.base=16,b10.uppercase=!0;break;case"o":b10.base=8;break;case"e":case"f":case"g":b10.signedconv=!0,b10.conv=c10;break;case"E":case"F":case"G":b10.signedconv=!0,b10.uppercase=!0,b10.conv=c10.toLowerCase();break}}return b10}function f$(a10,b10){a10.uppercase&&(b10=b10.toUpperCase());var f10=b10.length;a10.signedconv&&(a10.sign<0||a10.signstyle!=bs)&&f10++,a10.alternate&&(a10.base==8&&(f10+=1),a10.base==16&&(f10+=2));var c10=e;if(a10.justify==bV&&a10.filler==aE)for(var d10=f10;d1020?(c11-=20,a11/=Math.pow(10,c11),a11+=new Array(c11+1).join(ad),b11>0&&(a11=a11+a$+new Array(b11+1).join(ad)),a11):a11.toFixed(b11)}var c10,f10=gk(a10),e10=f10.prec<0?6:f10.prec;if((b10<0||b10==0&&1/b10==-1/0)&&(f10.sign=-1,b10=-b10),isNaN(b10))c10=fG,f10.filler=aE;else if(!isFinite(b10))c10="inf",f10.filler=aE;else switch(f10.conv){case"e":var c10=b10.toExponential(e10),d10=c10.length;c10.charAt(d10-3)==fP&&(c10=c10.slice(0,d10-1)+ad+c10.slice(d10-1));break;case"f":c10=j10(b10,e10);break;case"g":e10=e10||1,c10=b10.toExponential(e10-1);var i10=c10.indexOf(fP),h10=+c10.slice(i10+1);if(h10<-4||b10>=1e21||b10.toFixed(0).length>e10){for(var d10=i10-1;c10.charAt(d10)==ad;)d10--;c10.charAt(d10)==a$&&d10--,c10=c10.slice(0,d10+1)+c10.slice(i10),d10=c10.length,c10.charAt(d10-3)==fP&&(c10=c10.slice(0,d10-1)+ad+c10.slice(d10-1));break}else{var g10=e10;if(h10<0)g10-=h10+1,c10=b10.toFixed(g10);else for(;c10=b10.toFixed(g10),c10.length>e10+1;)g10--;if(g10){for(var d10=c10.length-1;c10.charAt(d10)==ad;)d10--;c10.charAt(d10)==a$&&d10--,c10=c10.slice(0,d10+1)}}break}return f$(f10,c10)}function dT(a10,b10){if(a10==fA)return e+b10;var c10=gk(a10);b10<0&&(c10.signedconv?(c10.sign=-1,b10=-b10):b10>>>=0);var d10=b10.toString(c10.base);if(c10.prec>=0){c10.filler=aE;var f10=c10.prec-d10.length;f10>0&&(d10=b1(f10,ad)+d10)}return f$(c10,d10)}var Ah=0;function ae(){return Ah++}function H(a10){return gq(a10)?a10:lo(a10)}function cF(){return typeof p.process<"u"&&typeof p.process.versions<"u"&&typeof p.process.versions.node<"u"}function Au(){function a10(a11){if(a11.charAt(0)===aH)return[e,a11.substring(1)]}function b10(a11){var h10=/^([a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?([\\/])?([\s\S]*?)$/,b11=h10.exec(a11),c10=b11[1]||e,f10=!!(c10&&c10.charAt(1)!==":");if(b11[2]||f10){var d10=b11[1]||e,g10=b11[2]||e;return[d10,a11.substring(d10.length+g10.length)]}}return cF()&&p.process&&p.process.platform&&p.process.platform==="win32"?b10:a10}var gr=Au();function lm(a10){return a10.slice(-1)!==aH?a10+aH:a10}if(cF()&&p.process&&p.process.cwd)var cA=p.process.cwd().replace(/\\/g,aH);else var cA="/static";cA=lm(cA);function z6(a10){a10=H(a10),gr(a10)||(a10=cA+a10);for(var e10=gr(a10),d10=e10[1].split(aH),b10=[],c10=0;c101&&b10.pop();break;case".":break;case"":break;default:b10.push(d10[c10]);break}return b10.unshift(e10[0]),b10.orig=a10,b10}function Ar(a10){for(var g10=e,c10=g10,b10,i10,d10=0,h10=a10.length;d10dF?(c10.substr(0,1),g10+=c10,c10=e,g10+=a10.slice(d10,f10)):c10+=a10.slice(d10,f10),f10==h10)break;d10=f10}b10>6),c10+=String.fromCharCode(ao|b10&bb)):b10<55296||b10>=jF?c10+=String.fromCharCode(kH|b10>>12,ao|b10>>6&bb,ao|b10&bb):b10>=56319||d10+1==h10||(i10=a10.charCodeAt(d10+1))jF?c10+="\xEF\xBF\xBD":(d10++,b10=(b10<<10)+i10-56613888,c10+=String.fromCharCode(j0|b10>>18,ao|b10>>12&bb,ao|b10>>6&bb,ao|b10&bb)),c10.length>ct&&(c10.substr(0,1),g10+=c10,c10=e)}return g10+c10}function as(a10){return gq(a10)?a10:Ar(a10)}var Av=["E2BIG","EACCES","EAGAIN",fz,"EBUSY","ECHILD","EDEADLK","EDOM",kG,"EFAULT","EFBIG","EINTR","EINVAL","EIO","EISDIR","EMFILE","EMLINK","ENAMETOOLONG","ENFILE","ENODEV",fO,"ENOEXEC","ENOLCK","ENOMEM","ENOSPC","ENOSYS",fT,ki,"ENOTTY","ENXIO","EPERM","EPIPE","ERANGE","EROFS","ESPIPE","ESRCH","EXDEV","EWOULDBLOCK","EINPROGRESS","EALREADY","ENOTSOCK","EDESTADDRREQ","EMSGSIZE","EPROTOTYPE","ENOPROTOOPT","EPROTONOSUPPORT","ESOCKTNOSUPPORT","EOPNOTSUPP","EPFNOSUPPORT","EAFNOSUPPORT","EADDRINUSE","EADDRNOTAVAIL","ENETDOWN","ENETUNREACH","ENETRESET","ECONNABORTED","ECONNRESET","ENOBUFS","EISCONN","ENOTCONN","ESHUTDOWN","ETOOMANYREFS","ETIMEDOUT","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ELOOP","EOVERFLOW"];function a2(a10,b10,c10,d10){var f10=Av.indexOf(a10);f10<0&&(d10==null&&(d10=-9999),f10=[0,d10]);var g10=[f10,as(b10||e),as(c10||e)];return g10}var lg={};function bg(a10){return lg[a10]}function a1(a10,b10){throw g([0,a10].concat(b10))}function f9(a10){return a10 instanceof Uint8Array||(a10=new Uint8Array(a10)),new aY(4,a10,a10.length)}function m(a10){gl(U.Sys_error,a10)}function lj(a10){m(a10+dL)}function gp(a10){return a10.t!=4&&dS(a10),a10.c}function aq(a10){return a10.l}function kT(){}function Y(a10){this.data=a10}Y.prototype=new kT,Y.prototype.constructor=Y,Y.prototype.truncate=function(a10){var b10=this.data;this.data=F(a10|0),aZ(b10,0,this.data,0,a10)},Y.prototype.length=function(){return aq(this.data)},Y.prototype.write=function(a10,b10,c10,d10){var e10=this.length();if(a10+d10>=e10){var f10=F(a10+d10),g10=this.data;this.data=f10,aZ(g10,0,this.data,0,e10)}return aZ(f9(b10),c10,this.data,a10,d10),0},Y.prototype.read=function(a10,b10,c10,d10){var e10=this.length();if(a10+d10>=e10&&(d10=e10-a10),d10){var f10=F(d10|0);aZ(this.data,a10,f10,0,d10),b10.set(gp(f10),c10)}return d10};function bw(a10,b10,c10){this.file=b10,this.name=a10,this.flags=c10}bw.prototype.err_closed=function(){m(this.name+jm)},bw.prototype.length=function(){if(this.file)return this.file.length();this.err_closed()},bw.prototype.write=function(a10,b10,c10,d10){if(this.file)return this.file.write(a10,b10,c10,d10);this.err_closed()},bw.prototype.read=function(a10,b10,c10,d10){if(this.file)return this.file.read(a10,b10,c10,d10);this.err_closed()},bw.prototype.close=function(){this.file=void 0};function N(a10,b10){this.content={},this.root=a10,this.lookupFun=b10}N.prototype.nm=function(a10){return this.root+a10},N.prototype.create_dir_if_needed=function(a10){for(var d10=a10.split(aH),c10=e,b10=0;b10>>16,a10=cC(a10,-2048144789),a10^=a10>>>13,a10=cC(a10,-1028477387),a10^=a10>>>16,a10}function zH(a10,b10,c10,d10){var j10,k10,l10,h10,g10,f10,e10,i10,m10;for(h10=b10,(h10<0||h10>cv)&&(h10=cv),g10=a10,f10=c10,j10=[d10],k10=0,l10=1;k100;)if(e10=j10[k10++],e10&&e10.caml_custom){if(cB[e10.caml_custom]&&cB[e10.caml_custom].hash){var n10=cB[e10.caml_custom].hash(e10);f10=V(f10,n10),g10--}}else if(e10 instanceof Array&&e10[0]===(e10[0]|0))switch(e10[0]){case 248:f10=V(f10,e10[2]),g10--;break;case 250:j10[--k10]=e10[1];break;default:if(la(e10[0]))break;var o10=e10.length-1<<10|e10[0];for(f10=V(f10,o10),i10=1,m10=e10.length;i10=h10);i10++)j10[l10++]=e10[i10];break}else dX(e10)?(f10=zI(f10,e10),g10--):dY(e10)?(f10=zM(f10,e10),g10--):typeof e10=="string"?(f10=gc(f10,e10),g10--):e10===(e10|0)?(f10=V(f10,e10+e10+1),g10--):typeof e10=="number"&&(f10=gb(f10,e10),g10--);return f10=zK(f10),f10&1073741823}function zN(a10,b10,c10){if(!isFinite(a10))return isNaN(a10)?as(fG):as(a10>0?j4:"-infinity");var k10=a10==0&&1/a10==-1/0?1:a10>=0?0:1;k10&&(a10=-a10);var f10=0;if(a10!=0)if(a10<1)for(;a10<1&&f10>-1022;)a10*=2,f10--;else for(;a10>=2;)a10/=2,f10++;var l10=f10<0?e:bV,g10=e;if(k10)g10=bs;else switch(c10){case 43:g10=bV;break;case 32:g10=aE;break;default:break}if(b10>=0&&b10<13){var i10=Math.pow(2,b10*4);a10=Math.round(a10*i10)/i10}var d10=a10.toString(16);if(b10>=0){var j10=d10.indexOf(a$);if(j10<0)d10+=a$+b1(b10,ad);else{var h10=j10+1+b10;d10.length>24&aV,a10>>31&aI)}function zY(a10){return a10.toInt()}function zU(a10){return+a10.isNeg()}function zX(a10){return a10.neg()}function zS(a10,b10){var c10=gk(a10);c10.signedconv&&zU(b10)&&(c10.sign=-1,b10=zX(b10));var d10=e,i10=dW(c10.base),h10="0123456789abcdef";do{var g10=b10.udivmod(i10);b10=g10.quotient,d10=h10.charAt(zY(g10.modulus))+d10}while(!zV(b10));if(c10.prec>=0){c10.filler=aE;var f10=c10.prec-d10.length;f10>0&&(d10=b1(f10,ad)+d10)}return f$(c10,d10)}function k8(a10,b10){return a10.or(b10)}function k9(a10,b10){return a10.shift_left(b10)}function gi(a10,b10){return a10.shift_right_unsigned(b10)}function Ai(a10){var b10=0,e10=n(a10),c10=10,d10=1;if(e10>0)switch(_(a10,b10)){case 45:b10++,d10=-1;break;case 43:b10++,d10=1;break}if(b10+1=48&&a10<=57?a10-48:a10>=65&&a10<=90?a10-55:a10>=97&&a10<=122?a10-87:-1}function k$(a10){var h10=Ai(a10),d10=h10[0],i10=h10[1],e10=h10[2],g10=n(a10),j10=-1>>>0,f10=d10=e10)&&aj(dO);var b10=c10;for(d10++;d10=e10)break;b10=e10*b10+c10,b10>j10&&aj(dO)}return d10!=g10&&aj(dO),b10=i10*b10,e10==10&&(b10|0)!=b10&&aj(dO),b10|0}function lb(a10){return a10.slice(1)}function dZ(a10,b10,c10){return a10[H(b10)].apply(a10,lb(c10))}function z1(a10,b10){switch(b10.length){case 1:return new a10;case 2:return new a10(b10[1]);case 3:return new a10(b10[1],b10[2]);case 4:return new a10(b10[1],b10[2],b10[3]);case 5:return new a10(b10[1],b10[2],b10[3],b10[4]);case 6:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5]);case 7:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5],b10[6]);case 8:return new a10(b10[1],b10[2],b10[3],b10[4],b10[5],b10[6],b10[7])}function c10(){return a10.apply(this,lb(b10))}return c10.prototype=a10.prototype,new c10}function lc(a10){for(var c10={},b10=1;b10>>32-e10,c10)}function g10(a10,b10,c10,d10,e10,f10,g11){return l10(b10&c10|~b10&d10,a10,b10,e10,f10,g11)}function h10(a10,b10,c10,d10,e10,f10,g11){return l10(b10&d10|c10&~d10,a10,b10,e10,f10,g11)}function i10(a10,b10,c10,d10,e10,f10,g11){return l10(b10^c10^d10,a10,b10,e10,f10,g11)}function j10(a10,b10,c10,d10,e10,f10,g11){return l10(c10^(b10|~d10),a10,b10,e10,f10,g11)}return function(a10,b10){var c10=a10[0],d10=a10[1],e10=a10[2],f10=a10[3];c10=g10(c10,d10,e10,f10,b10[0],7,3614090360),f10=g10(f10,c10,d10,e10,b10[1],12,3905402710),e10=g10(e10,f10,c10,d10,b10[2],17,606105819),d10=g10(d10,e10,f10,c10,b10[3],22,3250441966),c10=g10(c10,d10,e10,f10,b10[4],7,4118548399),f10=g10(f10,c10,d10,e10,b10[5],12,1200080426),e10=g10(e10,f10,c10,d10,b10[6],17,2821735955),d10=g10(d10,e10,f10,c10,b10[7],22,4249261313),c10=g10(c10,d10,e10,f10,b10[8],7,1770035416),f10=g10(f10,c10,d10,e10,b10[9],12,2336552879),e10=g10(e10,f10,c10,d10,b10[10],17,4294925233),d10=g10(d10,e10,f10,c10,b10[11],22,2304563134),c10=g10(c10,d10,e10,f10,b10[12],7,1804603682),f10=g10(f10,c10,d10,e10,b10[13],12,4254626195),e10=g10(e10,f10,c10,d10,b10[14],17,2792965006),d10=g10(d10,e10,f10,c10,b10[15],22,1236535329),c10=h10(c10,d10,e10,f10,b10[1],5,4129170786),f10=h10(f10,c10,d10,e10,b10[6],9,3225465664),e10=h10(e10,f10,c10,d10,b10[11],14,643717713),d10=h10(d10,e10,f10,c10,b10[0],20,3921069994),c10=h10(c10,d10,e10,f10,b10[5],5,3593408605),f10=h10(f10,c10,d10,e10,b10[10],9,38016083),e10=h10(e10,f10,c10,d10,b10[15],14,3634488961),d10=h10(d10,e10,f10,c10,b10[4],20,3889429448),c10=h10(c10,d10,e10,f10,b10[9],5,568446438),f10=h10(f10,c10,d10,e10,b10[14],9,3275163606),e10=h10(e10,f10,c10,d10,b10[3],14,4107603335),d10=h10(d10,e10,f10,c10,b10[8],20,1163531501),c10=h10(c10,d10,e10,f10,b10[13],5,2850285829),f10=h10(f10,c10,d10,e10,b10[2],9,4243563512),e10=h10(e10,f10,c10,d10,b10[7],14,1735328473),d10=h10(d10,e10,f10,c10,b10[12],20,2368359562),c10=i10(c10,d10,e10,f10,b10[5],4,4294588738),f10=i10(f10,c10,d10,e10,b10[8],11,2272392833),e10=i10(e10,f10,c10,d10,b10[11],16,1839030562),d10=i10(d10,e10,f10,c10,b10[14],23,4259657740),c10=i10(c10,d10,e10,f10,b10[1],4,2763975236),f10=i10(f10,c10,d10,e10,b10[4],11,1272893353),e10=i10(e10,f10,c10,d10,b10[7],16,4139469664),d10=i10(d10,e10,f10,c10,b10[10],23,3200236656),c10=i10(c10,d10,e10,f10,b10[13],4,681279174),f10=i10(f10,c10,d10,e10,b10[0],11,3936430074),e10=i10(e10,f10,c10,d10,b10[3],16,3572445317),d10=i10(d10,e10,f10,c10,b10[6],23,76029189),c10=i10(c10,d10,e10,f10,b10[9],4,3654602809),f10=i10(f10,c10,d10,e10,b10[12],11,3873151461),e10=i10(e10,f10,c10,d10,b10[15],16,530742520),d10=i10(d10,e10,f10,c10,b10[2],23,3299628645),c10=j10(c10,d10,e10,f10,b10[0],6,4096336452),f10=j10(f10,c10,d10,e10,b10[7],10,1126891415),e10=j10(e10,f10,c10,d10,b10[14],15,2878612391),d10=j10(d10,e10,f10,c10,b10[5],21,4237533241),c10=j10(c10,d10,e10,f10,b10[12],6,1700485571),f10=j10(f10,c10,d10,e10,b10[3],10,2399980690),e10=j10(e10,f10,c10,d10,b10[10],15,4293915773),d10=j10(d10,e10,f10,c10,b10[1],21,2240044497),c10=j10(c10,d10,e10,f10,b10[8],6,1873313359),f10=j10(f10,c10,d10,e10,b10[15],10,4264355552),e10=j10(e10,f10,c10,d10,b10[6],15,2734768916),d10=j10(d10,e10,f10,c10,b10[13],21,1309151649),c10=j10(c10,d10,e10,f10,b10[4],6,4149444226),f10=j10(f10,c10,d10,e10,b10[11],10,3174756917),e10=j10(e10,f10,c10,d10,b10[2],15,718787259),d10=j10(d10,e10,f10,c10,b10[9],21,3951481745),a10[0]=k10(c10,a10[0]),a10[1]=k10(d10,a10[1]),a10[2]=k10(e10,a10[2]),a10[3]=k10(f10,a10[3])}}();function zp(a10,b10,c10){var e10=a10.len&bb,d10=0;if(a10.len+=c10,e10){var f10=64-e10;if(c10=64;)a10.b8.set(b10.subarray(d10,d10+64),0),dP(a10.w,a10.b32),c10-=64,d10+=64;c10&&a10.b8.set(b10.subarray(d10,d10+c10),0)}function zn(a10){var c10=a10.len&bb;if(a10.b8[c10]=ao,c10++,c10>56){for(var b10=c10;b10<64;b10++)a10.b8[b10]=0;dP(a10.w,a10.b32);for(var b10=0;b10<56;b10++)a10.b8[b10]=0}else for(var b10=c10;b10<56;b10++)a10.b8[b10]=0;a10.b32[14]=a10.len<<3,a10.b32[15]=a10.len>>29&536870911,dP(a10.w,a10.b32);for(var e10=new Uint8Array(16),d10=0;d10<4;d10++)for(var b10=0;b10<4;b10++)e10[d10*4+b10]=a10.w[d10]>>8*b10&255;return e10}function An(a10){return cE(a10,0,a10.length)}function z7(a10,b10,c10){var d10=zo(),e10=gp(a10);return zp(d10,e10.subarray(b10,b10+c10),c10),An(zn(d10))}function z8(a10,b10,c10){return z7(bd(a10),b10,c10)}function z_(){return 0}var bf=new Array;function ld(a10){return bf[a10]}function bz(a10){var b10=ld(a10);return b10.opened||m("Cannot flush a closed channel"),!b10.buffer||b10.buffer_curr==0||(b10.output?b10.output(cE(b10.buffer,0,b10.buffer_curr)):b10.file.write(b10.offset,b10.buffer,0,b10.buffer_curr),b10.offset+=b10.buffer_curr,b10.buffer_curr=0),0}function Ap(a10,b10){if(b10.name)try{var d10=__require(fH),c10=d10.openSync(b10.name,"rs");return new av(c10,b10)}catch{}return new av(a10,b10)}var d2=new Array(3);function cw(a10,b10){Y.call(this,F(0)),this.log=function(a11){return 0},a10==1&&typeof console.log=="function"?this.log=console.log:a10==2&&typeof console.error=="function"?this.log=console.error:typeof console.log=="function"&&(this.log=console.log),this.flags=b10}cw.prototype.length=function(){return 0},cw.prototype.write=function(a10,b10,c10,d10){if(this.log){d10>0&&c10>=0&&c10+d10<=b10.length&&b10[c10+d10-1]==10&&d10--;var e10=F(d10);return aZ(f9(b10),c10,e10,0,d10),this.log(e10.toUtf16()),0}m(this.fd+jm)},cw.prototype.read=function(a10,b10,c10,d10){m(this.fd+": file descriptor is write only")},cw.prototype.close=function(){this.log=void 0};function d3(a10,b10){return b10==null&&(b10=d2.length),d2[b10]=a10,b10|0}function Ax(a10,b10,c10){for(var d10={};b10;){switch(b10[1]){case 0:d10.rdonly=1;break;case 1:d10.wronly=1;break;case 2:d10.append=1;break;case 3:d10.create=1;break;case 4:d10.truncate=1;break;case 5:d10.excl=1;break;case 6:d10.binary=1;break;case 7:d10.text=1;break;case 8:d10.nonblock=1;break}b10=b10[2]}d10.rdonly&&d10.wronly&&m(a10+f5),d10.text&&d10.binary&&m(a10+fE);var e10=lr(a10),f10=e10.device.open(e10.rest,d10);return d3(f10,void 0)}(function(){function a10(a11,b10){return cF()?Ap(a11,b10):new cw(a11,b10)}d3(a10(0,{rdonly:1,altname:"/dev/stdin",isCharacterDevice:!0}),0),d3(a10(1,{buffered:2,wronly:1,isCharacterDevice:!0}),1),d3(a10(2,{buffered:2,wronly:1,isCharacterDevice:!0}),2)})();function z$(a10){var b10=d2[a10];b10.flags.wronly&&m(j3+a10+" is writeonly");var d10=null,c10={file:b10,offset:b10.flags.append?b10.length():0,fd:a10,opened:!0,out:!1,buffer_curr:0,buffer_max:0,buffer:new Uint8Array(j5),refill:d10};return bf[c10.fd]=c10,c10.fd}function le(a10){var b10=d2[a10];b10.flags.rdonly&&m(j3+a10+" is readonly");var d10=b10.flags.buffered!==void 0?b10.flags.buffered:1,c10={file:b10,offset:b10.flags.append?b10.length():0,fd:a10,opened:!0,out:!0,buffer_curr:0,buffer:new Uint8Array(j5),buffered:d10};return bf[c10.fd]=c10,c10.fd}function Aa(){for(var b10=0,a10=0;a10e10.buffer.length){var g10=new Uint8Array(e10.buffer_curr+b10.length);g10.set(e10.buffer),e10.buffer=g10}switch(e10.buffered){case 0:e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,bz(a10);break;case 1:e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,e10.buffer_curr>=e10.buffer.length&&bz(a10);break;case 2:var f10=b10.lastIndexOf(10);f10<0?(e10.buffer.set(b10,e10.buffer_curr),e10.buffer_curr+=b10.length,e10.buffer_curr>=e10.buffer.length&&bz(a10)):(e10.buffer.set(b10.subarray(0,f10+1),e10.buffer_curr),e10.buffer_curr+=f10+1,bz(a10),e10.buffer.set(b10.subarray(f10+1),e10.buffer_curr),e10.buffer_curr+=b10.length-f10-1);break}return 0}function Ab(a10,b10,c10,d10){var b10=gp(b10);return Ac(a10,b10,c10,d10)}function gj(a10,b10,c10,d10){return Ab(a10,bd(b10),c10,d10)}function lf(a10,b10){var c10=String.fromCharCode(b10);return gj(a10,c10,0,1),0}function Ad(a10,b10){return b10==0&&gm(),a10%b10}function cD(a10,b10){return+(dR(a10,b10,!1)!=0)}function Af(a10,b10){var d10=new Array(b10+1);d10[0]=a10;for(var c10=1;c10<=b10;c10++)d10[c10]=0;return d10}function Ag(a10,b10){return a10[0]=aD,a10[1]=b10,0}function aw(a10){return a10 instanceof Array&&a10[0]==a10[0]>>>0?a10[0]:dX(a10)||dY(a10)?dC:a10 instanceof Function||typeof a10=="function"?247:a10&&a10.caml_custom?jS:cu}function zu(a10){var c10={};if(a10)for(var b10=1;b10=0?a10=e10:aj("caml_register_global: cannot locate "+d10)}}U[a10+1]=b10,c10&&(U[c10]=b10)}function go(a10,b10){return lg[a10]=b10,0}function Am(){G(fC)}function y(a10,b10){return b10>>>0>=n(a10)&&Am(),_(a10,b10)}function d1(a10){return a10.t&6&&cz(a10),a10.c}function Ao(){return 2147483647/4|0}function Aj(){li(U.Not_found)}function ll(a10){var b10=lq(H(a10));return b10===void 0&&Aj(),as(b10)}function Aq(){if(p.crypto){if(p.crypto.getRandomValues){var a10=p.crypto.getRandomValues(new Int32Array(4));return[0,a10[0],a10[1],a10[2],a10[3]]}else if(p.crypto.randomBytes){var a10=new Int32Array(p.crypto.randomBytes(16).buffer);return[0,a10[0],a10[1],a10[2],a10[3]]}}var b10=new Date().getTime(),c10=b10^4294967295*Math.random();return[0,c10]}function bA(a10){for(var b10=1;a10&&a10.joo_tramp;)a10=a10.joo_tramp.apply(null,a10.joo_args),b10++;return a10}function r(a10,b10){return{joo_tramp:a10,joo_args:b10}}function ln(a10,b10){if(b10.fun)return a10.fun=b10.fun,0;if(typeof b10=="function")return a10.fun=b10,0;for(var c10=b10.length;c10--;)a10[c10]=b10[c10];return 0}function L(a10){{if(a10 instanceof Array)return a10;var b10;return p.RangeError&&a10 instanceof p.RangeError&&a10.message&&a10.message.match(/maximum call stack/i)||p.InternalError&&a10 instanceof p.InternalError&&a10.message&&a10.message.match(/too much recursion/i)?b10=U.Stack_overflow:a10 instanceof p.Error&&bg(fV)?b10=[0,bg(fV),a10]:b10=[0,U.Failure,as(String(a10))],a10 instanceof p.Error&&(b10.js_error=a10),b10}}function z0(a10){switch(a10[2]){case-8:case-11:case-12:return 1;default:return 0}}function zE(a10){var b10=e;if(a10[0]==0){if(b10+=a10[1][1],a10.length==3&&a10[2][0]==0&&z0(a10[1]))var f10=a10[2],g10=1;else var g10=2,f10=a10;b10+="(";for(var d10=g10;d10g10&&(b10+=jx);var c10=f10[d10];typeof c10=="number"?b10+=c10.toString():c10 instanceof aY||typeof c10=="string"?b10+=dB+c10.toString()+dB:b10+=ku}b10+=")"}else a10[0]==q&&(b10+=a10[1]);return b10}function k4(a10){if(a10 instanceof Array&&(a10[0]==0||a10[0]==q)){var c10=bg(ky);if(c10)dQ(c10,[a10,!1]);else{var d10=zE(a10),b10=bg(j6);if(b10&&dQ(b10,[0]),console.error(fY+d10),a10.js_error)throw a10.js_error}}else throw a10}function Al(){var c10=p.process;c10&&c10.on?c10.on("uncaughtException",function(a10,b10){k4(a10),c10.exit(2)}):p.addEventListener&&p.addEventListener(jq,function(a10){a10.error&&k4(a10.error)})}Al();function h(a10,b10){return(a10.l>=0?a10.l:a10.l=a10.length)==1?a10(b10):be(a10,[b10])}function i(a10,b10,c10){return(a10.l>=0?a10.l:a10.l=a10.length)==2?a10(b10,c10):be(a10,[b10,c10])}function x(a10,b10,c10,d10){return(a10.l>=0?a10.l:a10.l=a10.length)==3?a10(b10,c10,d10):be(a10,[b10,c10,d10])}function fx(a10,b10,c10,d10,e10,f10){return(a10.l>=0?a10.l:a10.l=a10.length)==5?a10(b10,c10,d10,e10,f10):be(a10,[b10,c10,d10,e10,f10])}function zm(a10,b10,c10,d10,e10,f10,g10,h10){return(a10.l>=0?a10.l:a10.l=a10.length)==7?a10(b10,c10,d10,e10,f10,g10,h10):be(a10,[b10,c10,d10,e10,f10,g10,h10])}var Aw=void 0;zF();var d6=[q,kP,-1],gu=[q,jZ,-2],b3=[q,f6,-3],cH=[q,jA,-4],ax=[q,jD,-7],gs=[q,kL,-8],gt=[q,kh,-9],f=[q,kq,-11],b4=[q,kD,-12],zl=[4,0,0,0,[12,45,[4,0,0,0,0]]],es=[0,[11,'File "',[2,0,[11,'", line ',[4,0,0,0,[11,kN,[4,0,0,0,[12,45,[4,0,0,0,[11,kJ,[2,0,0]]]]]]]]]],'File "%s", line %d, characters %d-%d: %s'],i3=f4,br="content",i9="columns",i_="rows",fr=jQ,fs=f4,i$=cq,ja="page_content";ar(11,b4,kD),ar(10,f,kq),ar(9,[q,kv,-10],kv),ar(8,gt,kh),ar(7,gs,kL),ar(6,ax,jD),ar(5,[q,jV,-6],jV),ar(4,[q,j9,-5],j9),ar(3,cH,jA),ar(2,b3,f6),ar(1,gu,jZ),ar(0,d6,kP);var lB="output_substring",lx=a$,lu="true",lv="false",lF="CamlinternalLazy.Undefined",lJ="option is None",lM="\\\\",lN="\\'",lO="\\b",lP="\\t",lQ="\\n",lR="\\r",lZ="List.init",lW="hd",l_="String.blit / Bytes.blit_string",l9="Bytes.blit",l8="String.sub / Bytes.sub",mh="String.contains_from / Bytes.contains_from",mo="Array.blit",mn="Array.sub",ml="Array.init",mv=[0,"set.ml",570,18],mr=dI,ms=dI,mt=dI,mu=dI,mC="Map.remove_min_elt",my=dM,mz=dM,mA=dM,mB=dM,mD="Stdlib.Stack.Empty",mH="Stdlib.Queue.Empty",mT="Buffer.add_substring/add_subbytes",mQ="Buffer.add: cannot grow buffer",mP=[0,jg,93,2],mO=[0,jg,94,2],mM="Buffer.sub",m4="%c",m5="%s",m6=jH,m7=jv,m8=kR,m9=jB,m_="%f",m$="%B",na="%{",nb="%}",nc="%(",nd="%)",ne="%a",nf="%t",ng="%?",nh="%r",ni="%_r",nj=[0,K,850,23],nu=[0,K,814,21],nm=[0,K,815,21],nv=[0,K,818,21],nn=[0,K,819,21],nw=[0,K,822,19],no=[0,K,823,19],nx=[0,K,826,22],np=[0,K,827,22],ny=[0,K,831,30],nq=[0,K,832,30],ns=[0,K,836,26],nk=[0,K,837,26],nt=[0,K,846,28],nl=[0,K,847,28],nr=[0,K,851,23],oK=[0,K,1558,4],oL="Printf: bad conversion %[",oM=[0,K,1626,39],oN=[0,K,1649,31],oO=[0,K,1650,31],oP="Printf: bad conversion %_",oQ=jU,oR=kt,oS=jU,oT=kt,oX=[0,[11,"invalid box description ",[3,0,0]],"invalid box description %S"],oW=[0,0,4],oF=fG,oD="neg_infinity",oE=j4,oC=a$,ox=[0,ji],ol="%+nd",om="% nd",oo="%+ni",op="% ni",oq="%nx",or="%#nx",os="%nX",ot="%#nX",ou="%no",ov="%#no",ok="%nd",on=kR,ow="%nu",n9="%+ld",n_="% ld",oa="%+li",ob="% li",oc="%lx",od="%#lx",oe="%lX",of="%#lX",og="%lo",oh="%#lo",n8="%ld",n$=jv,oi="%lu",nV="%+Ld",nW="% Ld",nY="%+Li",nZ="% Li",n0="%Lx",n1="%#Lx",n2="%LX",n3="%#LX",n4="%Lo",n5="%#Lo",nU="%Ld",nX=jB,n6="%Lu",nH="%+d",nI="% d",nK="%+i",nL="% i",nM="%x",nN="%#x",nO="%X",nP="%#X",nQ="%o",nR="%#o",nG=fA,nJ=jH,nS=ka,mW="@]",mX="@}",mY="@?",mZ=`@ +`,m0="@.",m1="@@",m2="@%",m3="@",nz="CamlinternalFormat.Type_mismatch",o2=e,o3=[0,[11,jx,[2,0,[2,0,0]]],", %s%s"],pz=[0,[11,fY,[2,0,[12,10,0]]],ke],pA=[0,[11,"Fatal error in uncaught exception handler: exception ",[2,0,[12,10,0]]],`Fatal error in uncaught exception handler: exception %s +`],py="Fatal error: out of memory in uncaught exception handler",pv=[0,[11,fY,[2,0,[12,10,0]]],ke],pp=[0,[2,0,[12,10,0]],`%s +`],pq=[0,[11,jT,0],jT],pg="Raised at",ph="Re-raised at",pi="Raised by primitive operation at",pj="Called from",pk=" (inlined)",pm=e,pl=[0,[2,0,[12,32,[2,0,[11,' in file "',[2,0,[12,34,[2,0,[11,", line ",[4,0,0,0,[11,kN,zl]]]]]]]]]],'%s %s in file "%s"%s, line %d, characters %d-%d'],pn=[0,[2,0,[11," unknown location",0]],"%s unknown location"],o$="Out of memory",pa="Stack overflow",pb="Pattern matching failed",pc="Assertion failed",pd="Undefined recursive module",o5=[0,[12,40,[2,0,[2,0,[12,41,0]]]],"(%s%s)"],o6=e,o7=e,o8=[0,[12,40,[2,0,[12,41,0]]],"(%s)"],o1=[0,[4,0,0,0,0],fA],oZ=[0,[3,0,0],"%S"],o0=ku,ps=[0,e,`(Cannot print locations: bytecode executable program file not found)`,`(Cannot print locations: bytecode executable program file appears to be corrupt)`,`(Cannot print locations: bytecode executable program file has wrong magic number)`,`(Cannot print locations: bytecode executable program file cannot be opened; - -- too many open files. Try running with OCAMLRUNPARAM=b=2)`],pD="Fun.Finally_raised: ",pB="Stdlib.Fun.Finally_raised",pH="x",pO="Hashtbl: unsupported hash table format",pK=e,qz=[3,0,3],qA=a$,qt=kt,qu=" ",yf=[0,0],yd=[0,0],ye=[0,80,"Update"],x$=e,ya=e,yb=[0,80,[0,"cell-edit-btn"]],yc="\xE2\x9C\x8F\xEF\xB8\x8F",yi=[0,80,[0,"cell-edit-overlay"]],yj=[0,80,[0,fF]],xW="GET",xV=[0,c,419,17],xU=[0,c,434,11],xZ=[0,c,449,19],xY=[0,c,kB,13],xX=[0,c,439,13],x0=[0,c,466,11],x6=[0,c,484,19],x5=[0,c,479,19],x1=[0,c,472,13],x3=[0,c,488,15],x4=[0,c,ky,15],x2=[0,c,493,11],x8=e,x9=[0,c,505,17],x7=[0,c,508,11],xP=cq,xQ=jY,xJ="New column kind:",xH=[0,c,294,13],xD=dK,xE=bW,xF=dH,xG=cs,xz="Old value:",xA="Action: delete",xB="Key:",xC=[0,c,219,15],xy="On_change",xx=[0,c,144,22],xv="[blit v(%i) %i %i v'(%i)]",xs=[0,c,87,18],xp="PEERS",xn="STATUS",xl=[0,"SYNCED!",0],xh="modules/cursors",xi=[0,[0,"wss://p2p.u31.fr",0]],xj="testroom5267564",xk="zedoc",xm="synced",xo="status",xq="peers",xM=cq,xN=jY,y7=[0,80,"Add table"],y_=[0,80,[0,jw]];function z(a10){if(typeof a10=="number")return 0;switch(a10[0]){case 0:return[0,z(a10[1])];case 1:return[1,z(a10[1])];case 2:return[2,z(a10[1])];case 3:return[3,z(a10[1])];case 4:return[4,z(a10[1])];case 5:return[5,z(a10[1])];case 6:return[6,z(a10[1])];case 7:return[7,z(a10[1])];case 8:var c10=a10[1];return[8,c10,z(a10[2])];case 9:var b10=a10[1];return[9,b10,b10,z(a10[3])];case 10:return[10,z(a10[1])];case 11:return[11,z(a10[1])];case 12:return[12,z(a10[1])];case 13:return[13,z(a10[1])];default:return[14,z(a10[1])]}}function W(a10,b10){if(typeof a10=="number")return b10;switch(a10[0]){case 0:return[0,W(a10[1],b10)];case 1:return[1,W(a10[1],b10)];case 2:return[2,W(a10[1],b10)];case 3:return[3,W(a10[1],b10)];case 4:return[4,W(a10[1],b10)];case 5:return[5,W(a10[1],b10)];case 6:return[6,W(a10[1],b10)];case 7:return[7,W(a10[1],b10)];case 8:var c10=a10[1];return[8,c10,W(a10[2],b10)];case 9:var d10=a10[2],e10=a10[1];return[9,e10,d10,W(a10[3],b10)];case 10:return[10,W(a10[1],b10)];case 11:return[11,W(a10[1],b10)];case 12:return[12,W(a10[1],b10)];case 13:return[13,W(a10[1],b10)];default:return[14,W(a10[1],b10)]}}function w(a10,b10){if(typeof a10=="number")return b10;switch(a10[0]){case 0:return[0,w(a10[1],b10)];case 1:return[1,w(a10[1],b10)];case 2:var c10=a10[1];return[2,c10,w(a10[2],b10)];case 3:var d10=a10[1];return[3,d10,w(a10[2],b10)];case 4:var e10=a10[3],f10=a10[2],g10=a10[1];return[4,g10,f10,e10,w(a10[4],b10)];case 5:var h10=a10[3],i10=a10[2],j10=a10[1];return[5,j10,i10,h10,w(a10[4],b10)];case 6:var k10=a10[3],l10=a10[2],m10=a10[1];return[6,m10,l10,k10,w(a10[4],b10)];case 7:var n10=a10[3],o10=a10[2],p10=a10[1];return[7,p10,o10,n10,w(a10[4],b10)];case 8:var q10=a10[3],r10=a10[2],s10=a10[1];return[8,s10,r10,q10,w(a10[4],b10)];case 9:var t10=a10[1];return[9,t10,w(a10[2],b10)];case 10:return[10,w(a10[1],b10)];case 11:var u10=a10[1];return[11,u10,w(a10[2],b10)];case 12:var v10=a10[1];return[12,v10,w(a10[2],b10)];case 13:var x10=a10[2],y10=a10[1];return[13,y10,x10,w(a10[3],b10)];case 14:var z10=a10[2],A2=a10[1];return[14,A2,z10,w(a10[3],b10)];case 15:return[15,w(a10[1],b10)];case 16:return[16,w(a10[1],b10)];case 17:var B2=a10[1];return[17,B2,w(a10[2],b10)];case 18:var C2=a10[1];return[18,C2,w(a10[2],b10)];case 19:return[19,w(a10[1],b10)];case 20:var D2=a10[2],E2=a10[1];return[20,E2,D2,w(a10[3],b10)];case 21:var F2=a10[1];return[21,F2,w(a10[2],b10)];case 22:return[22,w(a10[1],b10)];case 23:var G2=a10[1];return[23,G2,w(a10[2],b10)];default:var H2=a10[2],I2=a10[1];return[24,I2,H2,w(a10[3],b10)]}}function d4(a10){return[0,a10]}function cG(a10){return a10[1]}function d5(a10,b10,c10){return a10[1]===b10?(a10[1]=c10,1):0}function aK(a10){throw g([0,b3,a10],1)}function t(a10){throw g([0,cH,a10],1)}function cI(a10){return 0<=a10?a10:-a10|0}var gs=kz;function ay(a10,b10){return a10+b10}function lt(b10){var e10=n(b10);return function(a10){for(var c10=a10;;){if(e10<=c10)return ay(b10,lu);var d10=y(b10,c10);a:{if(48<=d10){if(58>d10)break a}else if(d10===45)break a;return b10}c10=c10+1|0}}(0)}function gt(a10,b10){if(!a10)return b10;var c10=a10[1];return[0,c10,gt(a10[2],b10)]}z2(0);var lw=lb(1),at=lb(2);function b5(a10,b10){gg(a10,b10,0,n(b10))}function gu(a10){return b5(at,a10),lc(at,10),bz(at)}var d7=d4(function(a10){return function(a11){for(var b10=a11;;){if(!b10)return 0;var d10=b10[2],e10=b10[1];try{bz(e10)}catch(f10){var c10=L(f10);if(c10[1]!==gr)throw g(c10,0)}b10=d10}}(z3(0))});function d8(a10){return h(cG(d7),0)}gl(j3,d8);function lp(a10){return a10^-1}function lq(a10){return a10?lr:ls}function lv(a10){return lt(f9("%.12g",a10))}function lx(a10,b10,c10,d10){return 0<=c10&&0<=d10&&(n(b10)-d10|0)>=c10?gg(a10,b10,c10,d10):t(ly)}function lz(c10){for(;;){var d10=d4(1),a10=cG(d7);let e10=d10,f10=a10;var b10=1-d5(d7,a10,function(a11){return d5(e10,1,0)&&h(c10,0),h(f10,0)});if(!b10)return b10}}function cJ(a10){return bz(a10)}function lA(a10,b10){lc(a10,b10)}var d9=Af(0),b6=(4*d9|0)-1|0;function lB(a10){return 1-(typeof a10=="number"?1:0)}var lD=[q,lC,ae(0)];function lE(a10){throw g(lD,1)}function cK(a10){var d10=a10[1];a10[1]=lE;try{var c10=h(d10,0);return z9(a10,c10),c10}catch(f10){var b10=L(f10);throw a10[1]=function(a11){throw g(b10,0)},g(b10,0)}}function lF(a10){var b10=aw(a10);return b10!==aD&&b10!==ba&&b10!==kl?a10:zU(a10)}function cL(a10){return a10?a10[1]:t(lG)}function gv(a10){return a10?1:0}function lH(a10,b10){return b10?[0,h(a10,b10[1])]:0}function lI(a10,b10){return a10===b10?1:0}function lJ(a10){a:{if(40<=a10){if(a10===92)return lK;if(fZ>a10)break a}else{if(32<=a10){if(39<=a10)return lL;break a}if(14>a10)switch(a10){case 8:return lM;case 9:return lN;case 10:return lO;case 13:return lP}}var b10=F(4);return A(b10,0,92),A(b10,1,48+(a10/fI|0)|0),A(b10,2,48+((a10/10|0)%10|0)|0),A(b10,3,48+(a10%10|0)|0),d1(b10)}var c10=F(1);return A(c10,0,a10),d1(c10)}function lQ(a10){return 25>>0?a10:a10+kH|0}function lR(a10,b10){for(var d10=a10,c10=b10;;){if(!c10)return d10;d10=d10+1|0,c10=c10[2]}}function gw(a10){return lR(0,a10)}function bB(a10,b10){for(var c10=a10,d10=b10;;){if(!c10)return d10;var e10=[0,c10[1],d10];c10=c10[2],d10=e10}}function a3(a10){return bB(a10,0)}function gx(a10,b10,c10){if(b10<=a10)return 0;var d10=h(c10,a10);return[0,d10,gx(a10+1|0,b10,c10)]}function lS(a10,b10){return[0,a10,b10]}function lT(a10){return a10?a10[1]:aK(lU)}function lV(a10,b10,c10,d10){for(var f10=a10,e10=b10;;){if(c10<=e10)return f10;f10=[0,h(d10,e10),f10],e10=e10+1|0}}function d_(a10){if(!a10)return 0;var b10=a10[1];return gt(b10,d_(a10[2]))}function cM(a10,b10){if(!b10)return 0;var c10=b10[2],d10=h(a10,b10[1]);return[0,d10,cM(a10,c10)]}function a4(a10,b10){for(var c10=b10;;){if(!c10)return 0;var d10=c10[2];h(a10,c10[1]),c10=d10}}function gy(a10,b10,c10){for(var e10=b10,d10=c10;;){if(!d10)return e10;var f10=d10[2];e10=i(a10,e10,d10[1]),d10=f10}}function lW(a10,b10){return 0<=a10?50>1,s10=p10(r10,b11),D2=s10[1],t10=p10(a11-r10|0,s10[2]),E2=t10[2];return[0,B2(D2,t10[1],0),E2]}function p10(a11,b11){if(a11===2){if(b11){var j10=b11[2];if(j10){var k10=j10[1],g10=b11[1],B3=j10[2],q10=i(d10,g10,k10),C2=q10===0?[0,g10,0]:0>1,s10=h10(r10,b11),D2=s10[1],t10=h10(a11-r10|0,s10[2]),E2=t10[2];return[0,A2(D2,t10[1],0),E2]}var a10=gw(b10);return 2<=a10?h10(a10,b10)[1]:b10}function gz(a10,b10){return b10<=a10?a10:b10}function gA(a10){return e+a10}function l3(a10,b10){return k7(a10,b10)}function l4(a10,b10){return a10<=b10?a10:b10}function bh(a10,b10){var c10=F(a10);return zt(c10,0,a10,b10),c10}var l5=F(0);function gB(a10){var b10=aq(a10),c10=F(b10);return aZ(a10,0,c10,0,b10),c10}function d$(a10,b10,c10){if(0<=b10&&0<=c10&&(aq(a10)-c10|0)>=b10){var d10=F(c10);return aZ(a10,b10,d10,0,c10),d10}return t(l7)}function ea(a10,b10,c10){return d1(d$(a10,b10,c10))}function gC(a10,b10,c10,d10,e10){if(0<=e10&&0<=b10&&(aq(a10)-e10|0)>=b10&&0<=d10&&(aq(c10)-e10|0)>=d10){aZ(a10,b10,c10,d10,e10);return}return t(l8)}function aL(a10,b10,c10,d10,e10){if(0<=e10&&0<=b10&&(n(a10)-e10|0)>=b10&&0<=d10&&(aq(c10)-e10|0)>=d10){cy(a10,b10,c10,d10,e10);return}return t(l9)}function gD(a10){var b10=a10-9|0;a:{if(4>>0){if(b10!==23)break a}else if(b10===2)break a;return 1}return 0}function ma(a10,b10){var d10=aq(b10);if(d10===0)return b10;var e10=F(d10),f10=d10-1|0,g10=0;if(f10>=0)for(var c10=g10;;){A(e10,c10,h(a10,bY(b10,c10)));var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function gE(a10,b10,c10){zo(a10,b10,zG(c10))}function gF(a10,b10,c10){a0(a10,b10,c10)}function gG(a10,b10){return zn(a10,b10)}function cN(a10){return bd(a10)}function $(a10){return d1(a10)}function l6(a10){return gB(bd(a10))}function l_(a10){for(var d10=aq(a10),b10=[0,0];!(b10[1]>=d10||!gD(bY(a10,b10[1])));)b10[1]++;for(var c10=[0,d10-1|0];;){if(b10[1]<=c10[1]&&gD(bY(a10,c10[1]))){c10[1]--;continue}return b10[1]<=c10[1]?d$(a10,b10[1],(c10[1]-b10[1]|0)+1|0):l5}}function l$(a10){var b10=[0,0],j10=aq(a10)-1|0,l10=0;if(j10>=0)for(var g10=l10;;){var e10=bY(a10,g10);a:{b:{c:{if(32<=e10){var h10=e10-34|0;if(58>>0){if(93<=h10)break c}else if(56>>0)break b;var i10=1;break a}if(11<=e10){if(e10===13)break b}else if(8<=e10)break b}var i10=4;break a}var i10=2}b10[1]=b10[1]+i10|0;var o10=g10+1|0;if(j10===g10)break;g10=o10}if(b10[1]===aq(a10))return gB(a10);var c10=F(b10[1]);b10[1]=0;var k10=aq(a10)-1|0,m10=0;if(k10>=0)for(var f10=m10;;){var d10=bY(a10,f10);a:{b:{c:{if(35<=d10){if(d10!==92){if(fZ<=d10)break c;break b}}else{if(32>d10){if(14<=d10)break c;switch(d10){case 8:A(c10,b10[1],92),b10[1]++,A(c10,b10[1],98);break a;case 9:A(c10,b10[1],92),b10[1]++,A(c10,b10[1],116);break a;case 10:A(c10,b10[1],92),b10[1]++,A(c10,b10[1],110);break a;case 13:A(c10,b10[1],92),b10[1]++,A(c10,b10[1],114);break a;default:break c}}if(34>d10)break b}A(c10,b10[1],92),b10[1]++,A(c10,b10[1],d10);break a}A(c10,b10[1],92),b10[1]++,A(c10,b10[1],48+(d10/fI|0)|0),b10[1]++,A(c10,b10[1],48+((d10/10|0)%10|0)|0),b10[1]++,A(c10,b10[1],48+(d10%10|0)|0);break a}A(c10,b10[1],d10)}b10[1]++;var n10=f10+1|0;if(k10===f10)break;f10=n10}return c10}function mb(a10){return ma(lQ,a10)}function cO(a10,b10){return $(bh(a10,b10))}function eb(a10,b10,c10){return $(d$(cN(a10),b10,c10))}function gH(a10){var b10=a10-9|0;a:{if(4>>0){if(b10!==23)break a}else if(b10===2)break a;return 1}return 0}function me(a10,b10,c10,d10){for(var e10=c10;;){if(b10<=e10)throw g(ax,1);if(_(a10,e10)===d10)return e10;e10=e10+1|0}}function mf(a10,b10,c10){var d10=n(a10);if(0<=b10&&d10>=b10)try{me(a10,d10,b10,c10);var f10=1;return f10}catch(f11){var e10=L(f11);if(e10===ax)return 0;throw g(e10,0)}return t(mg)}function ec(a10,b10){return lh(a10,b10)}function mc(a10){return a10==e||!gH(_(a10,0))&&!gH(_(a10,n(a10)-1|0))?a10:$(l_(cN(a10)))}function md(a10){return function(a11,b10,c10){for(var d10=c10;;){if(b10<=d10)return a11;var e10=_(a11,d10)+kH|0;a:{if(59>>0){if(33>>0)break a}else if(e10===2)break a;d10=d10+1|0;continue}return $(l$(cN(a11)))}}(a10,n(a10),0)}function mh(a10,b10){return mf(a10,0,b10)}function mi(a10){return $(mb(cN(a10)))}function mj(a10,b10){return a10==b10?1:0}function gI(a10,b10){if(a10===0)return[0];if(0>a10)return t(mk);var d10=ap(a10,h(b10,0)),e10=a10-1|0,f10=1;if(e10>=1)for(var c10=f10;;){d10[1+c10]=h(b10,c10);var g10=c10+1|0;if(e10===c10)break;c10=g10}return d10}function cP(a10,b10,c10,d10,e10){return 0<=e10&&0<=b10&&(a10.length-1-e10|0)>=b10&&0<=d10&&(c10.length-1-e10|0)>=d10?zh(a10,b10,c10,d10,e10):t(mn)}function gJ(a10,b10){var d10=b10.length-2|0,e10=0;if(d10>=0)for(var c10=e10;;){h(a10,b10[1+c10]);var f10=c10+1|0;if(d10===c10)break;c10=f10}return 0}function gK(a10,b10){var d10=b10.length-1;if(d10===0)return[0];var e10=ap(d10,h(a10,b10[1])),f10=d10-1|0,g10=1;if(f10>=1)for(var c10=g10;;){e10[1+c10]=h(a10,b10[1+c10]);var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function mo(a10,b10){for(var d10=a10,c10=b10;;){if(!c10)return d10;d10=d10+1|0,c10=c10[2]}}function gL(a10){if(!a10)return[0];var b10=a10[2],c10=a10[1],e10=ap(mo(0,a10),c10);return function(a11,b11){for(var d10=a11,c11=b11;;){if(!c11)return e10;var f10=c11[2];e10[1+d10]=c11[1],d10=d10+1|0,c11=f10}}(1,b10)}function ml(a10,b10,c10){return 0<=b10&&0<=c10&&(a10.length-1-c10|0)>=b10?zi(a10,b10,c10):t(mm)}function mp(k10){function j10(a10){return a10?a10[4]:0}function d10(a10,b11,c11){var d11=a10?a10[4]:0,e11=c11?c11[4]:0,f10=e11<=d11?d11+1|0:e11+1|0;return[0,a10,b11,c11,f10]}function l10(a10,b11,c11){var g10=a10?a10[4]:0,h10=c11?c11[4]:0;if((h10+2|0)=h10){var w10=h10<=g10?g10+1|0:h10+1|0;return[0,a10,b11,c11,w10]}if(!c11)return t(mt);var k11=c11[3],m11=c11[2],f10=c11[1],r10=j10(f10);if(r10<=j10(k11))return d10(d10(a10,b11,f10),m11,k11);if(!f10)return t(ms);var s10=f10[2],u10=f10[1],v10=d10(f10[3],m11,k11);return d10(d10(a10,b11,u10),s10,v10)}function c10(a10,b11){if(!b11)return[0,0,a10,0,1];var d11=b11[3],e11=b11[2],f10=b11[1],g10=i(k10[1],a10,e11);if(g10===0)return b11;if(0<=g10){var h10=c10(a10,d11);return d11===h10?b11:l10(f10,e11,h10)}var j11=c10(a10,f10);return f10===j11?b11:l10(j11,e11,d11)}function b10(a10){return[0,0,a10,0,1]}var m10=0;function e10(a10,b11){for(var c11=b11;;){if(!c11)return;var d11=c11[3],f10=c11[2];e10(a10,c11[1]),h(a10,f10),c11=d11}}function n10(a10,b11){for(var d11=a10,c11=b11;;){if(!c11)return d11;var e11=c11[2],f10=c11[1];d11=[0,e11,n10(d11,c11[3])],c11=f10}}function o10(a10,b11,c11){for(var d11=c11;;){if(!d11)return;var e11=d11[3],f10=d11[1];d11=h(b11,d11[2])?e11:f10}}function p10(a10){function c11(a11,b11){if(3>=a11>>>0)switch(a11){case 0:return[0,0,b11];case 1:if(b11)return[0,[0,0,b11[1],0,1],b11[2]];break;case 2:if(b11){var h10=b11[2];if(h10)return[0,[0,[0,0,b11[1],0,1],h10[1],0,2],h10[2]]}break;default:if(b11){var i10=b11[2];if(i10){var j11=i10[2];if(j11)return[0,[0,[0,0,b11[1],0,1],i10[1],[0,0,j11[1],0,1],2],j11[2]]}}}var k11=a11/2|0,l11=c11(k11,b11),e11=l11[2],n11=l11[1];if(!e11)throw g([0,f,mu],1);var o11=e11[1],m11=c11((a11-k11|0)-1|0,e11[2]),p11=m11[2];return[0,d10(n11,o11,m11[1]),p11]}return c11(gw(a10),a10)[1]}return[0,,,,c10,,,,,,,,,,,,,m10,,,,,,,,,,,,,,e10,,,,,,,,function(a10){return n10(0,a10)},,,,,,,,,,,function(a10,b11){for(var c11=b11;;){if(!c11)return;var d11=c11[2],e11=c11[3],f10=c11[1];if(h(a10,d11))return o10(d11,a10,e11);c11=f10}},,,,,,,function(a10){if(!a10)return m10;var f10=a10[2],d11=a10[1];if(!f10)return b10(d11);var g10=f10[2],e11=f10[1];if(!g10)return c10(e11,b10(d11));var h10=g10[2],i10=g10[1];if(!h10)return c10(i10,c10(e11,b10(d11)));var j11=h10[2],l11=h10[1];if(!j11)return c10(l11,c10(i10,c10(e11,b10(d11))));if(j11[2])return p10(l2(k10[1],a10));var n11=j11[1];return c10(n11,c10(l11,c10(i10,c10(e11,b10(d11)))))}]}function mv(a10){var b10=mp(a10);return[0,b10[17],,,b10[4],,,,,,,,,,b10[31],,,,,,,,,b10[39],,,,,,,,,,,,,b10[50],b10[57]]}function mw(f10){function h10(a10){return a10?a10[5]:0}function e10(a10,b10,c11,d11){var e11=h10(a10),f11=h10(d11),g10=f11<=e11?e11+1|0:f11+1|0;return[0,a10,b10,c11,d11,g10]}function d10(a10,b10,c11,d11){var i10=a10?a10[5]:0,j11=d11?d11[5]:0;if((j11+2|0)=j11){var B2=j11<=i10?i10+1|0:j11+1|0;return[0,a10,b10,c11,d11,B2]}if(!d11)return t(mA);var l11=d11[4],o11=d11[3],p10=d11[2],g10=d11[1],w10=h10(g10);if(w10<=h10(l11))return e10(e10(a10,b10,c11,g10),p10,o11,l11);if(!g10)return t(mz);var x10=g10[3],y10=g10[2],z10=g10[1],A2=e10(g10[4],p10,o11,l11);return e10(e10(a10,b10,c11,z10),y10,x10,A2)}function j10(a10,b10,c11){if(!c11)return[0,0,a10,b10,0,1];var e11=c11[4],h11=c11[3],k11=c11[2],g10=c11[1],o11=c11[5],l11=i(f10[1],a10,k11);if(l11===0)return h11===b10?c11:[0,g10,a10,b10,e11,o11];if(0<=l11){var m11=j10(a10,b10,e11);return e11===m11?c11:d10(g10,k11,h11,m11)}var n11=j10(a10,b10,g10);return g10===n11?c11:d10(n11,k11,h11,e11)}function n10(a10){for(var b10=a10;;){if(!b10)throw g(ax,1);var c11=b10[1];if(!c11)return[0,b10[2],b10[3]];b10=c11}}function c10(a10){if(!a10)return t(mB);var b10=a10[1];if(!b10)return a10[4];var e11=a10[4],f11=a10[3],g10=a10[2];return d10(c10(b10),g10,f11,e11)}function o10(a10,b10){if(!a10)return b10;if(!b10)return a10;var e11=n10(b10),f11=e11[2],g10=e11[1];return d10(a10,g10,f11,c10(b10))}function k10(a10,b10){if(!b10)return 0;var c11=b10[4],h11=b10[3],g10=b10[2],e11=b10[1],j11=i(f10[1],a10,g10);if(j11===0)return o10(e11,c11);if(0<=j11){var l11=k10(a10,c11);return c11===l11?b10:d10(e11,g10,h11,l11)}var m11=k10(a10,e11);return e11===m11?b10:d10(m11,g10,h11,c11)}function l10(a10,b10){for(var c11=b10;;){if(!c11)return 0;var d11=c11[4],e11=c11[3],f11=c11[2];l10(a10,c11[1]),i(a10,f11,e11),c11=d11}}function m10(a10,b10,c11){for(var d11=b10,e11=c11;;){if(!d11)return e11;var f11=d11[4],g10=d11[3],h11=d11[2],i10=x(a10,h11,g10,m10(a10,d11[1],e11));d11=f11,e11=i10}}return[0,,,,,0,,j10,function(a10,b10){for(var c11=b10;;){if(!c11)throw g(ax,1);var e11=c11[4],h11=c11[3],j11=c11[1],d11=i(f10[1],a10,c11[2]);if(d11===0)return h11;var k11=0<=d11?e11:j11;c11=k11}},,,,,,,,,function(a10,b10){for(var c11=b10;;){if(!c11)return 0;var e11=c11[4],g10=c11[3],h11=c11[1],d11=i(f10[1],a10,c11[2]);if(d11===0)return[0,g10];var j11=0<=d11?e11:h11;c11=j11}},,,,,,,k10,,l10,,,m10]}function ed(a10){var b10=mw(a10);return[0,b10[5],,,b10[7],,,b10[24],,,,,b10[26],b10[29],,,,,,,,,,,,,,,b10[8],b10[17]]}var ee=[q,mC,ae(0)];function bC(a10){return[0,0,0]}function b7(a10){a10[1]=0,a10[2]=0}function a5(a10,b10){return b10[1]=[0,a10,b10[1]],b10[2]=b10[2]+1|0,0}function bD(a10){var b10=a10[1];if(!b10)return 0;var c10=b10[1];return a10[1]=b10[2],a10[2]=a10[2]-1|0,[0,c10]}function bE(a10){var b10=a10[1];return b10?[0,b10[1]]:0}function mD(a10){var b10=a10[1];if(!b10)throw g(ee,1);a10[1]=b10[2],a10[2]=a10[2]-1|0}function mE(a10){if(!a10[1])throw g(ee,1)}function mF(a10,b10){return a4(a10,b10[1])}var mH=[q,mG,ae(0)];function ef(a10){return[0,0,0,0]}function eg(a10){a10[1]=0,a10[2]=0,a10[3]=0}function eh(a10,b10){var c10=[0,a10,0],d10=b10[3];return d10?(b10[1]=b10[1]+1|0,d10[2]=c10,b10[3]=c10,0):(b10[1]=1,b10[2]=c10,b10[3]=c10,0)}function gM(a10){var b10=a10[2];if(!b10)throw g(mH,1);var c10=b10[1];if(b10[2]){var d10=b10[2];return a10[1]=a10[1]-1|0,a10[2]=d10,c10}return eg(a10),c10}function ei(a10){return a10[1]===0?1:0}function mI(a10){var b10=a10[2];return b10?[0,b10[1]]:0}function mJ(a10){var b10=a10[2];if(!b10)return 0;var c10=b10[1];if(b10[2]){var d10=b10[2];return a10[1]=a10[1]-1|0,a10[2]=d10,[0,c10]}return eg(a10),[0,c10]}function b8(a10){var b10=1<=a10?a10:1,c10=b6=(d10+b10|0));)c10[1]=2*c10[1]|0;b6a10[3])throw g([0,f,mO],1);if(!((d10+b10|0)<=a10[3]))throw g([0,f,mN],1)}function b9(a10,b10){var c10=n(b10),d10=a10[2]+c10|0;a10[3]=b10?ea(a10[1],b10,c10):t(mL)}function mM(a10){return a10[2]}function mQ(a10,b10){var c10=a10[2];a10[3]<=c10&&ej(a10,1),A(a10[1],c10,b10),a10[2]=c10+1|0}function mR(a10,b10,c10,d10){var e10=c10<0?1:0;if(e10)var f10=e10;else var h10=d10<0?1:0,f10=h10||((n(b10)-d10|0)e10){if(e10!==32){if(43>e10)break a;switch(e10-43|0){case 5:c:if(c10<(d10+2|0)&&1=(d10+1|0))break a;var f10=bh(d10+1|0,48);return a0(f10,0,e10),aL(b10,1,f10,(d10-c10|0)+2|0,c10-1|0),$(f10)}if(71<=e10){if(5>>0)break a}else if(65>e10)break a}if(c10a10)return b10;var h10=[0,0],i10=n(b10)-1|0,o10=0;if(i10>=0)for(var d10=o10;;){9>=_(b10,d10)+kd>>>0&&h10[1]++;var r10=d10+1|0;if(i10===d10)break;d10=r10}var j10=h10[1],k10=F(n(b10)+((j10-1|0)/3|0)|0),l10=[0,0];function e10(a11){a0(k10,l10[1],a11),l10[1]++}var f10=[0,((j10-1|0)%3|0)+1|0],m10=n(b10)-1|0,p10=0;if(m10>=0)for(var c10=p10;;){var g10=_(b10,c10);9>>0||(f10[1]===0&&(e10(95),f10[1]=3),f10[1]--),e10(g10);var q10=c10+1|0;if(m10===c10)break;c10=q10}return $(k10)}function ox(a10,b10){return cS(a10,dT(nE(a10),b10))}function oy(a10,b10){return cS(a10,dT(n6(a10),b10))}function oz(a10,b10){return cS(a10,dT(oi(a10),b10))}function oA(a10,b10){return cS(a10,zJ(nS(a10),b10))}function aM(d10,b10,c10){function a10(a11){switch(d10[1]){case 0:var e11=45;break;case 1:var e11=43;break;default:var e11=32}return zE(c10,b10,e11)}function e10(a11){var b11=zp(c10);return b11===3?c10<0?oC:oD:4<=b11?oE:a11}function f10(b11){var e11=n(b11);return function(a11){for(var c11=a11;;){if(c11===e11)return 0;var d11=y(b11,c11)-46|0;a:{if(23>>0){if(d11===55)break a}else if(21>>0)break a;c11=c11+1|0;continue}return 1}}(0)?b11:ay(b11,oB)}switch(d10[2]){case 5:return e10(f10(f9(gR(d10,b10),c10)));case 6:return a10(0);case 7:return mi(a10(0));case 8:return e10(a10(0));default:return f9(gR(d10,b10),c10)}}function oF(a10){var b10=lJ(a10),c10=n(b10),d10=bh(c10+2|0,39);return cy(b10,0,d10,1,c10),$(d10)}function oG(a10){var b10=gN(16);return el(b10,a10),gP(b10)}function co(a10,b10,c10,d10){for(var k10=b10,j10=c10,e10=d10;;){if(typeof e10=="number")return h(k10,j10);switch(e10[0]){case 0:var t10=e10[1];return function(a11){return o(k10,[5,j10,a11],t10)};case 1:var u10=e10[1];return function(a11){return o(k10,[4,j10,oF(a11)],u10)};case 2:return em(k10,j10,e10[2],e10[1],function(a11){return a11});case 3:return em(k10,j10,e10[2],e10[1],nD);case 4:return cT(k10,j10,e10[4],e10[2],e10[3],ox,e10[1]);case 5:return cT(k10,j10,e10[4],e10[2],e10[3],oy,e10[1]);case 6:return cT(k10,j10,e10[4],e10[2],e10[3],oz,e10[1]);case 7:return cT(k10,j10,e10[4],e10[2],e10[3],oA,e10[1]);case 8:return oH(k10,j10,e10[4],e10[2],e10[3],e10[1]);case 9:return em(k10,j10,e10[2],e10[1],lq);case 10:j10=[7,j10],e10=e10[1];break;case 11:j10=[2,j10,e10[1]],e10=e10[2];break;case 12:j10=[3,j10,e10[1]],e10=e10[2];break;case 13:var v10=e10[3],x10=oG(e10[2]);return function(a11){return o(k10,[4,j10,x10],v10)};case 14:var y10=e10[3],z10=e10[2];return function(a11){return o(k10,j10,w(nC(a11[1],z10),y10))};case 15:var A2=e10[1];return function(c11,b11){return o(k10,[6,j10,function(a11){return i(c11,a11,b11)}],A2)};case 16:var B2=e10[1];return function(a11){return o(k10,[6,j10,a11],B2)};case 17:j10=[0,j10,e10[1]],e10=e10[2];break;case 18:var l10=e10[1];if(l10[0]===0){let b11=j10,c11=k10,d11=e10[2];k10=function(a11){return o(c11,[1,b11,[0,a11]],d11)},j10=0,e10=l10[1][1]}else{let b11=j10,c11=k10,d11=e10[2];k10=function(a11){return o(c11,[1,b11,[1,a11]],d11)},j10=0,e10=l10[1][1]}break;case 19:throw g([0,f,oJ],1);case 20:var C2=e10[3],D2=[8,j10,oK];return function(a11){return o(k10,D2,C2)};case 21:var E2=e10[2];return function(a11){return o(k10,[4,j10,dT(j9,a11)],E2)};case 22:var F2=e10[1];return function(a11){return o(k10,[5,j10,a11],F2)};case 23:var m10=e10[2],n10=e10[1];return a10<50?ja(a10+1|0,k10,j10,n10,m10):r(ja,[0,k10,j10,n10,m10]);default:var p10=e10[3],q10=e10[1],s10=h(e10[2],0);return a10<50?fq(a10+1|0,k10,j10,p10,q10,s10):r(fq,[0,k10,j10,p10,q10,s10])}}}function o(a10,b10,c10){return bA(co(0,a10,b10,c10))}function ja(a10,b10,c10,d10,e10){if(typeof d10=="number")switch(d10){case 0:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 1:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 2:throw g([0,f,oL],1);default:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10])}switch(d10[0]){case 0:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 1:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 2:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 3:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 4:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 5:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 6:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 7:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 8:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 9:var h10=d10[2];return a10<50?fr(a10+1|0,b10,c10,h10,e10):r(fr,[0,b10,c10,h10,e10]);case 10:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);default:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10])}}function fr(a10,h10,c10,d10,e10){if(typeof d10=="number")return a10<50?s(a10+1|0,h10,c10,e10):r(s,[0,h10,c10,e10]);switch(d10[0]){case 0:var b10=d10[1];return function(a11){return af(h10,c10,b10,e10)};case 1:var i10=d10[1];return function(a11){return af(h10,c10,i10,e10)};case 2:var j10=d10[1];return function(a11){return af(h10,c10,j10,e10)};case 3:var k10=d10[1];return function(a11){return af(h10,c10,k10,e10)};case 4:var l10=d10[1];return function(a11){return af(h10,c10,l10,e10)};case 5:var m10=d10[1];return function(a11){return af(h10,c10,m10,e10)};case 6:var n10=d10[1];return function(a11){return af(h10,c10,n10,e10)};case 7:var o10=d10[1];return function(a11){return af(h10,c10,o10,e10)};case 8:var p10=d10[2];return function(a11){return af(h10,c10,p10,e10)};case 9:var q10=d10[3],t10=d10[2],u10=I(D(d10[1]),t10);return function(a11){return af(h10,c10,W(u10,q10),e10)};case 10:var v10=d10[1];return function(a11,b11){return af(h10,c10,v10,e10)};case 11:var w10=d10[1];return function(a11){return af(h10,c10,w10,e10)};case 12:var x10=d10[1];return function(a11){return af(h10,c10,x10,e10)};case 13:throw g([0,f,oM],1);default:throw g([0,f,oN],1)}}function af(a10,b10,c10,d10){return bA(fr(0,a10,b10,c10,d10))}function s(a10,b10,c10,d10){var e10=[8,c10,oO];return a10<50?co(a10+1|0,b10,e10,d10):r(co,[0,b10,e10,d10])}function em(g10,f10,c10,d10,e10){if(typeof d10=="number")return function(a10){return o(g10,[4,f10,h(e10,a10)],c10)};if(d10[0]===0){var b10=d10[2],i10=d10[1];return function(a10){return o(g10,[4,f10,ab(i10,b10,h(e10,a10))],c10)}}var j10=d10[1];return function(a10,b11){return o(g10,[4,f10,ab(j10,a10,h(e10,b11))],c10)}}function cT(k10,j10,h10,d10,e10,f10,g10){if(typeof d10=="number"){if(typeof e10=="number")return e10?function(a10,b11){return o(k10,[4,j10,bG(a10,i(f10,g10,b11))],h10)}:function(a10){return o(k10,[4,j10,i(f10,g10,a10)],h10)};var b10=e10[1];return function(a10){return o(k10,[4,j10,bG(b10,i(f10,g10,a10))],h10)}}if(d10[0]===0){var c10=d10[2],l10=d10[1];if(typeof e10=="number")return e10?function(a10,b11){return o(k10,[4,j10,ab(l10,c10,bG(a10,i(f10,g10,b11)))],h10)}:function(a10){return o(k10,[4,j10,ab(l10,c10,i(f10,g10,a10))],h10)};var n10=e10[1];return function(a10){return o(k10,[4,j10,ab(l10,c10,bG(n10,i(f10,g10,a10)))],h10)}}var m10=d10[1];if(typeof e10=="number")return e10?function(a10,b11,c11){return o(k10,[4,j10,ab(m10,a10,bG(b11,i(f10,g10,c11)))],h10)}:function(a10,b11){return o(k10,[4,j10,ab(m10,a10,i(f10,g10,b11))],h10)};var p10=e10[1];return function(a10,b11){return o(k10,[4,j10,ab(m10,a10,bG(p10,i(f10,g10,b11)))],h10)}}function oH(i10,h10,g10,d10,e10,f10){if(typeof d10=="number"){if(typeof e10=="number")return e10?function(a10,b11){return o(i10,[4,h10,aM(f10,a10,b11)],g10)}:function(a10){return o(i10,[4,h10,aM(f10,ek(f10),a10)],g10)};var b10=e10[1];return function(a10){return o(i10,[4,h10,aM(f10,b10,a10)],g10)}}if(d10[0]===0){var c10=d10[2],j10=d10[1];if(typeof e10=="number")return e10?function(a10,b11){return o(i10,[4,h10,ab(j10,c10,aM(f10,a10,b11))],g10)}:function(a10){return o(i10,[4,h10,ab(j10,c10,aM(f10,ek(f10),a10))],g10)};var l10=e10[1];return function(a10){return o(i10,[4,h10,ab(j10,c10,aM(f10,l10,a10))],g10)}}var k10=d10[1];if(typeof e10=="number")return e10?function(a10,b11,c11){return o(i10,[4,h10,ab(k10,a10,aM(f10,b11,c11))],g10)}:function(a10,b11){return o(i10,[4,h10,ab(k10,a10,aM(f10,ek(f10),b11))],g10)};var m10=e10[1];return function(a10,b11){return o(i10,[4,h10,ab(k10,a10,aM(f10,m10,b11))],g10)}}function fq(a10,b10,c10,d10,e10,f10){if(e10){var i10=e10[1];return function(a11){return oI(b10,c10,d10,i10,h(f10,a11))}}var g10=[4,c10,f10];return a10<50?co(a10+1|0,b10,g10,d10):r(co,[0,b10,g10,d10])}function oI(a10,b10,c10,d10,e10){return bA(fq(0,a10,b10,c10,d10,e10))}function aN(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;switch(c10[0]){case 0:var f10=c10[1],g10=gQ(c10[2]);return aN(a10,f10),b5(a10,g10);case 1:var d10=c10[2],e10=c10[1];if(d10[0]===0){var i10=d10[1];aN(a10,e10),b5(a10,oP),c10=i10}else{var j10=d10[1];aN(a10,e10),b5(a10,oQ),c10=j10}break;case 6:var m10=c10[2];return aN(a10,c10[1]),h(m10,a10);case 7:return aN(a10,c10[1]),cJ(a10);case 8:var n10=c10[2];return aN(a10,c10[1]),t(n10);case 2:case 4:var k10=c10[2];return aN(a10,c10[1]),b5(a10,k10);default:var l10=c10[2];return aN(a10,c10[1]),lA(a10,l10)}}}function aO(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;switch(c10[0]){case 0:var f10=c10[1],g10=gQ(c10[2]);return aO(a10,f10),b9(a10,g10);case 1:var d10=c10[2],e10=c10[1];if(d10[0]===0){var i10=d10[1];aO(a10,e10),b9(a10,oR),c10=i10}else{var j10=d10[1];aO(a10,e10),b9(a10,oS),c10=j10}break;case 6:var m10=c10[2];return aO(a10,c10[1]),b9(a10,h(m10,0));case 7:c10=c10[1];break;case 8:var n10=c10[2];return aO(a10,c10[1]),t(n10);case 2:case 4:var k10=c10[2];return aO(a10,c10[1]),b9(a10,k10);default:var l10=c10[2];return aO(a10,c10[1]),mQ(a10,l10)}}}function oT(a10){var c10=a10[1],b10=b8(cv);return o(function(a11){return aO(b10,a11),aK(cQ(b10))},0,c10)}function oU(c10){if(c10==e)return oV;var f10=n(c10);function j10(a11){return h(oT(oW),c10)}function k10(a11){for(var b11=a11;;){if(b11===f10)return b11;var d11=y(c10,b11);if(d11!==9&&d11!==32)return b11;b11=b11+1|0}}var i10=k10(0),o10=function(a11,b11){for(var d11=b11;;){if(d11===f10||25>>0)return d11;d11=d11+1|0}}(i10,i10),a10=eb(c10,i10,o10-i10|0),d10=k10(o10),l10=function(a11,b11){for(var d11=b11;;){if(d11===f10)return d11;var e10=y(c10,d11);a:{if(48<=e10){if(58>e10)break a}else if(e10===45)break a;return d11}d11=d11+1|0}}(d10,d10);if(d10===l10)var m10=0;else try{var r10=k8(eb(c10,d10,l10-d10|0)),m10=r10}catch(f11){var p10=L(f11);if(p10[1]!==b3)throw g(p10,0);var q10=j10(0),m10=q10}k10(l10)!==f10&&j10(0);a:{if(a10!==e&&a10!==jq){if(a10==="h"){var b10=0;break a}if(a10==="hov"){var b10=3;break a}if(a10==="hv"){var b10=2;break a}if(a10!=="v"){var b10=j10(0);break a}var b10=1;break a}var b10=4}return[0,m10,b10]}function oX(d10,b10,c10){return o(function(a10){return aN(b10,a10),h(d10,b10)},0,c10[1])}function cU(a10,b10){return oX(function(a11){return 0},a10,b10)}function en(a10){return cU(at,a10)}function eo(c10,b10){return o(function(a10){var b11=b8(64);return aO(b11,a10),h(c10,cQ(b11))},0,b10[1])}function B(a10){return eo(function(a11){return a11},a10)}var ep=d4(0);function er(a10,b10){var c10=a10[1+b10];return lB(c10)?aw(c10)===dC?h(B(oY),c10):aw(c10)===kl?lv(c10):oZ:h(B(o0),c10)}function gS(a10,b10){if(a10.length-1<=b10)return o1;var c10=gS(a10,b10+1|0),d10=er(a10,b10);return i(B(o2),d10,c10)}function o3(a10){var b10=a10.length-1;if(2>=b10>>>0)switch(b10){case 0:return o5;case 1:return o6;default:var e10=er(a10,1);return h(B(o7),e10)}var c10=gS(a10,2),d10=er(a10,1);return i(B(o4),d10,c10)}function o8(d10){return function(a10){for(var b10=a10;;){if(!b10)return 0;var e10=b10[2],f10=b10[1];a:{try{var c10=h(f10,d10)}catch{break a}if(c10)return[0,c10[1]]}b10=e10}}(cG(ep))}function o9(a10){if(a10===d6)return o_;if(a10===gq)return o$;if(a10[1]===gp){var b10=a10[2],e10=b10[3],i10=b10[2],j10=b10[1];return fu(B(eq2),j10,i10,e10,e10+5|0,pa)}if(a10[1]===f){var c10=a10[2],g10=c10[3],k10=c10[2],l10=c10[1];return fu(B(eq2),l10,k10,g10,g10+6|0,pb)}if(a10[1]===b4){var d10=a10[2],h10=d10[3],m10=d10[2],n10=d10[1];return fu(B(eq2),n10,m10,h10,h10+6|0,pc)}if(aw(a10)!==0)return a10[1];var o10=a10[1][1];return ay(o10,o3(a10))}function cV(a10){var b10=o8(a10);return b10?b10[1]:o9(a10)}function pd(a10){var b10=[0,zq(a10)];return b10}function pe(c10,b10){function a10(a11){return a11?c10===0?pf:pg:c10===0?ph:pi}if(b10[0]===0){var d10=b10[5],e10=b10[4],f10=b10[3],g10=b10[6]?pj:pl,i10=b10[2],j10=b10[7],k10=a10(b10[1]);return[0,zd(B(pk),k10,j10,i10,g10,f10,e10,d10)]}if(b10[1])return 0;var l10=a10(0);return[0,h(B(pm),l10)]}function pn(a10,b10){if(!b10)return cU(a10,pp);var d10=b10[1],e10=d10.length-2|0,g10=0;if(e10>=0)for(var c10=g10;;){var f10=pe(c10,j(d10,c10)[1+c10]);if(f10){var i10=f10[1];h(cU(a10,po),i10)}var k10=c10+1|0;if(e10===c10)break;c10=k10}return 0}function cW(a10,b10){return pn(a10,pd(b10))}var ps=pr.slice();function pt(a10,b10){var e10=cV(a10);h(en(pu),e10),cW(at,b10);var c10=z1(0);if(c10<0){var d10=cI(c10);gu(j(ps,d10)[1+d10])}return cJ(at)}var pv=[0];function gT(a10){var b10=k2(0);return b10}function pw(a10,b10){try{var d10=b10?pv:gT(0);try{d8(0)}catch{}try{var f10=pt(a10,d10),e10=f10}catch(f11){var i10=L(f11),j10=gT(0),k10=cV(a10);h(en(py),k10),cW(at,d10);var l10=cV(i10);h(en(pz),l10),cW(at,j10);var e10=cJ(at)}return e10}catch(f11){var c10=L(f11);if(c10===d6)return gu(px);throw g(c10,0)}}gl(kv,function(a10,b10){try{var c10=pw(a10,b10);return c10}catch{return 0}});function pq(a10){for(;;){var b10=cG(ep),c10=1-d5(ep,b10,[0,a10,b10]);if(!c10)return c10}}function pA(a10){return k2(a10)}var pC=[q,pB,ae(0)];pq(function(a10){return a10[1]===pC?[0,ay(pD,cV(a10[2]))]:0});function pE(a10){return zZ(a10,0,n(a10))}function pF(a10){return[0,ap(55,0),0]}function pG(a10,b10){function l10(a11,b11){return pE(ay(a11,gA(b11)))}function m10(a11){var b11=y(a11,3)<<24,c11=y(a11,2)<<16,d11=y(a11,1)<<8;return((y(a11,0)+d11|0)+c11|0)+b11|0}for(var g10=b10.length-1===0?[0,0]:b10,h10=g10.length-1,c10=0;;){j(a10[1],c10)[1+c10]=c10;var s10=c10+1|0;if(c10===54)break;c10=s10}var f10=[0,pH],i10=54+gz(55,h10)|0,n10=0;if(i10>=0)for(var d10=n10;;){var e10=d10%55|0,k10=z6(d10,h10),o10=j(g10,k10)[1+k10];f10[1]=l10(f10[1],o10);var p10=m10(f10[1]),q10=(j(a10[1],e10)[1+e10]^p10)&jV;j(a10[1],e10)[1+e10]=q10;var r10=d10+1|0;if(i10===d10)break;d10=r10}a10[2]=0}function pI(a10){var b10=pF(0);return pG(b10,a10),b10}function gU(a10){return pI(Ah(0))}function cX(a10){a10[2]=(a10[2]+1|0)%55|0;var b10=a10[2],c10=j(a10[1],b10)[1+b10],d10=(a10[2]+24|0)%55|0,e10=(j(a10[1],d10)[1+d10]+(c10^(c10>>>25|0)&31)|0)&jV,f10=a10[2];return j(a10[1],f10)[1+f10]=e10,e10}function gV(a10){var b10=gf(dW(cX(a10)),9),c10=gf(dW(cX(a10)),9);return k5(b10,k5(k6(c10,21),k6(gf(dW(cX(a10)),8),42)))}function pJ(a10){var b10=a10.length-1<4?1:0,c10=b10||(a10[4]<0?1:0);return c10}try{var zb=li(km),gZ=zb}catch(f10){var gW=L(f10);if(gW!==ax)throw g(gW,0);try{var za=li("CAMLRUNPARAM"),gY=za}catch(f11){var gX=L(f11);if(gX!==ax)throw g(gX,0);var gY=pK}var gZ=gY}var cY=[ba,function(a10){return gU(0)}],pL=mh(gZ,82);function pM(a10,b10){for(var c10=a10;;){if(b10<=c10||d9<(c10*2|0))return c10;c10=c10*2|0}}function es(a10,b10){var f10=a10?a10[1]:pL,c10=pM(16,b10);if(f10)var d10=aw(cY),g10=aD===d10?cY[1]:ba===d10?cK(cY):cY,e10=cX(g10);else var e10=0;return[0,0,ap(c10,0),e10,c10]}function pN(m10,b10,c10,d10){var g10=d10.length-1,f10=ap(g10,0),i10=c10.length-2|0;function n10(a11){for(var c11=a11;;){if(!c11)return;var i11=c11[1],l11=c11[2],n11=c11[3],g11=b10?c11:[0,i11,l11,0],e11=h(m10,i11),k11=j(f10,e11)[1+e11];k11?k11[3]=g11:j(d10,e11)[1+e11]=g11,j(f10,e11)[1+e11]=g11,c11=n11}}var o10=0;if(i10>=0)for(var e10=o10;;){n10(j(c10,e10)[1+e10]);var r10=e10+1|0;if(i10===e10)break;e10=r10}if(b10){var k10=g10-1|0,p10=0;if(k10>=0)for(var a10=p10;;){var l10=j(f10,a10)[1+a10];l10&&(l10[3]=0);var q10=a10+1|0;if(k10===a10)break;a10=q10}}}function g0(a10,b10){var c10=b10[2],d10=(c10.length-1)*2|0,e10=d10>>0))return g7(a10,d10)}function pZ(a10){var b10=mJ(a10[28]);if(b10){var c10=b10[1],d10=c10[1];a10[12]=a10[12]-c10[3]|0;var e10=d10;a10[9]=a10[9]+e10|0}}function p0(a10,b10,c10){if(typeof c10=="number")switch(c10){case 0:var j10=bE(a10[3]);if(!j10)return;var k10=j10[1][1],l10=function(a11,b11){if(!b11)return[0,a11,0];var c11=b11[1],d11=b11[2];return zV(a11,c11)?[0,a11,b11]:[0,c11,l10(a11,d11)]};k10[1]=l10(a10[6]-a10[9]|0,k10[1]);return;case 1:bD(a10[2]);return;case 2:bD(a10[3]);return;case 3:var m10=bE(a10[2]);return m10?g7(a10,m10[1][2]):c0(a10);case 4:var o10=a10[10]!==(a10[6]-a10[9]|0)?1:0;return o10&&pZ(a10);default:var p10=bD(a10[5]);return p10?et(a10,h(a10[25],p10[1])):void 0}switch(c10[0]){case 0:return g6(a10,b10,c10[1]);case 1:var d10=c10[2],f10=c10[1],q10=d10[1],z10=d10[2],r10=bE(a10[2]);if(!r10)return;var s10=r10[1],e10=s10[2];switch(s10[1]){case 0:return bI(a10,f10);case 1:return bi(a10,d10,e10);case 2:return bi(a10,d10,e10);case 3:return a10[9]<(b10+n(q10)|0)?bi(a10,d10,e10):bI(a10,f10);case 4:return a10[11]?bI(a10,f10):a10[9]<(b10+n(q10)|0)||((a10[6]-e10|0)+z10|0)=a10[14])return a10[13]=g5,g8(a10),b10&&c0(a10),qb(a10);hb(a10,0)}}function ew(a10,b10,c10){var d10=a10[14]=c10)return x(a10[17],hf,0,c10);x(a10[17],hf,0,80),c10=c10-80|0}}function qo(a10){return a10[1]===b$?ay(qq,ay(a10[2],qp)):qr}function qs(a10){return a10[1]===b$?ay(qu,ay(a10[2],qt)):qv}function qw(a10){return 0}function qx(a10){return 0}function qy(a10,b10,c10,d10,e10){var g10=ef(0),h10=[0,g3,qz,0];eh(h10,g10);var f10=bC(0);eu(f10),a5([0,1,h10],f10);var i10=78,j10=bC(0),k10=bC(0),l10=bC(0);return[0,f10,bC(0),l10,k10,j10,i10,10,68,i10,0,1,1,1,1,gs,qA,a10,b10,c10,d10,e10,0,0,qo,qs,qw,qx,g10]}function hh(a10,b10){var c10=qy(a10,b10,function(a11){return 0},function(a11){return 0},function(a11){return 0});return c10[19]=function(a11){return qm(c10,a11)},c10[20]=function(a11){return hg(c10,a11)},c10[21]=function(a11){return hg(c10,a11)},c10}function hi(d10){return hh(function(a10,b10,c10){return lx(d10,a10,b10,c10)},function(a10){return cJ(d10)})}function ex(d10){return hh(function(a10,b10,c10){return mR(d10,a10,b10,c10)},function(a10){return 0})}var qB=dF,qC=function(a10){return b8(qB)}(0),qD=hi(lw),qE=hi(at);ex(qC);function p8(a10,b10){a10[22]&&(a5(b10,a10[4]),h(a10[26],b10));var c10=a10[23];return c10&&ca(a10,[0,cZ,[5,b10],0])}function qd(a10,b10){return he(a10,n(b10),b10)}function qe(a10,b10){return hd(a10,1),h(a10[18],0)}function qf(a10,b10){var c10=a10[14]=0)for(var c10=g10;;){qJ(e10,c10,a10,j(b10,c10)[1+c10]);var h10=c10+1|0;if(f10===c10)break;c10=h10}return e10}function hl(a10,b10){return typeof b10!="number"&&b10[0]===0?hk(a10,b10[1]):aK(qK)}function qL(a10,b10,c10,d10){if(typeof c10!="number")return c10[0]===0?hm(c10[1],a10[1+b10],d10):void 0;if(c10!==2){a10[1+b10]=d10;return}if(aw(d10)===0&&d10.length-1===4)for(var e10=0,h10=a10[1+b10];;){h10[1+e10]=d10[1+e10];var i10=e10+1|0;if(e10===3)return;e10=i10}throw g([0,f,qM],1)}function hm(a10,b10,c10){if(aw(c10)===0&&a10.length-1<=c10.length-1){var e10=a10.length-2|0,h10=0;if(e10>=0)for(var d10=h10;;){var i10=c10[1+d10];qL(b10,d10,j(a10,d10)[1+d10],i10);var k10=d10+1|0;if(e10===d10)break;d10=k10}return}throw g([0,f,qN],1)}function hn(a10,b10,c10){return typeof a10!="number"&&a10[0]===0?hm(a10[1],b10,c10):aK(qO)}var ey=[q,qP,ae(0)];qH(qQ,[0,ey,[0]]);function ez(a10){return[0,a10]}function Q(a10){return[0,a10]}function c2(a10){return a10[0]===0?[0,a10[1]]:0}var bK=[0,function(a10){return a10}(0)];function bL(a10){return[1,0,0,0,a10]}function l(a10,b10){return a10[0]===0?[0,h(b10,a10[1])]:bL([0,a10,b10])}function cc(a10,b10,c10){if(a10[0]===0){var d10=a10[1];if(b10[0]===0)return[0,i(c10,d10,b10[1])]}return bL([1,a10,b10,c10])}function ho(a10){return a10[0]===0?a10[1]:bL([4,a10,0])}function hp(a10,b10,c10){switch(c10[0]){case 0:throw g([0,f,qT],1);case 1:c10[3]=[0,b10,a10,c10[3]];return;default:c10[2]=[0,b10,a10,c10[2]];return}}function eA(a10,b10){if(!b10)throw g([0,f,qU],1);if(b10[2]===a10)return[0,b10[1],b10[3]];var c10=eA(a10,b10[3]),d10=c10[1];return b10[3]=c10[2],[0,d10,b10]}function cd(a10,b10){switch(b10[0]){case 0:throw g([0,f,qV],1);case 1:var c10=eA(a10,b10[3]),e10=c10[1];return b10[3]=c10[2],e10;default:var d10=eA(a10,b10[2]),h10=d10[1];return b10[2]=d10[2],h10}}function hq(a10,b10,c10,d10){for(var e10=d10;;){if(!e10)throw g([0,f,qW],1);if(e10[1]===b10&&e10[2]===a10){e10[1]=c10;return}e10=e10[3]}}function eB(a10,b10,c10,d10){switch(d10[0]){case 0:throw g([0,f,qX],1);case 1:return hq(a10,b10,c10,d10[3]);default:return hq(a10,b10,c10,d10[2])}}function hr(a10,b10){for(var c10=b10;;){if(!c10)throw g([0,f,qY],1);if(c10[2]===a10)return c10[1];c10=c10[3]}}function qZ(a10,b10){switch(b10[0]){case 0:throw g([0,f,q0],1);case 1:return hr(a10,b10[3]);default:return hr(a10,b10[2])}}function aU(a10,b10,c10,d10){switch(d10[0]){case 0:throw g([0,f,q1],1);case 1:var j10=d10[1];if(typeof j10=="number"&&!j10){if(!c10||b10[1])return;b10[1]=1;return}var k10=d10[4];if(k10[0]===7){var n10=k10[2];if(n10[0]===1){var o10=n10[1];if(typeof o10=="number"){if(!o10&&c10){if(b10[1])return;b10[1]=1;return}}else if(c10)return}}var l10=d10[1];a:{if(typeof l10=="number"&&l10){var e10=1;break a}var e10=c10}d10[1]=0;var m10=d10[2];return a10<50?jb(a10+1|0,b10,e10,m10):r(jb,[0,b10,e10,m10]);default:var i10=d10[1];if(d10[1]=0,typeof i10=="number"){if(!i10)return;b10[1]=2;return}var p10=i10[1];return c10&&(b10[1]=2),h(d10[3],p10)}}function a6(a10,b10,c10){return bA(aU(0,a10,b10,c10))}function jb(a10,b10,c10,d10){if(typeof d10!="number")switch(d10[0]){case 0:var f10=d10[1];return a10<50?aU(a10+1|0,b10,c10,f10):r(aU,[0,b10,c10,f10]);case 1:var g10=d10[2];return a6(b10,c10,d10[1]),a10<50?aU(a10+1|0,b10,c10,g10):r(aU,[0,b10,c10,g10]);case 2:var h10=d10[3],l10=d10[2];return a6(b10,c10,d10[1]),a6(b10,c10,l10),a10<50?aU(a10+1|0,b10,c10,h10):r(aU,[0,b10,c10,h10]);case 3:var i10=d10[4],m10=d10[3],n10=d10[2];return a6(b10,c10,d10[1]),a6(b10,c10,n10),a6(b10,c10,m10),a10<50?aU(a10+1|0,b10,c10,i10):r(aU,[0,b10,c10,i10]);default:var o10=d10[1];d10[1]=0;var k10=o10-1|0,p10=0;if(k10>=0)for(var e10=p10;;){a6(b10,c10,j(d10[3],e10)[1+e10]);var q10=e10+1|0;if(k10===e10)break;e10=q10}return}}function q2(a10){return i(cU(at,q3),cW,zx(20))}function c3(a10,b10){var c10=[0,0];a6(c10,a10,b10);var d10=2<=c10[1]?1:0;return d10&&q2(0)}function am(a10){return bL([5,a10])}function aP(a10){return a10}function ac(a10,b10){if(a10[0]===1){var c10=a10[4];if(c10[0]===5)return c10[1]=b10,c3(0,a10)}throw g([0,f,q4],1)}function bM(a10){if(a10[0]===1){var b10=a10[4];if(b10[0]===5)return b10[1]}throw g([0,f,q5],1)}function bN(a10,b10,c10){for(var k10=a10,h10=b10,d10=c10;;)switch(d10[0]){case 0:return k10;case 1:var e10=d10[2];if(typeof e10=="number")throw g([0,f,q_],1);switch(e10[0]){case 0:if(e10[1]!==h10)throw g([0,f,q$],1);var o10=0;break;case 1:var B2=e10[2],C2=e10[1];if(C2===h10)var D2=[0,B2];else{if(B2!==h10)throw g([0,f,ra],1);var D2=[0,C2]}var o10=D2;break;case 2:var u10=e10[3],v10=e10[2],w10=e10[1];if(w10===h10)var x10=[1,v10,u10];else if(v10===h10)var x10=[1,w10,u10];else{if(u10!==h10)throw g([0,f,rb],1);var x10=[1,w10,v10]}var o10=x10;break;case 3:var p10=e10[4],q10=e10[3],r10=e10[2],s10=e10[1];if(s10===h10)var t10=[2,r10,q10,p10];else if(r10===h10)var t10=[2,s10,q10,p10];else if(q10===h10)var t10=[2,s10,r10,p10];else{if(p10!==h10)throw g([0,f,rc],1);var t10=[2,s10,r10,q10]}var o10=t10;break;default:var n10=cd(d10,h10);if(j(e10[3],n10)[1+n10]!==h10)throw g([0,f,rd],1);var m10=e10[2]-1|0;if(e10[2]=m10,n10>>2|0))var U2=ml(e10[3],0,K2>>>1|0),M2=[4,e10[1],e10[2],U2];else var M2=e10;var J2=M2}var o10=J2}if(d10[2]=o10,typeof o10!="number")return k10;var y10=d10[1];d10[1]=1;var l10=d10[4];switch(l10[0]){case 0:h10=d10,d10=l10[1];break;case 1:var N2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=N2;break;case 2:var O2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=O2;break;case 3:var P2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=P2;break;case 4:var z10=l10[2],A2=bN(k10,d10,l10[1]);if(!z10)return A2;var Q2=z10[1];l10[2]=0,k10=A2,h10=d10,d10=Q2;break;case 5:return k10;case 6:if(typeof y10=="number")return k10;var R2=y10[1];try{return i(l10[2],d10,R2),k10}catch(f10){var S2=L(f10);return[0,[0,S2,pA(0)],k10]}default:var T2=l10[1];k10=bN(k10,d10,l10[2]),h10=d10,d10=T2}break;default:throw g([0,f,re],1)}}function a7(a10,b10){for(var e10=a10,c10=b10;;)switch(c10[0]){case 0:return;case 1:var n10=typeof c10[2]=="number"?1:0,d10=c10[2];if(typeof d10=="number")var k10=[0,e10];else switch(d10[0]){case 0:var k10=[1,e10,d10[1]];break;case 1:var k10=[2,e10,d10[1],d10[2]];break;case 2:var k10=[3,e10,d10[1],d10[2],d10[3]];break;case 3:for(var o10=[0,d10[1],d10[2],d10[3],d10[4],e10,bK,bK,bK],l10=0;;){hp(c10,l10,j(o10,l10)[1+l10]);var w10=l10+1|0;if(l10===4)break;l10=w10}var k10=[4,5,5,o10];break;default:var i10=d10[2];if(i10>>1|0)}function hz(a10,b10,c10){if(typeof a10!="number"){if(a10[0]!==0){if(a10[2]!==b10)throw g([0,f,rN],1);a10[2]=c10;return}if(a10[2]===b10){a10[2]=c10;return}if(a10[4]===b10){a10[4]=c10;return}}throw g([0,f,rM],1)}function ft(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[4];if(typeof d10!="number"&&d10[0]!==1){var h10=c10[5],e10=d10[2];if(typeof e10=="number")var i10=0;else{if(e10[0]!==0)throw g([0,f,rR],1);e10[5]=c10;var i10=e10}return d10[2]=c10,c10[4]=i10,c10[5]=d10,d10[5]=h10,hz(h10,c10,d10),eI(b10,c10),a10<50?cp(a10+1|0,b10,d10):r(cp,[0,b10,d10])}}throw g([0,f,rQ],1)}function rO(a10,b10){return bA(ft(0,a10,b10))}function fs(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[2];if(typeof d10!="number"&&d10[0]!==1){var h10=c10[5],e10=d10[4];if(typeof e10=="number")var i10=0;else{if(e10[0]!==0)throw g([0,f,rT],1);e10[5]=c10;var i10=e10}return d10[4]=c10,c10[2]=i10,c10[5]=d10,d10[5]=h10,hz(h10,c10,d10),eI(b10,c10),a10<50?cp(a10+1|0,b10,d10):r(cp,[0,b10,d10])}}throw g([0,f,rS],1)}function rP(a10,b10){return bA(fs(0,a10,b10))}function jd(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[4];a:if(typeof d10!="number"&&d10[0]===0){var e10=bP(d10[2]);if(eH(bP(d10[4]),e10)){rP(b10,d10);break a}}return a10<50?ft(a10+1|0,b10,c10):r(ft,[0,b10,c10])}throw g([0,f,rU],1)}function jc(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[2];a:if(typeof d10!="number"&&d10[0]===0){var e10=bP(d10[4]);if(eH(bP(d10[2]),e10)){rO(b10,d10);break a}}return a10<50?fs(a10+1|0,b10,c10):r(fs,[0,b10,c10])}throw g([0,f,rV],1)}function cp(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=bP(c10[2]),e10=bP(c10[4]);return d10>>2|0)}function az(a10,b10){if(typeof a10=="number")var c10=b10;else{if(typeof b10!="number"){var d10=c8(b10);return[1,(hE(c8(a10),d10)+1|0)<<2,a10,b10]}var c10=a10}return c10}function hF(a10){return typeof a10=="number"?0:a10[0]===0?[0,a10[2]]:[1,a10[2],a10[3]]}var eJ=1,eK=2,sq=3;function hG(a10){return a10===-1?1:0}function eL(a10){return a10!==-1?1:0}function bQ(a10){return(a10&3)===3?1:0}function hH(a10){return(a10&3)===1?1:0}function hI(a10){return(a10&3)===2?1:0}function hJ(a10){return a10|3}function sr(a10){return a10>>>2|0}function hK(a10){return a10<<2|2}function ch(a10){return a10&lp(sq)}function hL(a10){return a10[2]}function hM(a10){return a10[3]}function hN(a10){return[0,0,0,0]}function c9(a10){a10[1]=a10[1]+1|0}function c_(a10){a10[2]=a10[2]+1|0}function c$(a10){a10[3]=a10[3]+1|0}function eM(a10,b10,c10){for(var d10=c10;;){if(typeof d10=="number")return;if(d10[0]===0){var e10=d10[1],i10=(e10&3)!==3?1:0,l10=i10&&(e10&3?1:0);if(l10){if(e10&b10)throw g([0,f,st],1);c9(a10),c$(a10),d10[1]=e10|3}return}var h10=d10[1],j10=(h10&3)!==3?1:0,k10=j10&&(h10&3?1:0);if(!k10)return k10;if(h10&b10)throw g([0,f,su],1);c9(a10),c$(a10),d10[1]=h10|3,eM(a10,b10,d10[2]),d10=d10[3]}}function da(a10,b10,c10,d10){if(typeof d10!="number"){if(d10[0]===0){var e10=d10[1];e10&c10||(c9(a10),e10&3?(d10[1]=-1,c$(a10),c_(a10)):d10[1]=e10|c10);var g10=e10!==-1?1:0,h10=g10&&((e10&3)===3?1:0);return h10&&(d10[1]=-1,c_(a10))}var f10=d10[1];f10&c10||(c9(a10),f10&3?(d10[1]=-1,c$(a10),c_(a10),eM(a10,c10,d10[2]),eM(a10,c10,d10[3])):(d10[1]=f10|c10,eh(d10,b10)));var i10=f10!==-1?1:0,j10=i10&&((f10&3)===3?1:0);return j10&&(d10[1]=-1,c_(a10))}}function eN(a10,b10,c10){var d10=gM(b10);if(typeof d10!="number"&&d10[0]===1){var e10=(d10[1]&3)===c10?1:0;return e10&&(da(a10,b10,c10,d10[2]),da(a10,b10,c10,d10[3]))}throw g([0,f,sv],1)}function hO(a10,b10,c10){for(;;){if(ei(b10))return;eN(a10,b10,c10)}}function sw(a10,b10,c10,d10){for(;;){if(ei(c10))return hO(b10,d10,eK);if(ei(d10))return hO(a10,c10,eJ);eN(a10,c10,eJ),eN(b10,d10,eK)}}function eO(a10){var b10=a10[6];return a10[6]=b10+1|0,b10}function eP(a10){for(var b10=a10;;){if(typeof b10=="number")return;if(b10[0]===0){var c10=b10[1];if(typeof c10!="number"&&c10[0]===0){var e10=c10[1],i10=eL(e10),l10=i10&&bQ(e10);l10&&(c10[1]=ch(e10));return}throw g([0,f,sB],1)}var d10=b10[1];if(typeof d10!="number"&&d10[0]===1){var h10=d10[1],m10=b10[4],n10=b10[3],j10=eL(h10),k10=j10&&bQ(h10);if(!k10)return k10;d10[1]=ch(h10),eP(n10),b10=m10;continue}throw g([0,f,sC],1)}}function hP(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;if(c10[0]===0){var d10=c10[1];if(typeof d10!="number"&&d10[0]===0){var e10=d10[1],u10=c10[2];if(!hH(e10)){if(hG(e10)){var k10=eO(a10);j(a10[4],k10)[1+k10]=d10,j(a10[5],k10)[1+k10]=[0,c10,0],d10[1]=hK(k10);return}if(hI(e10)){var n10=sr(e10),v10=[0,c10,j(a10[5],n10)[1+n10]];j(a10[5],n10)[1+n10]=v10;return}var q10=bQ(e10);if(q10)throw g([0,f,sF],1);return q10}var m10=a10[2];if(-1a10[3]))throw g([0,f,sE],1);d10[1]=ch(e10);return}throw g([0,f,sD],1)}var h10=c10[1];if(typeof h10!="number"&&h10[0]===1){var r10=c10[4],s10=c10[3],i10=h10[1],w10=c10[2];if(hG(i10)){var l10=eO(a10);return j(a10[4],l10)[1+l10]=h10,j(a10[5],l10)[1+l10]=[0,c10,0],h10[1]=hK(l10),eP(s10),eP(r10)}if(!hH(i10)){if(hI(i10)){var o10=i10>>>2|0,x10=[0,c10,j(a10[5],o10)[1+o10]];j(a10[5],o10)[1+o10]=x10;return}var t10=bQ(i10);if(t10)throw g([0,f,sI],1);return t10}if(-1a10[3])throw g([0,f,sH],1)}h10[1]=ch(i10),hP(a10,s10),c10=r10;continue}throw g([0,f,sG],1)}}function ci(a10,b10){if(typeof b10=="number")return 0;if(b10[0]!==0){var i10=b10[1];if(i10===-1){var l10=eO(a10);b10[1]=0,j(a10[4],l10)[1+l10]=b10;var p10=ci(a10,b10[2]);return[1,b10,0,p10,ci(a10,b10[3])]}if(!bQ(i10)){b10[1]=ch(b10[1]);var r10=ci(a10,b10[2]);return[1,b10,0,r10,ci(a10,b10[3])]}var d10=i10>>>2|0,k10=j(a10[5],d10)[1+d10];if(!k10)throw g([0,f,sL],1);var m10=k10[2],q10=k10[1];return j(a10[5],d10)[1+d10]=m10,m10===0&&(b10[1]=0),q10}var e10=b10[1];if(eL(e10)&&bQ(e10)){var c10=e10>>>2|0,h10=j(a10[5],c10)[1+c10];if(!h10)return[0,b10,0];var n10=h10[2],o10=h10[1];return j(a10[5],c10)[1+c10]=n10,o10}return b10[1]=0,[0,b10,0]}var eQ=[0,0,[0],0,0];function ss(a10){return a10[1]}function sx(a10){return a10[1]}function sy(a10){return a10[2]}function sz(a10,b10){var c10=hN(0),d10=hN(0),e10=ef(0),f10=ef(0);return da(c10,e10,eJ,a10),da(d10,f10,eK,b10),sw(c10,d10,e10,f10),[0,c10,d10]}function sA(a10){if(typeof a10!="number"){if(a10[0]===0){a10[1]=0;return}var b10=c8(a10[3]);a10[1]=(hE(c8(a10[2]),b10)+1|0)<<2}}function sJ(a10){var e10=a10[6]-1|0,h10=0;if(e10>=0)for(var b10=h10;;){var c10=j(a10[4],b10)[1+b10];typeof c10!="number"&&(c10[0],c10[1]=hJ(c10[1]));var d10=j(a10[5],b10)[1+b10];if(!d10)throw g([0,f,sK],1);if(d10[2]){var i10=a3(d10);j(a10[5],b10)[1+b10]=i10}var k10=b10+1|0;if(e10===b10)break;b10=k10}}function hQ(a10,b10,c10){if(typeof b10=="number"){if(typeof c10=="number")return[0,eQ,0]}else if(b10[1]===c10)return[0,eQ,b10];var t10=typeof b10=="number"?cg:b10[1],m10=sz(t10,c10),i10=sx(m10),n10=sy(m10),u10=hM(n10),v10=hM(i10)+u10|0,o10=ss(i10)-v10|0,w10=hL(n10),p10=hL(i10)+w10|0,x10=0,y10=ap(p10,0),z10=ap(p10,0),A2=a10?o10:-1,B2=a10?0:-1,C2=a10?ap(o10,0):[0],d10=[0,C2,B2,A2,z10,y10,x10];if(hP(d10,b10),d10[2]!==d10[3])throw g([0,f,sM],1);sJ(d10);var q10=ci(d10,c10),r10=d10[6]-1|0;if(r10>=0)for(var h10=r10;;){sA(j(d10[4],h10)[1+h10]);var F2=h10-1|0;if(h10===0)break;h10=F2}if(!a10)return[0,eQ,q10];var k10=[0,0],l10=[0,0],s10=d10[6]-1|0,D2=0;if(s10>=0)for(var e10=D2;;){a4(function(a11){if(typeof a11!="number")if(a11[0]===0){var b11=a11[2];if(b11)return k10[1]=[0,b11[1],k10[1]],0}else{var c11=a11[2];if(c11)return l10[1]=[0,c11[1],l10[1]],0}return 0},j(d10[5],e10)[1+e10]);var E2=e10+1|0;if(s10===e10)break;e10=E2}return[0,[0,d10[2],d10[1],k10[1],l10[1]],q10]}function sN(d10,b10){if(typeof b10=="number")return 0;function c10(a10){a:if(typeof a10!="number"){b:{if(a10[0]===0){var b11=a10[1];if(typeof b11!="number"&&b11[0]===0){var e10=a10[2];if(e10){var j10=e10[1];break b}var k10=h(d10[1],b11[2]);return a10[2]=[0,k10],k10}break a}var l10=a10[2];if(!l10){var n10=c10(a10[3]),o10=c10(a10[4]),m10=i(d10[2],n10,o10);return a10[2]=[0,m10],m10}var j10=l10[1]}return j10}throw g([0,f,sO],1)}return[0,c10(b10)]}function db(a10,b10){return[0,[0,a10,b10],0]}function dc(a10){return sN(a10[1],a10[2])}function sP(a10,b10){var c10=a10[1];return[0,c10,hQ(0,a10[2],b10)[2]]}function eR(a10,b10){var d10=a10[1],c10=hQ(1,a10[2],b10);return[0,c10[1],[0,d10,c10[2]]]}function dd(a10,b10,c10,d10){var e10=[0,d10];if(v===a10)var h10=c10[1],g10=0;else if(j4<=a10)var h10=c10[2].length-1,g10=c10[1];else var h10=c10[2].length-1,g10=0;var k10=h10-1|0;if(k10>=g10)for(var f10=g10;;){var l10=j(c10[2],f10)[1+f10];l10&&(e10[1]=i(b10,l10[1],e10[1]));var m10=f10+1|0;if(k10===f10)break;f10=m10}j4>a10&&a4(function(a11){return e10[1]=i(b10,a11,e10[1]),0},c10[3]),v!==a10&&a4(function(a11){return e10[1]=i(b10,a11,e10[1]),0},c10[4])}function eS(a10,b10,c10){if(typeof c10=="number")throw g([0,f,sQ],1);if(c10[0]===0)return h(a10,c10[2]);var d10=eS(a10,b10,c10[3]);return i(b10,eS(a10,b10,c10[2]),d10)}function bj(a10,b10,c10){var d10=b10[2],e10=b10[1],f10=c2(c10);if(f10){var g10=f10[1];return Q(typeof g10=="number"?e10:eS(a10,d10,g10))}var h10=[0,db(a10,d10)];return l(c10,function(a11){var b11=sP(h10[1],a11);h10[1]=b11;var c11=dc(b11);return c11?c11[1]:e10})}var aQ=[0,cg,az];function sR(a10,b10){return c5(b10,aQ,a10)}function de(a10){return sR(a10,J)}function hR(a10){function e10(a11,b10){for(var c10=a11,d10=b10;;){if(typeof c10=="number")return d10;if(c10[0]===0)return[0,c10[2],d10];var f10=e10(c10[3],d10);c10=c10[2],d10=f10}}return e10(a10,0)}var hS=[0,Q(0),function(a10,b10){return cc(a10,b10,az)}];function eT(c10,b10){return bj(function(a10){return J(h(c10,a10))},aQ,b10)}function sS(a10,b10){return ho(bj(b10,hS,a10))}function bk(a10){return sS(a10,function(a11){return l(a11,J)})}var bl=e;function sT(a10){return a10[kL]}function hT(a10,b10){var c10=a10?a10[1]:bl;return zW(b10).join(c10)}function eU(a10){return sT(a10)===0?1:0}function df(a10,b10){return k0(a10,b10)}p.Number;var eV=null,sU=void 0;function cj(a10){return a10===eV?1:0}function sV(a10){return a10===sU?1:0}function bR(a10){var b10=cj(a10);return b10||sV(a10)}function hU(a10){return 1-bR(a10)}function dg(a10,b10){return bR(b10)?0:[0,h(a10,b10)]}var k=p;function eW(a10,b10){var c10=a10[b10];return bR(c10)?0:[0,c10]}function eX(a10){return new k[jU](a10)}function hV(a10){return a10[kL]}function hW(c10,b10){return gI(hV(b10),function(a10){return h(c10,b10[a10])})}function hX(a10,b10){var d10=b10.length-1,e10=eX(d10),f10=d10-1|0,g10=0;if(f10>=0)for(var c10=g10;;){e10[c10]=h(a10,j(b10,c10)[1+c10]);var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function hY(f10,b10){return function(a10,b11,c10){for(var e10=a10,d10=c10;;){if(!d10)return b11;var g10=d10[2];b11[e10]=h(f10,d10[1]),e10=e10+1|0,d10=g10}}(0,eX(0),b10)}function s0(a10,b10){var c10=new k.Error(b10);return a10&&(c10[cq]=a10[1]),c10}var s2=Symbol.iterator;function s4(a10){return a10.next()}function s5(a10){var b10=dg(function(a11){return a11|0},a10.done);return b10?b10[1]:0}function s6(a10){return a10[dE]}function hZ(i10,g10,c10,d10,e10){return function(a10,b10){for(var d11=b10;;){var e11=s4(a10);if(s5(e11))return d11;var f10=s6(e11),j10=h(g10,f10[1]);d11=x(c10,h(i10,f10[0]),j10,d11)}}(d10,e10)}k.Promise;function sY(a10){return as(a10)}function bm(a10,b10,c10){return dZ(a10,sY(b10),c10)}function aA(a10){return as(a10)}function C(a10){return H(a10)}function bS(a10,b10){return a10 instanceof b10?1:0}var sW=!0;function sX(a10,b10){a10[b10]}function sZ(c10,b10){return lW(hV(b10),function(a10){return h(c10,b10[a10])})}function s1(a10,b10){return h(function(a11){throw a11},s0(a10,b10))}function s3(a10){return a10[s2]()}k.Event;function eY(a10){return a10[fv]}function h0(a10,b10,c10,d10){var e10=a10?a10[1]:{},f10=by(1,c10);return d10.addEventListener(b10,f10,e10),function(a11){return d10.removeEventListener(b10,f10,e10),0}}function h1(a10){return h(a10,0)}var eZ="change",dh="click";k.ArrayBuffer,k.DataView;function s7(a10){return a10.preventDefault(),0}var s8="DOMContentLoaded",s9=ka,s_="scroll",s$="wheel";k.Blob,k.File;var h2=k.JSON;k.encodeURI,k.decodeURI,k.encodeURIComponent,k.decodeURIComponent,k.URL,k.URLSearchParams;function aR(a10,b10){return[0,a10,b10]}var di=[0,bl,bl];function e0(a10){return[0,a10,bl]}function h3(a10){return a10}var ck=ku,e1=jN,h4=cq,h5=jz,e2="type",e3=dE,td="for";function aS(a10){return aR(ck,a10)}function h6(a10){return aR(td,a10)}var tf=e0(jl),th=e0("required");function dj(a10){return aR(h5,a10)}var ti=e0("selected"),bn=k.document;function ta(a10){return h2.stringify(a10)}function tb(a10){try{var c10=h2.parse(a10)}catch(f10){var b10=L(f10);if(b10[1]===ey)return[1,b10[2]];throw g(b10,0)}return[0,c10]}function tc(a10,b10){return a10?b10:di}var te="placeholder";function tg(a10){return aR(e1,a10)}function tj(a10){return aR(e2,a10)}function tk(a10){return aR(e3,a10)}function tl(a10){return a10.ownerDocument}bR(bn)||bn[jI];function tm(a10,b10){return a10.appendChild(b10),0}function tn(a10,b10,c10,d10){for(var g10=b10,f10=c10,e10=d10;;){if(!e10){g10!==0&&a10.setAttribute(jz,hT([0,";"],a3(g10))),f10!==0&&a10.setAttribute(ku,hT([0,aE],a3(f10)));return}var h10=e10[2],k10=e10[1],i10=k10[2],j10=k10[1];if(eU(j10))e10=h10;else if(df(j10,h5))g10=[0,i10,g10],e10=h10;else if(df(j10,ck)){var l10=eU(i10)?f10:[0,i10,f10];f10=l10,e10=h10}else a10.setAttribute(j10,i10),e10=h10}}function h7(a10,b10,c10,d10){var f10=a10?a10[1]:bn,g10=b10?b10[1]:0,e10=f10.createElement(c10);return tn(e10,0,0,g10),a4(function(a11){return tm(e10,a11)},d10),e10}function bo(a10,b10){var c10=a10?a10[1]:bn;return c10.createTextNode(C(b10))}function h8(a10,b10,c10){return eU(a10)?0:b10?(c10.setAttribute(a10,b10[1]),0):(c10.removeAttribute(a10),0)}function h9(a10,b10,c10){return b10?(c10[jm].add(a10),0):(c10[jm].remove(a10),0)}var h_="div";function tx(a10,b10,c10,d10){return h7(b10,c10,a10,d10)}function h$(a10,b10,c10){return tx(h_,a10,b10,c10)}function ia(a10){return a10[jI]}function dk(a10,b10,c10){return dZ(a10,b10,c10),0}var dl=k[kP];function dm(a10){return zT(function(a11,b10,c10){for(var e10=b10,d10=c10;;){if(!d10)return a11;var f10=d10[2];a11[e10]=d10[1],e10=e10+1|0,d10=f10}}(eX(0),0,a10))}function ah(a10){return dk(dl,tA,dm(a10))}function e4(a10){return dk(dl,tF,dm(a10))}k[kP],k.navigator;var tI=k.performance,dn=k[kp];sX(k,tJ);function to(a10,b10){dZ(a10,kF,gL(b10))}function tp(a10,b10,c10){var e10=a10?a10[1]:k[kp],d10=e10.getComputedStyle(c10)[b10];return bR(d10)?bl:d10}function tq(a10,b10){var c10=a10?a10[1]:kh,d10=kh<=c10?1:0;return b10.scrollIntoView(!!d10),0}var tr="button",ts="form",tt=ka,tu="label",tv="option",tw="select";function ty(a10){var b10=a10.body;return hU(b10)?b10:s1(0,"Document body is null. Try to defer your script execution.")}function tz(a10){return dg(function(a11){return a11},a10.activeElement)}function tB(a10){return dk(dl,tC,dm(a10))}function tD(a10){return dk(dl,tE,dm(a10))}function tG(a10){return a10}function tH(a10){return a10.now()}function tK(a10,b10){return k.setTimeout(by(1,b10),a10)}function tL(a10){k.clearTimeout(a10)}function tM(a10){k.requestAnimationFrame(by(1,a10))}k.ClipboardItem,k.FormData,k.Headers,k.Request,k.Response,k.fetch,k.MediaStream,k.MediaRecorder,k.MessageChannel,k.BroadcastChannel,k.Notification,k.WebSocket;function tN(a10){return a10.localStorage}function tO(a10,b10){function c10(a11){return a11}return function(a11){return dg(c10,a11)}(a10.getItem(b10))}function tP(a10,b10,c10){try{a10.setItem(b10,c10);return}catch(f10){var d10=L(f10);if(d10[1]===ey)return;throw g(d10,0)}}function aB(a10,b10,c10){return[0,a10,b10,c10]}function ib(a10){var b10=a10[1];return b10===82||83<=b10?gv(c2(a10[2])):1}function dp(a10){return cL(c2(a10))}function tQ(a10){return d_(cM(function(a11){var b10=a11[1];return b10===82?[0,dp(a11[2]),0]:83<=b10?hR(dp(a11[2])):[0,a11[2],0]},a10))}function ic(a10){if(!a10)return tR;var b10=l1(ib,a10),c10=b10[2];return[0,tQ(b10[1]),c10]}var id2=kF,e5="before";function tU(a10){return[0,a10]}function tV(a10,b10){return[1,eV,a10,b10]}var tW="remove",tX="contains";function ie(a10){var b10=tz(tl(a10));return b10?bm(a10,tX,[0,b10[1]])|0:0}function ig(e10,b10){var c10=[0,db(tU,tV)];return l(b10,function(a10){var b11=eR(c10[1],a10),d10=b11[2],g10=b11[1];c10[1]=d10,dd(v,function(a11,b12){return a11[0]===0?a11[1][dD]=sW:0},g10,0);var h10=ie(e10),i10=dc(d10);if(i10){var f10=function(d11,b12){if(b12[0]!==0){if(!cj(b12[1]))return b12[1];var l10=f10(d11,b12[3]),k10=f10(l10,b12[2]);return b12[1]=k10,k10}var c11=b12[1];if(delete c11[dD],c11.parentNode!==e10)cj(d11)?bm(e10,id2,[0,c11]):bm(d11,e5,[0,c11]);else{var a11=c11.nextSibling!==d11?1:0;if(a11){if(h10)var g11=ie(c11),i11=g11&&function(a12){for(;;){var b13=c11.nextSibling;if(b13===d11)return 1;if(cj(b13))return 0;bm(c11,e5,[0,b13])}}(0);else var i11=h10;var j10=1-i11}else var j10=a11;j10&&(cj(d11)?bm(e10,id2,[0,c11]):bm(d11,e5,[0,c11]))}return c11};f10(eV,i10[1])}return dd(v,function(a11,b12){if(a11[0]!==0)return 0;var c11=a11[1],d11=hU(c11[dD]),e11=d11&&(delete c11[dD],bm(c11,tW,[0]),0);return e11},g10,0),e10})}var dq=Q(0),e6=[0,bl,bl];function tS(a10){if(!a10)return tT;var b10=a10[1],c10=b10[1];if(c10===82){if(!a10[2])return[0,0,[0,l(b10[2],J)]]}else if(83<=c10){if(!a10[2])return[0,0,[0,b10[2]]]}else if(!a10[2])return[0,[0,b10[2],0],0];return lY(ib,a10)?[0,d_(cM(function(a11){var b11=a11[1];return b11===82?[0,dp(a11[2]),0]:83<=b11?hR(dp(a11[2])):[0,a11[2],0]},a10)),0]:[0,0,[0,c5(function(a11){var b11=a11[1];return b11===82?l(a11[2],J):83<=b11?a11[2]:Q(J(a11[2]))},hS,a10)]]}function ih(c10,b10){function d10(a10){var b11=a10[2],d11=a10[1];return df(d11,ck)?h9(b11,1,c10):h8(d11,[0,b11],c10)}function e10(a10){var b11=a10[1],d11=a10[2];return df(b11,ck)?h9(d11,0,c10):h8(b11,0,c10)}function h10(a10){var b11=[0,e6];return function(a11){b11[1]!==e6&&e10(b11[1]);var c11=a11;return d10(c11),b11[1]=c11,0}}return c5(function(a10){var b11=a10[1];if(b11===82){var i10=a10[2];return l(i10,h10(0))}if(83>b11)throw g([0,f,tY],1);var j10=a10[2],c11=[0,db(function(a11){var b12=a11;return d10(b12),b12},function(a11,b12){return e6})];return l(j10,function(a11){var b12=eR(c11[1],a11),d11=b12[2],f10=b12[1];return c11[1]=d11,dd(v,function(a12,b13){return e10(a12)},f10,0),dc(d11),0})},[0,dq,function(a10,b11){return dq}],b10)}function e7(a10,b10){return h0(b10[1],b10[2],b10[3],a10)}function tZ(c10,b10){return c5(function(a10){var b11=a10[1];if(b11===82){var d10=[0,0];return l(a10[2],function(a11){var b12=d10[1];return b12&&h1(b12[1]),d10[1]=[0,e7(c10,a11)],0})}if(83>b11)throw g([0,f,t0],1);var h10=a10[2],e10=[0,db(function(a11){return e7(c10,a11)},function(a11,b12){return a11})];return l(h10,function(a11){var b12=eR(e10[1],a11),c11=b12[2],d11=b12[1];return e10[1]=c11,dd(v,function(a12,b13){return h1(a12)},d11,0),dc(c11),0})},[0,dq,function(a10,b11){return dq}],b10)}function ii(a10,b10,c10,d10,e10,f10){var q10=b10?b10[1]:0,r10=c10?c10[1]:0,s10=d10?d10[1]:function(a11){},m10=ic(q10),k10=m10[2],t10=m10[1],n10=ic(r10),o10=n10[2],u10=n10[1],p10=tS(f10),i10=p10[2],g10=h7(a10,[0,t10],e10,p10[1]);if(h(s10,g10),k10)if(i10)var v10=ig(g10,i10[1]),j10=cc(ih(g10,k10),v10,function(a11,b11){return b11});else var j10=l(ih(g10,k10),function(a11){return g10});else var j10=i10?ig(g10,i10[1]):Q(g10);a4(function(a11){return e7(g10,a11),0},u10);var w10=o10?cc(tZ(g10,o10),j10,function(a11,b11){return b11}):j10;return w10}function bT(a10,b10,c10,d10,e10,f10){return ii(b10,c10,d10,e10,a10,f10)}function t1(a10,b10,c10,d10,e10,f10){return ii(b10,c10,d10,e10,a10,0)}function e8(a10,b10,c10,d10,e10){return bT(tr,a10,b10,c10,d10,e10)}function R(a10,b10,c10,d10,e10){return bT(h_,a10,b10,c10,d10,e10)}function ij(a10,b10,c10,d10,e10){return t1(tt,a10,b10,c10,d10,e10)}function ik(a10,b10,c10,d10,e10){return bT(tu,a10,b10,c10,d10,e10)}function t2(a10,b10,c10,d10,e10){return bT(ts,a10,b10,c10,d10,e10)}function t3(a10,b10,c10,d10,e10){return bT(tv,a10,b10,c10,d10,e10)}function t4(a10,b10,c10,d10,e10){return bT(tw,a10,b10,c10,d10,e10)}function dr(a10,b10){return b10=c10)return uj;if(b10==="bold")return ui;if(b10==="cyan")return uh;if(b10==="green")return ug;if(b10==="magenta")return uf;if(b10==="red")return ue;if(b10==="reset")return ud;if(b10==="white")return uc;if(b10==="yellow")return ub}else{if(b10==="Black")return us;if(b10==="Blue")return ur;if(b10==="Cyan")return uq;if(b10==="Green")return up;if(b10==="Magenta")return uo;if(b10==="Red")return un;if(b10==="White")return um;if(b10==="Yellow")return ul;if(b10==="black")return uk}throw g(e_,1)}function io(a10,b10){return a5(b10,a10),uu}function ip(a10){try{mD(a10),mE(a10)}catch(f10){var b10=L(f10);if(b10!==ee)throw g(b10,0)}return uv}var iq=[q,uw,ae(0)],ut=0;function ux(a10,b10,c10){if(c10[1]===iq)return io(a10,c10[2]);if(c10[1]!==b$)return h(b10,c10);var e10=c10[2];try{var f10=io(a10,im(e10));return f10}catch(f11){var d10=L(f11);if(d10===e_)return h(b10,c10);throw g(d10,0)}}function uy(a10,b10,c10){if(c10[1]===iq)return ip(a10);if(c10[1]!==b$)return h(b10,c10);var e10=c10[2];try{im(e10)}catch(f10){var d10=L(f10);if(d10===e_)return h(b10,c10);throw g(d10,0)}return ip(a10)}function uz(a10){var c10=bC(0);p_(a10,1);var b10=p$(a10,0),d10=b10[2],e10=b10[1];return qa(a10,[0,function(a11){return ux(c10,e10,a11)},function(a11){return uy(c10,d10,a11)},b10[3],b10[4]])}function uA(a10,b10){var d10=b8(64),c10=ex(d10),e10=a10&&ut;return e10&&uz(c10),qG(function(a11){return bJ(c10,0),cQ(d10)},c10,b10)}function uB(a10){return uA(1,a10)}function uC(a10,b10){return l3(a10,b10)}function uD(a10){try{var c10=[0,k8(a10)];return c10}catch(f10){var b10=L(f10);if(b10[1]===b3)return 0;throw g(b10,0)}}function uE(a10){return a10|0}function uG(a10,b10,c10,d10){for(var g10=a10,f10=b10,e10=d10;;){if(!e10){g10[1+f10]=0;return}var j10=e10[2],i10=[0,h(c10,e10[1]),kg];g10[1+f10]=i10,g10=i10,f10=1,e10=j10}}function uF(a10,b10){if(!b10)return 0;var d10=b10[2],c10=[0,h(a10,b10[1]),kg];return uG(c10,1,a10,d10),c10}function e$(a10,b10){return b10?[0,h(a10,b10[1])]:0}function uH(a10,b10,c10){return c10?h(b10,c10[1]):a10}function uI(a10,b10){if(b10)return h(a10,b10[1])}function uJ(a10,b10){return b10?b10[1]:a10}function uK(a10,b10){return a10?a10[1]:b10}function uL(a10){return a10?[0,a10[1],0]:0}function uM(a10,b10){return b10[0]===0?h(a10,b10[1]):[1,b10[1]]}function uN(a10,b10){return uM(b10,a10)}function uO(a10){var b10=mv(a10);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b10[37],,,,,,,,,,,b10[23]]}function uP(a10){var b10=uO(a10);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b10[40],,,,,,,,,,,,,,,,,,,,b10[51]]}function uQ(e10,b10){var d10=n(e10);if(dr(d10,n(b10)))return 0;var f10=n(b10)-d10|0;return function(a10){for(var c10=a10;;){if(t5(c10,d10))return 1;if(_(b10,f10+c10|0)!==_(e10,c10))return 0;c10=c10+1|0}}(0)}function fa(a10,b10){return uQ(a10,b10)?[0,eb(b10,0,n(b10)-n(a10)|0)]:0}var ir=[q,uS,ae(0)];function is(a10){return[0,[0,a10]]}function bp(a10,b10,c10,d10){return[1,a10,b10,c10,d10]}function uU(a10){return a10[0]===0&&typeof a10[1]=="number"?1:0}function it(a10,b10){if(b10[0]===0){var c10=b10[1];if(typeof c10=="number")return is(a10);switch(c10[0]){case 0:return[0,[1,a10,c10[1]]];case 1:return[0,[2,a10,c10[1],c10[2]]];default:return bp(4,[1,a10,c10[1]],uT,[1,c10[2],c10[3]])}}var d10=b10[2],f10=b10[1];if(typeof d10!="number")switch(d10[0]){case 0:break;case 1:return bp(f10+1|0,[2,a10,d10[1],d10[2]],b10[3],b10[4]);default:var e10=b10[3],h10=d10[3],i10=d10[2],j10=d10[1],g10=aw(e10),k10=aD===g10?e10[1]:ba===g10?cK(e10):e10;return bp(f10+1|0,[1,a10,j10],[ba,function(a11){return it([0,i10,h10],k10)}],b10[4])}return bp(f10+1|0,[1,a10,d10[1]],b10[3],b10[4])}function iu(a10){if(a10[0]===0){var b10=a10[1];if(typeof b10=="number")throw g(ir,1);switch(b10[0]){case 0:return[0,uR,b10[1]];case 1:var n10=b10[2];return[0,is(b10[1]),n10];default:return[0,[0,[1,b10[1],b10[2]]],b10[3]]}}var d10=a10[3],e10=a10[2],f10=a10[1],i10=aw(d10),j10=aD===i10?d10[1]:ba===i10?cK(d10):d10,h10=a10[4];if(typeof h10!="number"&&h10[0]!==0){var c10=a10[4];if(typeof c10!="number"&&c10[0]===2){var q10=c10[3];return[0,bp(f10-1|0,e10,d10,[1,c10[1],c10[2]]),q10]}var p10=c10[2];return[0,bp(f10-1|0,e10,d10,[0,c10[1]]),p10]}var k10=h10[1];if(uU(j10))return[0,[0,e10],k10];var l10=iu(j10),m10=l10[2],o10=[1,m10[1],m10[2]];return[0,bp(f10-1|0,e10,lF(l10[1]),o10),k10]}function uW(a10){if(typeof a10=="number")return 0;switch(a10[0]){case 0:return 1;case 1:return 2;default:return 3}}function uV(a10){try{var c10=[0,iu(a10)];return c10}catch(f10){var b10=L(f10);if(b10===ir)return 0;throw g(b10,0)}}function uX(a10){return a10[0]===0?uW(a10[1]):a10[1]}function uY(a10){return a10.height}function uZ(a10){return a10}function u2(a10){switch(a10){case 0:return u3;case 1:return u4;default:return u5}}function u0(a10){return a10.contentRect}function u1(a10){a10[fv]}function u6(a10,b10,c10){var d10=b10?[0,c10,{box:C(u2(b10[1]))}]:[0,c10];return dZ(a10,"observe",d10),0}function u7(c10){return new k.ResizeObserver(function(a10,b10){return i(c10,sZ(function(a11){return a11},a10),b10)})}var u8=jv,u9="pattern",iv=uP([0,ec]);function u_(a10,b10){return h(a10,b10),b10}function u$(a10){var b10=fa(va,a10);if(b10){var c10=b10[1],d10=uD(c10);if(d10)return[0,[0,d10[1]]];var g10=function(a11){return[0,a11]};return function(a11){return e$(g10,a11)}(e9(c10))}var e10=fa(vb,a10);if(e10){var h10=function(a11){return[1,a11]};return function(a11){return e$(h10,a11)}(e9(e10[1]))}var f10=fa(vc,a10);if(!f10)return 0;function i10(a11){return[1,a11]}return function(a11){return e$(i10,a11)}(e9(f10[1]))}function iw(a10){switch(a10[0]){case 0:var b10=a10[1];return h(B(vd),b10);case 1:var c10=a10[1];return h(B(ve),c10);default:var d10=a10[1];return h(B(vf),d10)}}function ix(a10){var c10=a10?a10[1]:ia(bn);function b10(a11){var b11=u$(as(tp(0,"font-size",a11)));if(!b11)return 16;var c11=b11[1];return c11[0]===0?c11[1]:aK(vg)}return function(a11){switch(a11[0]){case 0:return a11[1];case 1:var d10=a11[1];return d10*b10(ia(bn));default:var e10=a11[1];return e10*b10(c10)}}}function vh(e10,b10,c10,d10){function f10(a10,b11){return cc(d10,a10,b11)}function g10(a10,b11){return x(e10,b11[1],b11[2],a10)}return function(a10){return f10(a10,g10)}(cc(b10,c10,function(a10,b11){return[0,a10,b11]}))}var vk=[q,vj,ae(0)],vm=[q,vl,ae(0)];function iy(a10){return[0,0]}function iz(a10,b10){if(a10[1])throw g(vm,1);return a10[1]=[0,b10],0}function iA(a10){var b10=a10[1];if(b10)return b10[1];throw g(vk,1)}function vi(a10,b10,c10){return vh(function(a11,b11,c11){return[0,a11,b11,c11]},a10,b10,c10)}function vn(a10){return ta(a10)}function vo(a10){var b10=tb(a10);return b10[0]===0?[0,b10[1]]:(tB([0,b10[1],0]),vp)}var iB=es(0,64),iC=tN(dn);function vq(a10){return pS(iB,a10)?aK(h(B(vr),a10)):pP(iB,a10,0)}function iD(c10,b10){return function(a10){return tP(iC,c10,a10)}(vn(b10))}function vs(a10){var b10=tO(iC,a10);function c10(a11){return vo(a11)}var d10=b10?[0,b10[1]]:vt;return uN(d10,c10)}function vu(a10,b10){var c10=vs(a10);if(c10[0]===0)return c10[1];var d10=c10[1];return typeof d10=="number"||tD([0,d10[2],0]),h(b10,0)}function vv(d10,b10){iD(d10,b10);var a10=am(b10),c10=eC(0,a10);return eD(c10,function(a11){return iD(d10,bO(c10)),0}),bO(c10),a10}function vw(a10,b10){vq(a10);var c10=H(a10);return vv(c10,vu(c10,b10))}function iE(a10,b10){return vw(a10,function(a11){return b10})}var vy=iv[49],vx=iv[29];function vz(a10){return uF(function(a11){return[0,80,aS(H(a11))]},vy(a10))}var vA=0;function a8(d10,b10,c10){var a10=b10[1],e10=a10===82?[0,82,l(b10[2],function(a11){return function(a12){return aR(d10,a12)}(H(a11))})]:83<=a10?aK(vD):[0,80,function(a11){return aR(d10,a11)}(H(b10[2]))];return[0,e10,c10]}function fb(d10,b10,c10){return b10?[0,[0,80,function(a10){return aR(d10,a10)}(H(b10[1]))],c10]:c10}function iF(a10,b10){var c10=b10[1];return c10===82?[0,82,l(b10[2],a10)]:83<=c10?[0,83,eT(a10,b10[2])]:[0,80,h(a10,b10[2])]}function vF(a10){return a10[0]===0?aS(H(a10[1])):a10[1]}function fc(a10,b10){return[0,iF(vF,a10),b10]}function au(a10){return fc(a10,0)}function ds(a10,b10){return fc(a10,b10)}function vB(a10,b10){var d10=vz(b10[1]),e10=b10[2],c10=function(a11){return bB(e10,a11)}(d10);return a10?[0,[0,80,tg(H(a10[1]))],c10]:c10}function vC(a10){return[0,vx(a10),vA]}function vE(a10,b10,c10){return b10?[0,[0,80,a10],c10]:c10}function vG(a10){return fc(iF(function(a11){return[0,a11]},a10),0)}function vH(a10,b10){return b10[0]===0?(a10.scroll(0,b10[1]),0):tq(0,b10[1])}function vI(a10,b10,c10,d10,e10){var g10=a10?a10[1]:0,h10=b10?b10[1]:0,f10=am(1),i10=ds(vJ,ds([0,82,l(f10,function(a11){return a11?[1,aS("locked")]:[1,di]})],g10)),j10=vG(vK),k10=[0,[0,80,aB(0,dh,function(a11){return ac(f10,1)})],0],m10=R(0,[0,j10],[0,k10],0,[0,[0,82,e8(0,0,0,0,[0,[0,80,bo(0,vL)],0])],0]),n10=aB(0,s$,function(a11){var b11=bM(f10);return b11&&ac(f10,0)});return R(0,[0,i10],[0,[0,[0,80,n10],h10]],c10,[0,[0,82,l(vi(e10,f10,d10),function(a11){var b11=a11[1],c11=a11[3];return a11[2]&&uI(function(a12){return vH(b11,a12)},c11),b11})],[0,[0,82,m10],0]])}function dt(a10,b10){return typeof b10=="number"?0:b10[0]===0?[0,h(a10,b10[1])]:[1,b10[1]]}function vM(e10,b10,c10){var d10=am(c10);return[0,aB(0,b10,function(a10){return ac(d10,h(e10,eY(a10)[dE]))}),d10]}function iG(a10,b10,c10,d10,e10,f10,g10,h10,i10,j10){var l10=d10?d10[1]:0,m10=f10?f10[1]:0,n10=function(a11){return fb(u9,h10,a11)}(function(a11){return vE(th,m10,a11)}([0,[0,80,tj(H(i10))],l10])),o10=uK(b10,function(a11){return[0,a11]}),k10=vM(a10,g10,j10),p10=k10[2],q10=k10[1];return[0,ij(c10,[0,n10],[0,[0,[0,80,q10],uL(e10)]],0,0),p10,o10]}function du(a10,b10,c10,d10,e10,f10,g10,h10){var i10=c10?c10[1]:0,j10=function(a11){return fb(e3,h10,a11)}(function(a11){return fb(te,g10,a11)}(i10));return iG(aA,a10,b10,[0,j10],d10,e10,s9,f10,vO,uJ(vN,h10))}function dv(a10,b10,c10,d10){var e10=b10?b10[1]:0;return iG(function(a11){return 0},0,a10,[0,a8(e3,d10,e10)],c10,0,eZ,0,vP,0)}function aC(a10,b10){return l(a10,function(a11){return[0,a11,b10]})}function dw(a10,b10,c10,d10){return function(g10){var i10=[0,[0,cg,function(a11){return a11}],function(a11,b11){var c11=b11[2],d11=a11[2];return[0,az(a11[1],b11[1]),function(a12){return h(c11,h(d11,a12))}]}];function j10(a11){var b11=a11[1],c11=a11[2];function d11(a12){var c12=bM(b11[2]);return h(b11[3],c12)}return[0,J(b11[1]),function(a12){var b12=d11(0);return h(h(c11,a12),b12)}]}var e10=function(a11){return bj(j10,i10,a11)}(bk(d10[2])),f10=[0,82,l(e10,function(a11){var b11=a11[2];return aB(0,u8,function(a12){return h(g10,h(b11,d10[1])),s7(a12)})})],k10=l(e10,function(a11){return a11[1]}),m10=uH([0,f10,0],function(a11){return lS(f10,a11)},c10);return t2(a10,b10,[0,m10],0,[0,[0,83,bk(k10)],0])}}function iH(a10,b10){return a10?h(B(vQ),b10):b10}function vR(a10,b10,c10,d10){var e10=a10?a10[1]:1,f10=b10?b10[1]:0,g10=c10?c10[1]:0;return function(a11){var b11=iH(1,d10[1]),h10=iH(0,d10[1]),c11=e10?iE(b11,d10[2]):am(d10[2]),i10=d10[3];ik(0,[0,[0,[0,80,h6(H(b11))],0]],0,0,i10);var j10=[0,80,h10],k10=function(a12){return a8(e2,vS,a12)}(function(a12){return a8(h4,j10,a12)}(a8(e1,[0,80,b11],f10))),m10=[0,[0,80,aB(0,eZ,function(a12){return ac(c11,aA(eY(a12)[dE]))})],g10];return[0,t4(0,[0,k10],[0,m10],0,[0,[0,83,bk(eT(function(a12){var b12=a12[1],d11=a12[2],e11=au([0,80,[1,tk(H(b12))]]),f11=ds([0,82,l(c11,function(a13){return[1,tc(t9(a13,b12),ti)]})],e11);return t3(0,[0,f11],0,0,[0,[0,80,bo(0,d11)],0])},a11))],0]),,c11]}}function iI(a10,b10,c10,d10,e10,f10,g10){var m10=b10?b10[1]:0,n10=c10?c10[1]:function(a11){},j10=h(uB(vT),d10);function k10(a11){return a11?[0,e10]:0}a:{if(a10&&a10[1]){var o10=iE(j10,k10(g10)),i10=o10;break a}var i10=am(k10(g10))}var p10=ik(0,[0,[0,[0,80,h6(H(j10))],0]],0,0,f10),q10=[0,80,d10],r10=function(a11){return a8(e2,vU,a11)}(function(a11){return a8(h4,q10,a11)}(a8(e1,[0,80,j10],0))),s10=[0,[0,82,l(i10,function(a11){return a11?tf:di})],r10];return[0,R(0,0,0,0,[0,[0,82,ij(0,[0,s10],[0,[0,[0,80,aB(0,eZ,function(a11){var b11=k10(eY(a11)[jl]|0);return h(n10,b11),ac(i10,b11)})],m10]],0,0)],[0,[0,82,p10],0]]),i10]}function vV(a10){var d10=ed(a10);return[0,,function(a11){return uX(a11[1])},function(a11){},,function(a11,b10,c10){var e10=d10[4].call(null,b10,c10,a11[2]);return[0,it(b10,a11[1]),e10]},function(a11){var c10=uV(a11[1]);if(!c10)return[0,a11,0];var e10=c10[1],b10=e10[2],f10=e10[1],g10=[0,[0,b10,d10[28].call(null,b10,a11[2])]];return[0,[0,f10,d10[7].call(null,b10,a11[2])],g10]},function(a11,b10){return d10[29].call(null,b10,a11[2])}]}function vW(a10){var b10=vV(a10);return[0,function(a11){b10[3].call(null,0),b10[3].call(null,0)}]}function vY(a10){return bj(function(a11){return J(R(0,0,0,0,a11[3]))},aQ,a10)}function vZ(a10){return c4(bj(function(a11){return a11[2]},[0,v3,function(a11,b10){return i(B(v2),a11,b10)}],a10),function(a11){return i(B(v1),v0,a11)})}ix(0)(v7);function vX(a10,b10,c10){return[0,a10,b10,c10]}function v4(a10){return vZ(a10[1][1])}function v5(a10){var b10=iw(a10[2]),c10=[0,[0,80,aS(jk)],0],d10=[0,[0,80,aS("lwdui-lazy-table-header")],c10],e10=[0,[0,80,dj(H(h(B(v6),b10)))],d10];return R(0,[0,e10],0,0,[0,[0,83,bk(vY(a10[1][1]))],0])}var v8=vW([0,uC]),dx=k.yjs;function v9(d10,b10,c10){return function(a10){var r10=a10[3],s10=a10[2],f10=iy(0),g10=iy(0),k10=iw(d10[2]),u10=h(B(v$),k10),v10=cf(function(a11,b12){return J([0,eG(a11),a11,r10])},aQ,s10);es(0,2048),function(a11){return v8[1].call(null,50)}(0);var e10=am(0),m10=Q(function(a11){return a11}),b11=eC(0,qR(m10,e10));eD(b11,function(a11){var c11=bO(b11);return c11[2]?h(c11[1],0):0}),bO(b11);function t10(a11){return i(B(v_),k10,a11)}function j10(a11){var b12=[0,aS("row_spacer"),0];return h$(0,[0,[0,dj(H(t10(a11))),b12]],0)}var w10=l(bj(function(a11){var b12=a11[1],c11=a11[3],d11=a11[2],e11=a8(ck,wa,0),f11=[0,80,dj(H(u10))];return b12?[0,0,J(R(0,[0,[0,f11,e11]],0,0,[0,[0,83,bk(i(c11,d11,b12[1]))],0])),0]:[0,1,cg,0]},[0,[0,0,cg,0],function(a11,b12){var f11=b12[3],g11=b12[2],c11=b12[1],d11=a11[3],e11=a11[2],h10=a11[1],k11=hF(e11),i10=hF(g11);if(typeof k11=="number")return typeof i10=="number"?[0,((h10+d11|0)+c11|0)+f11|0,e11,0]:[0,(h10+d11|0)+c11|0,g11,f11];if(typeof i10=="number")return[0,h10,e11,(d11+c11|0)+f11|0];var l10=dr(d11+c11|0,0)?function(a12){return az(e11,a12)}(az(J(Q(j10(d11+c11|0))),g11)):az(e11,g11);return[0,h10,l10,f11]}],v10),function(a11){var b12=a11[3],c11=a11[2],d11=a11[1],e11=dr(d11,0)?az(J(Q(j10(d11))),c11):c11;return dr(b12,0)?az(e11,J(Q(j10(b12)))):e11}),x10=v5(d10),y10=u7(function(a11,b12){var d11=lT(a11);u1(d11);var c11=uY(u0(d11)),f11=bM(e10);return f11?t6(f11[1],c11)?ac(e10,[0,c11]):0:ac(e10,[0,c11])}),z10=au(wb),n10=R(0,[0,z10],0,[0,function(a11){return iz(f10,a11)}],[0,[0,83,bk(w10)],0]),o10=au(wc),p10=[0,[0,82,l(m10,function(c11){return aB(0,s_,function(a11){var d11=[0,0],b12=[0,-1];function e11(e12){var a12=800,f11=tH(tI);t7(b12[1],0)&&tL(b12[1]),b12[1]=tK(a12,function(a13){return h(c11,e12)});var g11=t8(f11-d11[1],a12);return g11&&(d11[1]=f11,h(c11,e12))}return iA(g10),function(a12){return e11(a12)}(0),0})})],0];function q10(a11){return iz(g10,a11)}var A2=c10?vI([0,o10],[0,p10],[0,q10],l(c10[1],function(a11){var b12=iA(f10),c11=d10[2];return[0,[0,cC(a11,uE(ix([0,b12])(c11)))]]}),n10):R(0,[0,o10],[0,p10],[0,q10],[0,[0,82,n10],0]);function C2(a11){return u6(y10,0,a11)}function D2(a11){return u_(C2,a11)}var E2=function(a11){return l(a11,D2)}(A2),F2=vB(0,vC(wd));return R(0,[0,[0,[0,82,l(v4(d10),function(a11){return dj(H(a11))})],F2]],0,0,[0,[0,82,x10],[0,[0,82,E2],0]])}}var fd=ed([0,ec]),fe=dx.Text,ff=dx[jU],fg=dx.Map,bU=hl(wi,wh),a9=hl(wk,wj);function we(a10,b10){return[0,a10,b10]}function iJ(a10){return bS(a10,ff)?[0,aW,a10]:bS(a10,fg)?[0,v,a10]:bS(a10,fe)?[0,bv,a10]:[0,T,a10]}function wl(a10){var b10=eW(a10,wm);if(b10)return[0,b10[1]];var c10=eW(a10,wn);if(c10)return[1,hW(iJ,c10[1])];var d10=eW(a10,wo);if(d10)return[2,d10[1]];throw g([0,f,wp],1)}hn(wq,bU,[0,function(a10){return new ff},function(a10,b10,c10){return a10.insert(b10,hX(function(a11){var b11=a11[1];return bv<=b11?(aW<=b11,a11[2]):(v<=b11,a11[2])},c10)),0},function(a10,b10,c10){return a10.delete(b10,c10),0},function(a10,b10){return a10.push(hX(function(a11){var b11=a11[1];return bv<=b11?(aW<=b11,a11[2]):(v<=b11,a11[2])},b10)),0},function(a10,d10){return a10.forEach(function(a11,b10,c10){return x(d10,b10,iJ(a11),c10)}),0},function(a10,b10){function c10(a11){return h(b10,we(wl,a11))}return a10.observe(c10),c10}]);function fh(a10){return bS(a10,ff)?[0,aW,a10]:bS(a10,fg)?[0,v,a10]:bS(a10,fe)?[0,bv,a10]:[0,T,a10]}function iK(a10,b10){return function(a11){return dg(fh,a11)}(a10.get(C(b10)))}function wr(a10){return a10}function ws(a10){return a10[fv]}function wt(a10){var b10=aA(a10.action);if(b10!=="add")if(b10!==jF){if(b10!=="update")throw g([0,cH,h(B(wu),b10)],1);var c10=1}else var c10=2;else var c10=0;var d10=a10.oldValue,e10=bR(d10)?0:[0,fh(d10)];return[0,c10,0,e10]}function iL(a10){return s3(a10.entries())}hn(wv,a9,[0,function(a10){return new fg},[0,function(d10){var a10=d10[jM].keys.entries();return hZ(aA,wt,function(a11,b10,c10){var e10=iK(ws(d10),a11);return fd[4].call(null,a11,[0,b10[1],e10,b10[3]],c10)},a10,fd[1])}],iK,function(a10,b10,c10){var d10=c10[1],e10=bv<=d10?(aW<=d10,c10[2]):(v<=d10,c10[2]);return a10.set(C(b10),e10),0},function(a10,b10){return a10.delete(C(b10)),0},iL,function(a10,d10,c10){return hZ(aA,fh,function(a11,b10,c11){return x(d10,a11,b10,c11)},iL(a10),c10)},function(a10,b10){function c10(a11){return h(b10,a11)}return a10.observe(c10),c10}]);var ww=dx.Doc;function iM(a10,b10){return a10.getArray(C(b10))}function bq(a10,b10){return a10.transact(by(1,b10)),0}function iN(a10){return a10}var ai=a9[4],aT=a9[3],cl=a9[1],dy=bU[5],fi=bU[4],iO=bU[3],iP=bU[1];function wf(a10){var b10=a10[1];return[0,function(a11){return hW(b10,a11)}(a10[2][jM].delta)]}function wg(a10,b10){var c10=a10?[0,C(a10[1])]:[0];return zS(fe,c10)}function wx(a10){return new ww}var wy=a9[8],wz=a9[7],wA=a9[5],wB=a9[2][1],wC=bU[6];function wD(a10){return a10}var wE=k.IndexeddbPersistence;function wF(a10,b10){var c10=b10;new wE(C(a10),c10)}var wG=k.WebrtcProvider;function wH(a10,b10,c10){var e10=lH(function(a11){return[0,wI,hY(C,a11)]},b10),d10=[0,[0,wL,{config:{iceServers:hY(function(a11){return a11},cM(function(a11){return{urls:C(h(B(wK),a11))}},wJ))}}]];ah([0,d10,0]);var f10=k$(gL(l0(function(a11){return a11})([0,e10,[0,d10,0]]))),g10=c10;return new wG(C(a10),g10,f10)}var iQ=k.Quill,wM=k.QuillCursors;function wN(a10,b10){iQ.register(C(a10),b10)}function wO(a10,b10,c10){var d10=a10?a10[1]:0,e10=d10?wP:wR,f10=b10?[0,[0,wQ,!!b10[1]]]:[0],g10=k$(f10);return{theme:C(e10),modules:g10}}function wS(a10,b10){return new iQ(a10,b10)}function wT(a10){return a10}var wU=k.QuillBinding;function wV(a10,b10){var c10=b10;new wU(a10,c10)}function wW(a10,b10,c10){return x(eo(t,wX),b10,c10,a10)}function iR(a10,b10,c10){var d10=0<=c10?1:0;if(d10)var e10=0<=b10?1:0,f10=e10&&((b10+c10|0)<=a10?1:0);else var f10=d10;var g10=1-f10;return g10&&wW(a10,b10,c10)}var wY=[0];function wZ(a10,b10,c10,d10){var e10=ap(a10,b10);return cP(c10,0,e10,0,d10),e10}function iS(a10,b10){return b10<=a10?a10:b10}function iT(a10){return eo(t,a10)}function w0(a10,b10){var c10=a10[1];return i(iT(w1),b10,c10)}function w2(a10,b10){return i(iT(w3),a10,b10.length-1)}function cm(a10,b10){var c10=1-(a10<=b10.length-1?1:0);return c10&&w2(a10,b10)}function iU(a10){return[0,0,0,wY]}function cn(a10){return a10[1]}function w4(a10,b10){return a10[3][1+b10]}function iV(a10){var b10=a10[1],c10=a10[3];if(cm(b10,c10),0>>4|0));var f11=b11+1|0;function i11(a11,b12,c12){a0(a11,b12,c12)}return function(a11){return i11(d11,f11,a11)}(h10(g10,c11&15))}for(;!(4<=d10[1]);){var n10=y(b10,d10[1]);f10(e10,c10[1],n10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(6<=d10[1]);){var m10=y(b10,d10[1]);f10(e10,c10[1],m10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(8<=d10[1]);){var l10=y(b10,d10[1]);f10(e10,c10[1],l10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(10<=d10[1]);){var k10=y(b10,d10[1]);f10(e10,c10[1],k10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;;){if(16<=d10[1])return $(e10);var j10=y(b10,d10[1]);f10(e10,c10[1],j10),c10[1]=c10[1]+2|0,d10[1]++}}var xf=gU(0),an=wx(0);wN(xh,wM);var dz=wH(xj,xi,an);wF(xk,an),dn.yjsdoc=an,dn.yjsprovider=dz,dz.on(C(xm),by(1,function(a10){return ah(xl)})),dz.on(C(xo),by(1,function(a10){return ah([0,xn,[0,a10,0]])})),dz.on(C(xq),by(1,function(a10){return ah([0,xp,[0,a10,0]])}));function xg(a10){return xc(xf,0)}function xr(a10,b10){var c10=a10?a10[1]:64,d10=hw(0);return[0,d10,es(0,c10)]}function iY(a10,b10,c10){var e10=g1(a10[2],b10);if(e10)var d10=e10[1];else{var g10=eF(0,a10[1]);g2(a10[2],b10,g10);var d10=g10}var f10=eG(d10);return f10?ac(f10[1][2],[0,c10]):rG(d10,[0,b10,am([0,c10])])}function fk(a10,b10){var c10=g1(a10[2],b10);if(c10)var d10=c10[1];else{var f10=a10[1],e10=eF([0,[0,b10,am(0)]],f10);g2(a10[2],b10,e10);var d10=e10}return cL(eG(d10))[2]}function fl(a10,b10){return l(fk(a10,b10),function(a11){if(!a11)return 0;var b11=a11[1];if(typeof b11!="number"&&T===b11[1])return[0,aA(b11[2])];throw g([0,f,xs],1)})}function xt(a10){var b10=hw(0);return[0,b10,iU(0)]}function xu(a10){try{var c10=[0,iX(a10[2],0)];return c10}catch(f10){var b10=L(f10);if(b10[1]===cH)return 0;throw g(b10,0)}}function iZ(a10,b10){var c10=eF(a10,b10[1]);return w7(b10[2],c10)}function i0(a10,b10,c10,d10){var e10=[0,b10,[0,c10,[0,cn(d10),0]]];e4([0,xv,[0,cn(a10),e10]]);var f10=cn(d10),g10=iX(a10,0);return fj(d10,gI(c10,function(a11){return g10})),w$(a10,b10,d10,f10,c10)}function xw(i10,b10,c10){var e10=[0,0],j10=i10[2],d10=iU(0);gJ(function(a11){switch(a11[0]){case 0:var m10=a11[1];return i0(j10,e10[1],m10,d10),e10[1]=e10[1]+m10|0,0;case 1:var c11=a11[1];if(cn(d10)!==0){var o10=[0,iV(d10)];return fj(d10,gK(function(a12){var d11=h(b10,a12),c12=rC([0,d11],o10[1]);return o10[1]=c12,c12},c11))}var n10=xu(i10);if(!n10)return gJ(function(a12){var c12=h(b10,a12);return iZ([0,c12],[0,i10[1],d10])},c11);var s10=n10[1];return fj(d10,gK(function(a12){return rA([0,h(b10,a12)],s10)},c11));default:var k11=a11[1],t10=e10[1]===0?sj(i10[1]):hD(iV(d10)),p10=[0,t10],u10=1;if(k11>=1)for(var l10=u10;;){var q10=p10[1];if(!q10)throw g([0,f,xx],1);var r10=q10[1];p10[1]=hD(r10),rJ(r10);var v10=l10+1|0;if(k11===l10)break;l10=v10}return e10[1]=e10[1]+k11|0,0}},c10);var k10=e10[1],a10=cn(j10)-k10|0;return 0 ",yn=[0,0],yl=[0,0],ym=[0,80,"Update"],yh=e,yi=e,yj=[0,80,[0,"cell-edit-btn"]],yk="\xE2\x9C\x8F\xEF\xB8\x8F",yq=[0,80,[0,"cell-edit-overlay"]],yr=[0,80,[0,fI]],x4="GET",x3=[0,c,419,17],x2=[0,c,434,11],x7=[0,c,449,19],x6=[0,c,kE,13],x5=[0,c,439,13],x8=[0,c,466,11],yc=[0,c,484,19],yb=[0,c,479,19],x9=[0,c,472,13],x$=[0,c,488,15],ya=[0,c,kB,15],x_=[0,c,493,11],ye=e,yf=[0,c,505,17],yd=[0,c,508,11],xX=cq,xY=j1,xR="New column kind:",xP=[0,c,294,13],xL=dK,xM=bW,xN=dH,xO=cs,xH="Old value:",xI="Action: delete",xJ="Key:",xK=[0,c,219,15],xG="On_change",xF=[0,c,144,22],xD="[blit v(%i) %i %i v'(%i)]",xA=[0,c,87,18],xx="PEERS",xv="STATUS",xt=[0,"SYNCED!",0],xp="modules/cursors",xq=[0,[0,"wss://p2p.u31.fr",0]],xr="testroom5267564",xs="zedoc",xu="synced",xw="status",xy="peers",xU=cq,xV=j1,ze=[0,80,"Add table"],zh=[0,80,[0,jz]];function z(a10){if(typeof a10=="number")return 0;switch(a10[0]){case 0:return[0,z(a10[1])];case 1:return[1,z(a10[1])];case 2:return[2,z(a10[1])];case 3:return[3,z(a10[1])];case 4:return[4,z(a10[1])];case 5:return[5,z(a10[1])];case 6:return[6,z(a10[1])];case 7:return[7,z(a10[1])];case 8:var c10=a10[1];return[8,c10,z(a10[2])];case 9:var b10=a10[1];return[9,b10,b10,z(a10[3])];case 10:return[10,z(a10[1])];case 11:return[11,z(a10[1])];case 12:return[12,z(a10[1])];case 13:return[13,z(a10[1])];default:return[14,z(a10[1])]}}function W(a10,b10){if(typeof a10=="number")return b10;switch(a10[0]){case 0:return[0,W(a10[1],b10)];case 1:return[1,W(a10[1],b10)];case 2:return[2,W(a10[1],b10)];case 3:return[3,W(a10[1],b10)];case 4:return[4,W(a10[1],b10)];case 5:return[5,W(a10[1],b10)];case 6:return[6,W(a10[1],b10)];case 7:return[7,W(a10[1],b10)];case 8:var c10=a10[1];return[8,c10,W(a10[2],b10)];case 9:var d10=a10[2],e10=a10[1];return[9,e10,d10,W(a10[3],b10)];case 10:return[10,W(a10[1],b10)];case 11:return[11,W(a10[1],b10)];case 12:return[12,W(a10[1],b10)];case 13:return[13,W(a10[1],b10)];default:return[14,W(a10[1],b10)]}}function w(a10,b10){if(typeof a10=="number")return b10;switch(a10[0]){case 0:return[0,w(a10[1],b10)];case 1:return[1,w(a10[1],b10)];case 2:var c10=a10[1];return[2,c10,w(a10[2],b10)];case 3:var d10=a10[1];return[3,d10,w(a10[2],b10)];case 4:var e10=a10[3],f10=a10[2],g10=a10[1];return[4,g10,f10,e10,w(a10[4],b10)];case 5:var h10=a10[3],i10=a10[2],j10=a10[1];return[5,j10,i10,h10,w(a10[4],b10)];case 6:var k10=a10[3],l10=a10[2],m10=a10[1];return[6,m10,l10,k10,w(a10[4],b10)];case 7:var n10=a10[3],o10=a10[2],p10=a10[1];return[7,p10,o10,n10,w(a10[4],b10)];case 8:var q10=a10[3],r10=a10[2],s10=a10[1];return[8,s10,r10,q10,w(a10[4],b10)];case 9:var t10=a10[1];return[9,t10,w(a10[2],b10)];case 10:return[10,w(a10[1],b10)];case 11:var u10=a10[1];return[11,u10,w(a10[2],b10)];case 12:var v10=a10[1];return[12,v10,w(a10[2],b10)];case 13:var x10=a10[2],y10=a10[1];return[13,y10,x10,w(a10[3],b10)];case 14:var z10=a10[2],A2=a10[1];return[14,A2,z10,w(a10[3],b10)];case 15:return[15,w(a10[1],b10)];case 16:return[16,w(a10[1],b10)];case 17:var B2=a10[1];return[17,B2,w(a10[2],b10)];case 18:var C2=a10[1];return[18,C2,w(a10[2],b10)];case 19:return[19,w(a10[1],b10)];case 20:var D2=a10[2],E2=a10[1];return[20,E2,D2,w(a10[3],b10)];case 21:var F2=a10[1];return[21,F2,w(a10[2],b10)];case 22:return[22,w(a10[1],b10)];case 23:var G2=a10[1];return[23,G2,w(a10[2],b10)];default:var H2=a10[2],I2=a10[1];return[24,I2,H2,w(a10[3],b10)]}}function d4(a10){return[0,a10]}function cG(a10){return a10[1]}function d5(a10,b10,c10){return a10[1]===b10?(a10[1]=c10,1):0}function aK(a10){throw g([0,b3,a10],1)}function t(a10){throw g([0,cH,a10],1)}function cI(a10){return 0<=a10?a10:-a10|0}var gv=kC;function ay(a10,b10){return a10+b10}function lw(b10){var e10=n(b10);return function(a10){for(var c10=a10;;){if(e10<=c10)return ay(b10,lx);var d10=y(b10,c10);a:{if(48<=d10){if(58>d10)break a}else if(d10===45)break a;return b10}c10=c10+1|0}}(0)}function gw(a10,b10){if(!a10)return b10;var c10=a10[1];return[0,c10,gw(a10[2],b10)]}z$(0);var lz=le(1),at=le(2);function b5(a10,b10){gj(a10,b10,0,n(b10))}function gx(a10){return b5(at,a10),lf(at,10),bz(at)}var d7=d4(function(a10){return function(a11){for(var b10=a11;;){if(!b10)return 0;var d10=b10[2],e10=b10[1];try{bz(e10)}catch(f10){var c10=L(f10);if(c10[1]!==gu)throw g(c10,0)}b10=d10}}(Aa(0))});function d8(a10){return h(cG(d7),0)}go(j6,d8);function ls(a10){return a10^-1}function lt(a10){return a10?lu:lv}function ly(a10){return lw(ga("%.12g",a10))}function lA(a10,b10,c10,d10){return 0<=c10&&0<=d10&&(n(b10)-d10|0)>=c10?gj(a10,b10,c10,d10):t(lB)}function lC(c10){for(;;){var d10=d4(1),a10=cG(d7);let e10=d10,f10=a10;var b10=1-d5(d7,a10,function(a11){return d5(e10,1,0)&&h(c10,0),h(f10,0)});if(!b10)return b10}}function cJ(a10){return bz(a10)}function lD(a10,b10){lf(a10,b10)}var d9=Ao(0),b6=(4*d9|0)-1|0;function lE(a10){return 1-(typeof a10=="number"?1:0)}var lG=[q,lF,ae(0)];function lH(a10){throw g(lG,1)}function cK(a10){var d10=a10[1];a10[1]=lH;try{var c10=h(d10,0);return Ag(a10,c10),c10}catch(f10){var b10=L(f10);throw a10[1]=function(a11){throw g(b10,0)},g(b10,0)}}function lI(a10){var b10=aw(a10);return b10!==aD&&b10!==ba&&b10!==ko?a10:z3(a10)}function cL(a10){return a10?a10[1]:t(lJ)}function d_(a10,b10){return b10?[0,h(a10,b10[1])]:0}function gy(a10){return a10?1:0}function lK(a10,b10){return a10===b10?1:0}function lL(a10){a:{if(40<=a10){if(a10===92)return lM;if(f2>a10)break a}else{if(32<=a10){if(39<=a10)return lN;break a}if(14>a10)switch(a10){case 8:return lO;case 9:return lP;case 10:return lQ;case 13:return lR}}var b10=F(4);return B(b10,0,92),B(b10,1,48+(a10/fL|0)|0),B(b10,2,48+((a10/10|0)%10|0)|0),B(b10,3,48+(a10%10|0)|0),d1(b10)}var c10=F(1);return B(c10,0,a10),d1(c10)}function lS(a10){return 25>>0?a10:a10+kK|0}function lT(a10,b10){for(var d10=a10,c10=b10;;){if(!c10)return d10;d10=d10+1|0,c10=c10[2]}}function gz(a10){return lT(0,a10)}function bB(a10,b10){for(var c10=a10,d10=b10;;){if(!c10)return d10;var e10=[0,c10[1],d10];c10=c10[2],d10=e10}}function a3(a10){return bB(a10,0)}function gA(a10,b10,c10){if(b10<=a10)return 0;var d10=h(c10,a10);return[0,d10,gA(a10+1|0,b10,c10)]}function lU(a10,b10){return[0,a10,b10]}function lV(a10){return a10?a10[1]:aK(lW)}function lX(a10,b10,c10,d10){for(var f10=a10,e10=b10;;){if(c10<=e10)return f10;f10=[0,h(d10,e10),f10],e10=e10+1|0}}function d$(a10){if(!a10)return 0;var b10=a10[1];return gw(b10,d$(a10[2]))}function cM(a10,b10){if(!b10)return 0;var c10=b10[2],d10=h(a10,b10[1]);return[0,d10,cM(a10,c10)]}function a4(a10,b10){for(var c10=b10;;){if(!c10)return 0;var d10=c10[2];h(a10,c10[1]),c10=d10}}function gB(a10,b10,c10){for(var e10=b10,d10=c10;;){if(!d10)return e10;var f10=d10[2];e10=i(a10,e10,d10[1]),d10=f10}}function gC(g10){function b10(a10,b11){for(var d10=a10,c11=b11;;){if(!c11)return a3(d10);var e10=c11[2],f10=h(g10,c11[1]);f10&&(d10=[0,f10[1],d10]),c11=e10}}var c10=0;return function(a10){return b10(c10,a10)}}function lY(a10,b10){return 0<=a10?50>1,s10=p10(r10,b11),D2=s10[1],t10=p10(a11-r10|0,s10[2]),E2=t10[2];return[0,B2(D2,t10[1],0),E2]}function p10(a11,b11){if(a11===2){if(b11){var j10=b11[2];if(j10){var k10=j10[1],g10=b11[1],B3=j10[2],q10=i(d10,g10,k10),C2=q10===0?[0,g10,0]:0>1,s10=h10(r10,b11),D2=s10[1],t10=h10(a11-r10|0,s10[2]),E2=t10[2];return[0,A2(D2,t10[1],0),E2]}var a10=gz(b10);return 2<=a10?h10(a10,b10)[1]:b10}function gD(a10,b10){return b10<=a10?a10:b10}function gE(a10){return e+a10}function l4(a10,b10){return k_(a10,b10)}function l5(a10,b10){return a10<=b10?a10:b10}function bh(a10,b10){var c10=F(a10);return zC(c10,0,a10,b10),c10}var l6=F(0);function gF(a10){var b10=aq(a10),c10=F(b10);return aZ(a10,0,c10,0,b10),c10}function ea(a10,b10,c10){if(0<=b10&&0<=c10&&(aq(a10)-c10|0)>=b10){var d10=F(c10);return aZ(a10,b10,d10,0,c10),d10}return t(l8)}function eb(a10,b10,c10){return d1(ea(a10,b10,c10))}function gG(a10,b10,c10,d10,e10){if(0<=e10&&0<=b10&&(aq(a10)-e10|0)>=b10&&0<=d10&&(aq(c10)-e10|0)>=d10){aZ(a10,b10,c10,d10,e10);return}return t(l9)}function aL(a10,b10,c10,d10,e10){if(0<=e10&&0<=b10&&(n(a10)-e10|0)>=b10&&0<=d10&&(aq(c10)-e10|0)>=d10){cy(a10,b10,c10,d10,e10);return}return t(l_)}function gH(a10){var b10=a10-9|0;a:{if(4>>0){if(b10!==23)break a}else if(b10===2)break a;return 1}return 0}function mb(a10,b10){var d10=aq(b10);if(d10===0)return b10;var e10=F(d10),f10=d10-1|0,g10=0;if(f10>=0)for(var c10=g10;;){B(e10,c10,h(a10,bY(b10,c10)));var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function gI(a10,b10,c10){zx(a10,b10,zP(c10))}function gJ(a10,b10,c10){a0(a10,b10,c10)}function gK(a10,b10){return zw(a10,b10)}function cN(a10){return bd(a10)}function $(a10){return d1(a10)}function l7(a10){return gF(bd(a10))}function l$(a10){for(var d10=aq(a10),b10=[0,0];!(b10[1]>=d10||!gH(bY(a10,b10[1])));)b10[1]++;for(var c10=[0,d10-1|0];;){if(b10[1]<=c10[1]&&gH(bY(a10,c10[1]))){c10[1]--;continue}return b10[1]<=c10[1]?ea(a10,b10[1],(c10[1]-b10[1]|0)+1|0):l6}}function ma(a10){var b10=[0,0],j10=aq(a10)-1|0,l10=0;if(j10>=0)for(var g10=l10;;){var e10=bY(a10,g10);a:{b:{c:{if(32<=e10){var h10=e10-34|0;if(58>>0){if(93<=h10)break c}else if(56>>0)break b;var i10=1;break a}if(11<=e10){if(e10===13)break b}else if(8<=e10)break b}var i10=4;break a}var i10=2}b10[1]=b10[1]+i10|0;var o10=g10+1|0;if(j10===g10)break;g10=o10}if(b10[1]===aq(a10))return gF(a10);var c10=F(b10[1]);b10[1]=0;var k10=aq(a10)-1|0,m10=0;if(k10>=0)for(var f10=m10;;){var d10=bY(a10,f10);a:{b:{c:{if(35<=d10){if(d10!==92){if(f2<=d10)break c;break b}}else{if(32>d10){if(14<=d10)break c;switch(d10){case 8:B(c10,b10[1],92),b10[1]++,B(c10,b10[1],98);break a;case 9:B(c10,b10[1],92),b10[1]++,B(c10,b10[1],116);break a;case 10:B(c10,b10[1],92),b10[1]++,B(c10,b10[1],110);break a;case 13:B(c10,b10[1],92),b10[1]++,B(c10,b10[1],114);break a;default:break c}}if(34>d10)break b}B(c10,b10[1],92),b10[1]++,B(c10,b10[1],d10);break a}B(c10,b10[1],92),b10[1]++,B(c10,b10[1],48+(d10/fL|0)|0),b10[1]++,B(c10,b10[1],48+((d10/10|0)%10|0)|0),b10[1]++,B(c10,b10[1],48+(d10%10|0)|0);break a}B(c10,b10[1],d10)}b10[1]++;var n10=f10+1|0;if(k10===f10)break;f10=n10}return c10}function mc(a10){return mb(lS,a10)}function cO(a10,b10){return $(bh(a10,b10))}function ec(a10,b10,c10){return $(ea(cN(a10),b10,c10))}function gL(a10){var b10=a10-9|0;a:{if(4>>0){if(b10!==23)break a}else if(b10===2)break a;return 1}return 0}function mf(a10,b10,c10,d10){for(var e10=c10;;){if(b10<=e10)throw g(ax,1);if(_(a10,e10)===d10)return e10;e10=e10+1|0}}function mg(a10,b10,c10){var d10=n(a10);if(0<=b10&&d10>=b10)try{mf(a10,d10,b10,c10);var f10=1;return f10}catch(f11){var e10=L(f11);if(e10===ax)return 0;throw g(e10,0)}return t(mh)}function ed(a10,b10){return lk(a10,b10)}function md(a10){return a10==e||!gL(_(a10,0))&&!gL(_(a10,n(a10)-1|0))?a10:$(l$(cN(a10)))}function me(a10){return function(a11,b10,c10){for(var d10=c10;;){if(b10<=d10)return a11;var e10=_(a11,d10)+kK|0;a:{if(59>>0){if(33>>0)break a}else if(e10===2)break a;d10=d10+1|0;continue}return $(ma(cN(a11)))}}(a10,n(a10),0)}function mi(a10,b10){return mg(a10,0,b10)}function mj(a10){return $(mc(cN(a10)))}function mk(a10,b10){return a10==b10?1:0}function gM(a10,b10){if(a10===0)return[0];if(0>a10)return t(ml);var d10=ap(a10,h(b10,0)),e10=a10-1|0,f10=1;if(e10>=1)for(var c10=f10;;){d10[1+c10]=h(b10,c10);var g10=c10+1|0;if(e10===c10)break;c10=g10}return d10}function cP(a10,b10,c10,d10,e10){return 0<=e10&&0<=b10&&(a10.length-1-e10|0)>=b10&&0<=d10&&(c10.length-1-e10|0)>=d10?zq(a10,b10,c10,d10,e10):t(mo)}function gN(a10,b10){var d10=b10.length-2|0,e10=0;if(d10>=0)for(var c10=e10;;){h(a10,b10[1+c10]);var f10=c10+1|0;if(d10===c10)break;c10=f10}return 0}function gO(a10,b10){var d10=b10.length-1;if(d10===0)return[0];var e10=ap(d10,h(a10,b10[1])),f10=d10-1|0,g10=1;if(f10>=1)for(var c10=g10;;){e10[1+c10]=h(a10,b10[1+c10]);var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function mp(a10,b10){for(var d10=a10,c10=b10;;){if(!c10)return d10;d10=d10+1|0,c10=c10[2]}}function ee(a10){if(!a10)return[0];var b10=a10[2],c10=a10[1],e10=ap(mp(0,a10),c10);return function(a11,b11){for(var d10=a11,c11=b11;;){if(!c11)return e10;var f10=c11[2];e10[1+d10]=c11[1],d10=d10+1|0,c11=f10}}(1,b10)}function mm(a10,b10,c10){return 0<=b10&&0<=c10&&(a10.length-1-c10|0)>=b10?zr(a10,b10,c10):t(mn)}function mq(k10){function j10(a10){return a10?a10[4]:0}function d10(a10,b11,c11){var d11=a10?a10[4]:0,e11=c11?c11[4]:0,f10=e11<=d11?d11+1|0:e11+1|0;return[0,a10,b11,c11,f10]}function l10(a10,b11,c11){var g10=a10?a10[4]:0,h10=c11?c11[4]:0;if((h10+2|0)=h10){var w10=h10<=g10?g10+1|0:h10+1|0;return[0,a10,b11,c11,w10]}if(!c11)return t(mu);var k11=c11[3],m11=c11[2],f10=c11[1],r10=j10(f10);if(r10<=j10(k11))return d10(d10(a10,b11,f10),m11,k11);if(!f10)return t(mt);var s10=f10[2],u10=f10[1],v10=d10(f10[3],m11,k11);return d10(d10(a10,b11,u10),s10,v10)}function c10(a10,b11){if(!b11)return[0,0,a10,0,1];var d11=b11[3],e11=b11[2],f10=b11[1],g10=i(k10[1],a10,e11);if(g10===0)return b11;if(0<=g10){var h10=c10(a10,d11);return d11===h10?b11:l10(f10,e11,h10)}var j11=c10(a10,f10);return f10===j11?b11:l10(j11,e11,d11)}function b10(a10){return[0,0,a10,0,1]}var m10=0;function e10(a10,b11){for(var c11=b11;;){if(!c11)return;var d11=c11[3],f10=c11[2];e10(a10,c11[1]),h(a10,f10),c11=d11}}function n10(a10,b11){for(var d11=a10,c11=b11;;){if(!c11)return d11;var e11=c11[2],f10=c11[1];d11=[0,e11,n10(d11,c11[3])],c11=f10}}function o10(a10,b11,c11){for(var d11=c11;;){if(!d11)return;var e11=d11[3],f10=d11[1];d11=h(b11,d11[2])?e11:f10}}function p10(a10){function c11(a11,b11){if(3>=a11>>>0)switch(a11){case 0:return[0,0,b11];case 1:if(b11)return[0,[0,0,b11[1],0,1],b11[2]];break;case 2:if(b11){var h10=b11[2];if(h10)return[0,[0,[0,0,b11[1],0,1],h10[1],0,2],h10[2]]}break;default:if(b11){var i10=b11[2];if(i10){var j11=i10[2];if(j11)return[0,[0,[0,0,b11[1],0,1],i10[1],[0,0,j11[1],0,1],2],j11[2]]}}}var k11=a11/2|0,l11=c11(k11,b11),e11=l11[2],n11=l11[1];if(!e11)throw g([0,f,mv],1);var o11=e11[1],m11=c11((a11-k11|0)-1|0,e11[2]),p11=m11[2];return[0,d10(n11,o11,m11[1]),p11]}return c11(gz(a10),a10)[1]}return[0,,,,c10,,,,,,,,,,,,,m10,,,,,,,,,,,,,,e10,,,,,,,,function(a10){return n10(0,a10)},,,,,,,,,,,function(a10,b11){for(var c11=b11;;){if(!c11)return;var d11=c11[2],e11=c11[3],f10=c11[1];if(h(a10,d11))return o10(d11,a10,e11);c11=f10}},,,,,,,function(a10){if(!a10)return m10;var f10=a10[2],d11=a10[1];if(!f10)return b10(d11);var g10=f10[2],e11=f10[1];if(!g10)return c10(e11,b10(d11));var h10=g10[2],i10=g10[1];if(!h10)return c10(i10,c10(e11,b10(d11)));var j11=h10[2],l11=h10[1];if(!j11)return c10(l11,c10(i10,c10(e11,b10(d11))));if(j11[2])return p10(l3(k10[1],a10));var n11=j11[1];return c10(n11,c10(l11,c10(i10,c10(e11,b10(d11)))))}]}function mw(a10){var b10=mq(a10);return[0,b10[17],,,b10[4],,,,,,,,,,b10[31],,,,,,,,,b10[39],,,,,,,,,,,,,b10[50],b10[57]]}function mx(f10){function h10(a10){return a10?a10[5]:0}function e10(a10,b10,c11,d11){var e11=h10(a10),f11=h10(d11),g10=f11<=e11?e11+1|0:f11+1|0;return[0,a10,b10,c11,d11,g10]}function d10(a10,b10,c11,d11){var i10=a10?a10[5]:0,j11=d11?d11[5]:0;if((j11+2|0)=j11){var B2=j11<=i10?i10+1|0:j11+1|0;return[0,a10,b10,c11,d11,B2]}if(!d11)return t(mB);var l11=d11[4],o11=d11[3],p10=d11[2],g10=d11[1],w10=h10(g10);if(w10<=h10(l11))return e10(e10(a10,b10,c11,g10),p10,o11,l11);if(!g10)return t(mA);var x10=g10[3],y10=g10[2],z10=g10[1],A2=e10(g10[4],p10,o11,l11);return e10(e10(a10,b10,c11,z10),y10,x10,A2)}function j10(a10,b10,c11){if(!c11)return[0,0,a10,b10,0,1];var e11=c11[4],h11=c11[3],k11=c11[2],g10=c11[1],o11=c11[5],l11=i(f10[1],a10,k11);if(l11===0)return h11===b10?c11:[0,g10,a10,b10,e11,o11];if(0<=l11){var m11=j10(a10,b10,e11);return e11===m11?c11:d10(g10,k11,h11,m11)}var n11=j10(a10,b10,g10);return g10===n11?c11:d10(n11,k11,h11,e11)}function n10(a10){for(var b10=a10;;){if(!b10)throw g(ax,1);var c11=b10[1];if(!c11)return[0,b10[2],b10[3]];b10=c11}}function c10(a10){if(!a10)return t(mC);var b10=a10[1];if(!b10)return a10[4];var e11=a10[4],f11=a10[3],g10=a10[2];return d10(c10(b10),g10,f11,e11)}function o10(a10,b10){if(!a10)return b10;if(!b10)return a10;var e11=n10(b10),f11=e11[2],g10=e11[1];return d10(a10,g10,f11,c10(b10))}function k10(a10,b10){if(!b10)return 0;var c11=b10[4],h11=b10[3],g10=b10[2],e11=b10[1],j11=i(f10[1],a10,g10);if(j11===0)return o10(e11,c11);if(0<=j11){var l11=k10(a10,c11);return c11===l11?b10:d10(e11,g10,h11,l11)}var m11=k10(a10,e11);return e11===m11?b10:d10(m11,g10,h11,c11)}function l10(a10,b10){for(var c11=b10;;){if(!c11)return 0;var d11=c11[4],e11=c11[3],f11=c11[2];l10(a10,c11[1]),i(a10,f11,e11),c11=d11}}function m10(a10,b10,c11){for(var d11=b10,e11=c11;;){if(!d11)return e11;var f11=d11[4],g10=d11[3],h11=d11[2],i10=x(a10,h11,g10,m10(a10,d11[1],e11));d11=f11,e11=i10}}return[0,,,,,0,,j10,function(a10,b10){for(var c11=b10;;){if(!c11)throw g(ax,1);var e11=c11[4],h11=c11[3],j11=c11[1],d11=i(f10[1],a10,c11[2]);if(d11===0)return h11;var k11=0<=d11?e11:j11;c11=k11}},,,,,,,,,function(a10,b10){for(var c11=b10;;){if(!c11)return 0;var e11=c11[4],g10=c11[3],h11=c11[1],d11=i(f10[1],a10,c11[2]);if(d11===0)return[0,g10];var j11=0<=d11?e11:h11;c11=j11}},,,,,,,k10,,l10,,,m10]}function ef(a10){var b10=mx(a10);return[0,b10[5],,,b10[7],,,b10[24],,,,,b10[26],b10[29],,,,,,,,,,,,,,,b10[8],b10[17]]}var eg=[q,mD,ae(0)];function bC(a10){return[0,0,0]}function b7(a10){a10[1]=0,a10[2]=0}function a5(a10,b10){return b10[1]=[0,a10,b10[1]],b10[2]=b10[2]+1|0,0}function bD(a10){var b10=a10[1];if(!b10)return 0;var c10=b10[1];return a10[1]=b10[2],a10[2]=a10[2]-1|0,[0,c10]}function bE(a10){var b10=a10[1];return b10?[0,b10[1]]:0}function mE(a10){var b10=a10[1];if(!b10)throw g(eg,1);a10[1]=b10[2],a10[2]=a10[2]-1|0}function mF(a10){if(!a10[1])throw g(eg,1)}function mG(a10,b10){return a4(a10,b10[1])}var mI=[q,mH,ae(0)];function eh(a10){return[0,0,0,0]}function ei(a10){a10[1]=0,a10[2]=0,a10[3]=0}function ej(a10,b10){var c10=[0,a10,0],d10=b10[3];return d10?(b10[1]=b10[1]+1|0,d10[2]=c10,b10[3]=c10,0):(b10[1]=1,b10[2]=c10,b10[3]=c10,0)}function gP(a10){var b10=a10[2];if(!b10)throw g(mI,1);var c10=b10[1];if(b10[2]){var d10=b10[2];return a10[1]=a10[1]-1|0,a10[2]=d10,c10}return ei(a10),c10}function ek(a10){return a10[1]===0?1:0}function mJ(a10){var b10=a10[2];return b10?[0,b10[1]]:0}function mK(a10){var b10=a10[2];if(!b10)return 0;var c10=b10[1];if(b10[2]){var d10=b10[2];return a10[1]=a10[1]-1|0,a10[2]=d10,[0,c10]}return ei(a10),[0,c10]}function b8(a10){var b10=1<=a10?a10:1,c10=b6=(d10+b10|0));)c10[1]=2*c10[1]|0;b6a10[3])throw g([0,f,mP],1);if(!((d10+b10|0)<=a10[3]))throw g([0,f,mO],1)}function b9(a10,b10){var c10=n(b10),d10=a10[2]+c10|0;a10[3]=b10?eb(a10[1],b10,c10):t(mM)}function mN(a10){return a10[2]}function mR(a10,b10){var c10=a10[2];a10[3]<=c10&&el(a10,1),B(a10[1],c10,b10),a10[2]=c10+1|0}function mS(a10,b10,c10,d10){var e10=c10<0?1:0;if(e10)var f10=e10;else var h10=d10<0?1:0,f10=h10||((n(b10)-d10|0)e10){if(e10!==32){if(43>e10)break a;switch(e10-43|0){case 5:c:if(c10<(d10+2|0)&&1=(d10+1|0))break a;var f10=bh(d10+1|0,48);return a0(f10,0,e10),aL(b10,1,f10,(d10-c10|0)+2|0,c10-1|0),$(f10)}if(71<=e10){if(5>>0)break a}else if(65>e10)break a}if(c10a10)return b10;var h10=[0,0],i10=n(b10)-1|0,o10=0;if(i10>=0)for(var d10=o10;;){9>=_(b10,d10)+kg>>>0&&h10[1]++;var r10=d10+1|0;if(i10===d10)break;d10=r10}var j10=h10[1],k10=F(n(b10)+((j10-1|0)/3|0)|0),l10=[0,0];function e10(a11){a0(k10,l10[1],a11),l10[1]++}var f10=[0,((j10-1|0)%3|0)+1|0],m10=n(b10)-1|0,p10=0;if(m10>=0)for(var c10=p10;;){var g10=_(b10,c10);9>>0||(f10[1]===0&&(e10(95),f10[1]=3),f10[1]--),e10(g10);var q10=c10+1|0;if(m10===c10)break;c10=q10}return $(k10)}function oy(a10,b10){return cS(a10,dT(nF(a10),b10))}function oz(a10,b10){return cS(a10,dT(n7(a10),b10))}function oA(a10,b10){return cS(a10,dT(oj(a10),b10))}function oB(a10,b10){return cS(a10,zS(nT(a10),b10))}function aM(d10,b10,c10){function a10(a11){switch(d10[1]){case 0:var e11=45;break;case 1:var e11=43;break;default:var e11=32}return zN(c10,b10,e11)}function e10(a11){var b11=zy(c10);return b11===3?c10<0?oD:oE:4<=b11?oF:a11}function f10(b11){var e11=n(b11);return function(a11){for(var c11=a11;;){if(c11===e11)return 0;var d11=y(b11,c11)-46|0;a:{if(23>>0){if(d11===55)break a}else if(21>>0)break a;c11=c11+1|0;continue}return 1}}(0)?b11:ay(b11,oC)}switch(d10[2]){case 5:return e10(f10(ga(gU(d10,b10),c10)));case 6:return a10(0);case 7:return mj(a10(0));case 8:return e10(a10(0));default:return ga(gU(d10,b10),c10)}}function oG(a10){var b10=lL(a10),c10=n(b10),d10=bh(c10+2|0,39);return cy(b10,0,d10,1,c10),$(d10)}function oH(a10){var b10=gQ(16);return en(b10,a10),gS(b10)}function co(a10,b10,c10,d10){for(var k10=b10,j10=c10,e10=d10;;){if(typeof e10=="number")return h(k10,j10);switch(e10[0]){case 0:var t10=e10[1];return function(a11){return o(k10,[5,j10,a11],t10)};case 1:var u10=e10[1];return function(a11){return o(k10,[4,j10,oG(a11)],u10)};case 2:return eo(k10,j10,e10[2],e10[1],function(a11){return a11});case 3:return eo(k10,j10,e10[2],e10[1],nE);case 4:return cT(k10,j10,e10[4],e10[2],e10[3],oy,e10[1]);case 5:return cT(k10,j10,e10[4],e10[2],e10[3],oz,e10[1]);case 6:return cT(k10,j10,e10[4],e10[2],e10[3],oA,e10[1]);case 7:return cT(k10,j10,e10[4],e10[2],e10[3],oB,e10[1]);case 8:return oI(k10,j10,e10[4],e10[2],e10[3],e10[1]);case 9:return eo(k10,j10,e10[2],e10[1],lt);case 10:j10=[7,j10],e10=e10[1];break;case 11:j10=[2,j10,e10[1]],e10=e10[2];break;case 12:j10=[3,j10,e10[1]],e10=e10[2];break;case 13:var v10=e10[3],x10=oH(e10[2]);return function(a11){return o(k10,[4,j10,x10],v10)};case 14:var y10=e10[3],z10=e10[2];return function(a11){return o(k10,j10,w(nD(a11[1],z10),y10))};case 15:var A2=e10[1];return function(c11,b11){return o(k10,[6,j10,function(a11){return i(c11,a11,b11)}],A2)};case 16:var B2=e10[1];return function(a11){return o(k10,[6,j10,a11],B2)};case 17:j10=[0,j10,e10[1]],e10=e10[2];break;case 18:var l10=e10[1];if(l10[0]===0){let b11=j10,c11=k10,d11=e10[2];k10=function(a11){return o(c11,[1,b11,[0,a11]],d11)},j10=0,e10=l10[1][1]}else{let b11=j10,c11=k10,d11=e10[2];k10=function(a11){return o(c11,[1,b11,[1,a11]],d11)},j10=0,e10=l10[1][1]}break;case 19:throw g([0,f,oK],1);case 20:var C2=e10[3],D2=[8,j10,oL];return function(a11){return o(k10,D2,C2)};case 21:var E2=e10[2];return function(a11){return o(k10,[4,j10,dT(ka,a11)],E2)};case 22:var F2=e10[1];return function(a11){return o(k10,[5,j10,a11],F2)};case 23:var m10=e10[2],n10=e10[1];return a10<50?jc(a10+1|0,k10,j10,n10,m10):r(jc,[0,k10,j10,n10,m10]);default:var p10=e10[3],q10=e10[1],s10=h(e10[2],0);return a10<50?ft(a10+1|0,k10,j10,p10,q10,s10):r(ft,[0,k10,j10,p10,q10,s10])}}}function o(a10,b10,c10){return bA(co(0,a10,b10,c10))}function jc(a10,b10,c10,d10,e10){if(typeof d10=="number")switch(d10){case 0:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 1:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 2:throw g([0,f,oM],1);default:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10])}switch(d10[0]){case 0:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 1:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 2:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 3:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 4:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 5:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 6:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 7:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 8:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);case 9:var h10=d10[2];return a10<50?fu(a10+1|0,b10,c10,h10,e10):r(fu,[0,b10,c10,h10,e10]);case 10:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10]);default:return a10<50?s(a10+1|0,b10,c10,e10):r(s,[0,b10,c10,e10])}}function fu(a10,h10,c10,d10,e10){if(typeof d10=="number")return a10<50?s(a10+1|0,h10,c10,e10):r(s,[0,h10,c10,e10]);switch(d10[0]){case 0:var b10=d10[1];return function(a11){return af(h10,c10,b10,e10)};case 1:var i10=d10[1];return function(a11){return af(h10,c10,i10,e10)};case 2:var j10=d10[1];return function(a11){return af(h10,c10,j10,e10)};case 3:var k10=d10[1];return function(a11){return af(h10,c10,k10,e10)};case 4:var l10=d10[1];return function(a11){return af(h10,c10,l10,e10)};case 5:var m10=d10[1];return function(a11){return af(h10,c10,m10,e10)};case 6:var n10=d10[1];return function(a11){return af(h10,c10,n10,e10)};case 7:var o10=d10[1];return function(a11){return af(h10,c10,o10,e10)};case 8:var p10=d10[2];return function(a11){return af(h10,c10,p10,e10)};case 9:var q10=d10[3],t10=d10[2],u10=I(D(d10[1]),t10);return function(a11){return af(h10,c10,W(u10,q10),e10)};case 10:var v10=d10[1];return function(a11,b11){return af(h10,c10,v10,e10)};case 11:var w10=d10[1];return function(a11){return af(h10,c10,w10,e10)};case 12:var x10=d10[1];return function(a11){return af(h10,c10,x10,e10)};case 13:throw g([0,f,oN],1);default:throw g([0,f,oO],1)}}function af(a10,b10,c10,d10){return bA(fu(0,a10,b10,c10,d10))}function s(a10,b10,c10,d10){var e10=[8,c10,oP];return a10<50?co(a10+1|0,b10,e10,d10):r(co,[0,b10,e10,d10])}function eo(g10,f10,c10,d10,e10){if(typeof d10=="number")return function(a10){return o(g10,[4,f10,h(e10,a10)],c10)};if(d10[0]===0){var b10=d10[2],i10=d10[1];return function(a10){return o(g10,[4,f10,ab(i10,b10,h(e10,a10))],c10)}}var j10=d10[1];return function(a10,b11){return o(g10,[4,f10,ab(j10,a10,h(e10,b11))],c10)}}function cT(k10,j10,h10,d10,e10,f10,g10){if(typeof d10=="number"){if(typeof e10=="number")return e10?function(a10,b11){return o(k10,[4,j10,bG(a10,i(f10,g10,b11))],h10)}:function(a10){return o(k10,[4,j10,i(f10,g10,a10)],h10)};var b10=e10[1];return function(a10){return o(k10,[4,j10,bG(b10,i(f10,g10,a10))],h10)}}if(d10[0]===0){var c10=d10[2],l10=d10[1];if(typeof e10=="number")return e10?function(a10,b11){return o(k10,[4,j10,ab(l10,c10,bG(a10,i(f10,g10,b11)))],h10)}:function(a10){return o(k10,[4,j10,ab(l10,c10,i(f10,g10,a10))],h10)};var n10=e10[1];return function(a10){return o(k10,[4,j10,ab(l10,c10,bG(n10,i(f10,g10,a10)))],h10)}}var m10=d10[1];if(typeof e10=="number")return e10?function(a10,b11,c11){return o(k10,[4,j10,ab(m10,a10,bG(b11,i(f10,g10,c11)))],h10)}:function(a10,b11){return o(k10,[4,j10,ab(m10,a10,i(f10,g10,b11))],h10)};var p10=e10[1];return function(a10,b11){return o(k10,[4,j10,ab(m10,a10,bG(p10,i(f10,g10,b11)))],h10)}}function oI(i10,h10,g10,d10,e10,f10){if(typeof d10=="number"){if(typeof e10=="number")return e10?function(a10,b11){return o(i10,[4,h10,aM(f10,a10,b11)],g10)}:function(a10){return o(i10,[4,h10,aM(f10,em(f10),a10)],g10)};var b10=e10[1];return function(a10){return o(i10,[4,h10,aM(f10,b10,a10)],g10)}}if(d10[0]===0){var c10=d10[2],j10=d10[1];if(typeof e10=="number")return e10?function(a10,b11){return o(i10,[4,h10,ab(j10,c10,aM(f10,a10,b11))],g10)}:function(a10){return o(i10,[4,h10,ab(j10,c10,aM(f10,em(f10),a10))],g10)};var l10=e10[1];return function(a10){return o(i10,[4,h10,ab(j10,c10,aM(f10,l10,a10))],g10)}}var k10=d10[1];if(typeof e10=="number")return e10?function(a10,b11,c11){return o(i10,[4,h10,ab(k10,a10,aM(f10,b11,c11))],g10)}:function(a10,b11){return o(i10,[4,h10,ab(k10,a10,aM(f10,em(f10),b11))],g10)};var m10=e10[1];return function(a10,b11){return o(i10,[4,h10,ab(k10,a10,aM(f10,m10,b11))],g10)}}function ft(a10,b10,c10,d10,e10,f10){if(e10){var i10=e10[1];return function(a11){return oJ(b10,c10,d10,i10,h(f10,a11))}}var g10=[4,c10,f10];return a10<50?co(a10+1|0,b10,g10,d10):r(co,[0,b10,g10,d10])}function oJ(a10,b10,c10,d10,e10){return bA(ft(0,a10,b10,c10,d10,e10))}function aN(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;switch(c10[0]){case 0:var f10=c10[1],g10=gT(c10[2]);return aN(a10,f10),b5(a10,g10);case 1:var d10=c10[2],e10=c10[1];if(d10[0]===0){var i10=d10[1];aN(a10,e10),b5(a10,oQ),c10=i10}else{var j10=d10[1];aN(a10,e10),b5(a10,oR),c10=j10}break;case 6:var m10=c10[2];return aN(a10,c10[1]),h(m10,a10);case 7:return aN(a10,c10[1]),cJ(a10);case 8:var n10=c10[2];return aN(a10,c10[1]),t(n10);case 2:case 4:var k10=c10[2];return aN(a10,c10[1]),b5(a10,k10);default:var l10=c10[2];return aN(a10,c10[1]),lD(a10,l10)}}}function aO(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;switch(c10[0]){case 0:var f10=c10[1],g10=gT(c10[2]);return aO(a10,f10),b9(a10,g10);case 1:var d10=c10[2],e10=c10[1];if(d10[0]===0){var i10=d10[1];aO(a10,e10),b9(a10,oS),c10=i10}else{var j10=d10[1];aO(a10,e10),b9(a10,oT),c10=j10}break;case 6:var m10=c10[2];return aO(a10,c10[1]),b9(a10,h(m10,0));case 7:c10=c10[1];break;case 8:var n10=c10[2];return aO(a10,c10[1]),t(n10);case 2:case 4:var k10=c10[2];return aO(a10,c10[1]),b9(a10,k10);default:var l10=c10[2];return aO(a10,c10[1]),mR(a10,l10)}}}function oU(a10){var c10=a10[1],b10=b8(cv);return o(function(a11){return aO(b10,a11),aK(cQ(b10))},0,c10)}function oV(c10){if(c10==e)return oW;var f10=n(c10);function j10(a11){return h(oU(oX),c10)}function k10(a11){for(var b11=a11;;){if(b11===f10)return b11;var d11=y(c10,b11);if(d11!==9&&d11!==32)return b11;b11=b11+1|0}}var i10=k10(0),o10=function(a11,b11){for(var d11=b11;;){if(d11===f10||25>>0)return d11;d11=d11+1|0}}(i10,i10),a10=ec(c10,i10,o10-i10|0),d10=k10(o10),l10=function(a11,b11){for(var d11=b11;;){if(d11===f10)return d11;var e10=y(c10,d11);a:{if(48<=e10){if(58>e10)break a}else if(e10===45)break a;return d11}d11=d11+1|0}}(d10,d10);if(d10===l10)var m10=0;else try{var r10=k$(ec(c10,d10,l10-d10|0)),m10=r10}catch(f11){var p10=L(f11);if(p10[1]!==b3)throw g(p10,0);var q10=j10(0),m10=q10}k10(l10)!==f10&&j10(0);a:{if(a10!==e&&a10!==jt){if(a10==="h"){var b10=0;break a}if(a10==="hov"){var b10=3;break a}if(a10==="hv"){var b10=2;break a}if(a10!=="v"){var b10=j10(0);break a}var b10=1;break a}var b10=4}return[0,m10,b10]}function oY(d10,b10,c10){return o(function(a10){return aN(b10,a10),h(d10,b10)},0,c10[1])}function cU(a10,b10){return oY(function(a11){return 0},a10,b10)}function ep(a10){return cU(at,a10)}function eq2(c10,b10){return o(function(a10){var b11=b8(64);return aO(b11,a10),h(c10,cQ(b11))},0,b10[1])}function C(a10){return eq2(function(a11){return a11},a10)}var er=d4(0);function et(a10,b10){var c10=a10[1+b10];return lE(c10)?aw(c10)===dC?h(C(oZ),c10):aw(c10)===ko?ly(c10):o0:h(C(o1),c10)}function gV(a10,b10){if(a10.length-1<=b10)return o2;var c10=gV(a10,b10+1|0),d10=et(a10,b10);return i(C(o3),d10,c10)}function o4(a10){var b10=a10.length-1;if(2>=b10>>>0)switch(b10){case 0:return o6;case 1:return o7;default:var e10=et(a10,1);return h(C(o8),e10)}var c10=gV(a10,2),d10=et(a10,1);return i(C(o5),d10,c10)}function o9(d10){return function(a10){for(var b10=a10;;){if(!b10)return 0;var e10=b10[2],f10=b10[1];a:{try{var c10=h(f10,d10)}catch{break a}if(c10)return[0,c10[1]]}b10=e10}}(cG(er))}function o_(a10){if(a10===d6)return o$;if(a10===gt)return pa;if(a10[1]===gs){var b10=a10[2],e10=b10[3],i10=b10[2],j10=b10[1];return fx(C(es),j10,i10,e10,e10+5|0,pb)}if(a10[1]===f){var c10=a10[2],g10=c10[3],k10=c10[2],l10=c10[1];return fx(C(es),l10,k10,g10,g10+6|0,pc)}if(a10[1]===b4){var d10=a10[2],h10=d10[3],m10=d10[2],n10=d10[1];return fx(C(es),n10,m10,h10,h10+6|0,pd)}if(aw(a10)!==0)return a10[1];var o10=a10[1][1];return ay(o10,o4(a10))}function cV(a10){var b10=o9(a10);return b10?b10[1]:o_(a10)}function pe(a10){var b10=[0,zz(a10)];return b10}function pf(c10,b10){function a10(a11){return a11?c10===0?pg:ph:c10===0?pi:pj}if(b10[0]===0){var d10=b10[5],e10=b10[4],f10=b10[3],g10=b10[6]?pk:pm,i10=b10[2],j10=b10[7],k10=a10(b10[1]);return[0,zm(C(pl),k10,j10,i10,g10,f10,e10,d10)]}if(b10[1])return 0;var l10=a10(0);return[0,h(C(pn),l10)]}function po(a10,b10){if(!b10)return cU(a10,pq);var d10=b10[1],e10=d10.length-2|0,g10=0;if(e10>=0)for(var c10=g10;;){var f10=pf(c10,j(d10,c10)[1+c10]);if(f10){var i10=f10[1];h(cU(a10,pp),i10)}var k10=c10+1|0;if(e10===c10)break;c10=k10}return 0}function cW(a10,b10){return po(a10,pe(b10))}var pt=ps.slice();function pu(a10,b10){var e10=cV(a10);h(ep(pv),e10),cW(at,b10);var c10=z_(0);if(c10<0){var d10=cI(c10);gx(j(pt,d10)[1+d10])}return cJ(at)}var pw=[0];function gW(a10){var b10=k5(0);return b10}function px(a10,b10){try{var d10=b10?pw:gW(0);try{d8(0)}catch{}try{var f10=pu(a10,d10),e10=f10}catch(f11){var i10=L(f11),j10=gW(0),k10=cV(a10);h(ep(pz),k10),cW(at,d10);var l10=cV(i10);h(ep(pA),l10),cW(at,j10);var e10=cJ(at)}return e10}catch(f11){var c10=L(f11);if(c10===d6)return gx(py);throw g(c10,0)}}go(ky,function(a10,b10){try{var c10=px(a10,b10);return c10}catch{return 0}});function pr(a10){for(;;){var b10=cG(er),c10=1-d5(er,b10,[0,a10,b10]);if(!c10)return c10}}function pB(a10){return k5(a10)}var pD=[q,pC,ae(0)];pr(function(a10){return a10[1]===pD?[0,ay(pE,cV(a10[2]))]:0});function pF(a10){return z8(a10,0,n(a10))}function pG(a10){return[0,ap(55,0),0]}function pH(a10,b10){function l10(a11,b11){return pF(ay(a11,gE(b11)))}function m10(a11){var b11=y(a11,3)<<24,c11=y(a11,2)<<16,d11=y(a11,1)<<8;return((y(a11,0)+d11|0)+c11|0)+b11|0}for(var g10=b10.length-1===0?[0,0]:b10,h10=g10.length-1,c10=0;;){j(a10[1],c10)[1+c10]=c10;var s10=c10+1|0;if(c10===54)break;c10=s10}var f10=[0,pI],i10=54+gD(55,h10)|0,n10=0;if(i10>=0)for(var d10=n10;;){var e10=d10%55|0,k10=Ad(d10,h10),o10=j(g10,k10)[1+k10];f10[1]=l10(f10[1],o10);var p10=m10(f10[1]),q10=(j(a10[1],e10)[1+e10]^p10)&jY;j(a10[1],e10)[1+e10]=q10;var r10=d10+1|0;if(i10===d10)break;d10=r10}a10[2]=0}function pJ(a10){var b10=pG(0);return pH(b10,a10),b10}function gX(a10){return pJ(Aq(0))}function cX(a10){a10[2]=(a10[2]+1|0)%55|0;var b10=a10[2],c10=j(a10[1],b10)[1+b10],d10=(a10[2]+24|0)%55|0,e10=(j(a10[1],d10)[1+d10]+(c10^(c10>>>25|0)&31)|0)&jY,f10=a10[2];return j(a10[1],f10)[1+f10]=e10,e10}function gY(a10){var b10=gi(dW(cX(a10)),9),c10=gi(dW(cX(a10)),9);return k8(b10,k8(k9(c10,21),k9(gi(dW(cX(a10)),8),42)))}function pK(a10){var b10=a10.length-1<4?1:0,c10=b10||(a10[4]<0?1:0);return c10}try{var zk=ll(kp),g2=zk}catch(f10){var gZ=L(f10);if(gZ!==ax)throw g(gZ,0);try{var zj=ll("CAMLRUNPARAM"),g1=zj}catch(f11){var g0=L(f11);if(g0!==ax)throw g(g0,0);var g1=pL}var g2=g1}var cY=[ba,function(a10){return gX(0)}],pM=mi(g2,82);function pN(a10,b10){for(var c10=a10;;){if(b10<=c10||d9<(c10*2|0))return c10;c10=c10*2|0}}function eu(a10,b10){var f10=a10?a10[1]:pM,c10=pN(16,b10);if(f10)var d10=aw(cY),g10=aD===d10?cY[1]:ba===d10?cK(cY):cY,e10=cX(g10);else var e10=0;return[0,0,ap(c10,0),e10,c10]}function pO(m10,b10,c10,d10){var g10=d10.length-1,f10=ap(g10,0),i10=c10.length-2|0;function n10(a11){for(var c11=a11;;){if(!c11)return;var i11=c11[1],l11=c11[2],n11=c11[3],g11=b10?c11:[0,i11,l11,0],e11=h(m10,i11),k11=j(f10,e11)[1+e11];k11?k11[3]=g11:j(d10,e11)[1+e11]=g11,j(f10,e11)[1+e11]=g11,c11=n11}}var o10=0;if(i10>=0)for(var e10=o10;;){n10(j(c10,e10)[1+e10]);var r10=e10+1|0;if(i10===e10)break;e10=r10}if(b10){var k10=g10-1|0,p10=0;if(k10>=0)for(var a10=p10;;){var l10=j(f10,a10)[1+a10];l10&&(l10[3]=0);var q10=a10+1|0;if(k10===a10)break;a10=q10}}}function g3(a10,b10){var c10=b10[2],d10=(c10.length-1)*2|0,e10=d10>>0))return g_(a10,d10)}function p0(a10){var b10=mK(a10[28]);if(b10){var c10=b10[1],d10=c10[1];a10[12]=a10[12]-c10[3]|0;var e10=d10;a10[9]=a10[9]+e10|0}}function p1(a10,b10,c10){if(typeof c10=="number")switch(c10){case 0:var j10=bE(a10[3]);if(!j10)return;var k10=j10[1][1],l10=function(a11,b11){if(!b11)return[0,a11,0];var c11=b11[1],d11=b11[2];return z4(a11,c11)?[0,a11,b11]:[0,c11,l10(a11,d11)]};k10[1]=l10(a10[6]-a10[9]|0,k10[1]);return;case 1:bD(a10[2]);return;case 2:bD(a10[3]);return;case 3:var m10=bE(a10[2]);return m10?g_(a10,m10[1][2]):c0(a10);case 4:var o10=a10[10]!==(a10[6]-a10[9]|0)?1:0;return o10&&p0(a10);default:var p10=bD(a10[5]);return p10?ev(a10,h(a10[25],p10[1])):void 0}switch(c10[0]){case 0:return g9(a10,b10,c10[1]);case 1:var d10=c10[2],f10=c10[1],q10=d10[1],z10=d10[2],r10=bE(a10[2]);if(!r10)return;var s10=r10[1],e10=s10[2];switch(s10[1]){case 0:return bI(a10,f10);case 1:return bi(a10,d10,e10);case 2:return bi(a10,d10,e10);case 3:return a10[9]<(b10+n(q10)|0)?bi(a10,d10,e10):bI(a10,f10);case 4:return a10[11]?bI(a10,f10):a10[9]<(b10+n(q10)|0)||((a10[6]-e10|0)+z10|0)=a10[14])return a10[13]=g8,g$(a10),b10&&c0(a10),qc(a10);he(a10,0)}}function ey(a10,b10,c10){var d10=a10[14]=c10)return x(a10[17],hi,0,c10);x(a10[17],hi,0,80),c10=c10-80|0}}function qp(a10){return a10[1]===b$?ay(qr,ay(a10[2],qq)):qs}function qt(a10){return a10[1]===b$?ay(qv,ay(a10[2],qu)):qw}function qx(a10){return 0}function qy(a10){return 0}function qz(a10,b10,c10,d10,e10){var g10=eh(0),h10=[0,g6,qA,0];ej(h10,g10);var f10=bC(0);ew(f10),a5([0,1,h10],f10);var i10=78,j10=bC(0),k10=bC(0),l10=bC(0);return[0,f10,bC(0),l10,k10,j10,i10,10,68,i10,0,1,1,1,1,gv,qB,a10,b10,c10,d10,e10,0,0,qp,qt,qx,qy,g10]}function hk(a10,b10){var c10=qz(a10,b10,function(a11){return 0},function(a11){return 0},function(a11){return 0});return c10[19]=function(a11){return qn(c10,a11)},c10[20]=function(a11){return hj(c10,a11)},c10[21]=function(a11){return hj(c10,a11)},c10}function hl(d10){return hk(function(a10,b10,c10){return lA(d10,a10,b10,c10)},function(a10){return cJ(d10)})}function ez(d10){return hk(function(a10,b10,c10){return mS(d10,a10,b10,c10)},function(a10){return 0})}var qC=dF,qD=function(a10){return b8(qC)}(0),qE=hl(lz),qF=hl(at);ez(qD);function p9(a10,b10){a10[22]&&(a5(b10,a10[4]),h(a10[26],b10));var c10=a10[23];return c10&&ca(a10,[0,cZ,[5,b10],0])}function qe(a10,b10){return hh(a10,n(b10),b10)}function qf(a10,b10){return hg(a10,1),h(a10[18],0)}function qg(a10,b10){var c10=a10[14]=0)for(var c10=g10;;){qK(e10,c10,a10,j(b10,c10)[1+c10]);var h10=c10+1|0;if(f10===c10)break;c10=h10}return e10}function ho(a10,b10){return typeof b10!="number"&&b10[0]===0?hn(a10,b10[1]):aK(qL)}function qM(a10,b10,c10,d10){if(typeof c10!="number")return c10[0]===0?hp(c10[1],a10[1+b10],d10):void 0;if(c10!==2){a10[1+b10]=d10;return}if(aw(d10)===0&&d10.length-1===4)for(var e10=0,h10=a10[1+b10];;){h10[1+e10]=d10[1+e10];var i10=e10+1|0;if(e10===3)return;e10=i10}throw g([0,f,qN],1)}function hp(a10,b10,c10){if(aw(c10)===0&&a10.length-1<=c10.length-1){var e10=a10.length-2|0,h10=0;if(e10>=0)for(var d10=h10;;){var i10=c10[1+d10];qM(b10,d10,j(a10,d10)[1+d10],i10);var k10=d10+1|0;if(e10===d10)break;d10=k10}return}throw g([0,f,qO],1)}function hq(a10,b10,c10){return typeof a10!="number"&&a10[0]===0?hp(a10[1],b10,c10):aK(qP)}var eA=[q,qQ,ae(0)];qI(qR,[0,eA,[0]]);function eB(a10){return[0,a10]}function Q(a10){return[0,a10]}function c2(a10){return a10[0]===0?[0,a10[1]]:0}var bK=[0,function(a10){return a10}(0)];function bL(a10){return[1,0,0,0,a10]}function l(a10,b10){return a10[0]===0?[0,h(b10,a10[1])]:bL([0,a10,b10])}function cc(a10,b10,c10){if(a10[0]===0){var d10=a10[1];if(b10[0]===0)return[0,i(c10,d10,b10[1])]}return bL([1,a10,b10,c10])}function hr(a10){return a10[0]===0?a10[1]:bL([4,a10,0])}function hs(a10,b10,c10){switch(c10[0]){case 0:throw g([0,f,qU],1);case 1:c10[3]=[0,b10,a10,c10[3]];return;default:c10[2]=[0,b10,a10,c10[2]];return}}function eC(a10,b10){if(!b10)throw g([0,f,qV],1);if(b10[2]===a10)return[0,b10[1],b10[3]];var c10=eC(a10,b10[3]),d10=c10[1];return b10[3]=c10[2],[0,d10,b10]}function cd(a10,b10){switch(b10[0]){case 0:throw g([0,f,qW],1);case 1:var c10=eC(a10,b10[3]),e10=c10[1];return b10[3]=c10[2],e10;default:var d10=eC(a10,b10[2]),h10=d10[1];return b10[2]=d10[2],h10}}function ht(a10,b10,c10,d10){for(var e10=d10;;){if(!e10)throw g([0,f,qX],1);if(e10[1]===b10&&e10[2]===a10){e10[1]=c10;return}e10=e10[3]}}function eD(a10,b10,c10,d10){switch(d10[0]){case 0:throw g([0,f,qY],1);case 1:return ht(a10,b10,c10,d10[3]);default:return ht(a10,b10,c10,d10[2])}}function hu(a10,b10){for(var c10=b10;;){if(!c10)throw g([0,f,qZ],1);if(c10[2]===a10)return c10[1];c10=c10[3]}}function q0(a10,b10){switch(b10[0]){case 0:throw g([0,f,q1],1);case 1:return hu(a10,b10[3]);default:return hu(a10,b10[2])}}function aU(a10,b10,c10,d10){switch(d10[0]){case 0:throw g([0,f,q2],1);case 1:var j10=d10[1];if(typeof j10=="number"&&!j10){if(!c10||b10[1])return;b10[1]=1;return}var k10=d10[4];if(k10[0]===7){var n10=k10[2];if(n10[0]===1){var o10=n10[1];if(typeof o10=="number"){if(!o10&&c10){if(b10[1])return;b10[1]=1;return}}else if(c10)return}}var l10=d10[1];a:{if(typeof l10=="number"&&l10){var e10=1;break a}var e10=c10}d10[1]=0;var m10=d10[2];return a10<50?jd(a10+1|0,b10,e10,m10):r(jd,[0,b10,e10,m10]);default:var i10=d10[1];if(d10[1]=0,typeof i10=="number"){if(!i10)return;b10[1]=2;return}var p10=i10[1];return c10&&(b10[1]=2),h(d10[3],p10)}}function a6(a10,b10,c10){return bA(aU(0,a10,b10,c10))}function jd(a10,b10,c10,d10){if(typeof d10!="number")switch(d10[0]){case 0:var f10=d10[1];return a10<50?aU(a10+1|0,b10,c10,f10):r(aU,[0,b10,c10,f10]);case 1:var g10=d10[2];return a6(b10,c10,d10[1]),a10<50?aU(a10+1|0,b10,c10,g10):r(aU,[0,b10,c10,g10]);case 2:var h10=d10[3],l10=d10[2];return a6(b10,c10,d10[1]),a6(b10,c10,l10),a10<50?aU(a10+1|0,b10,c10,h10):r(aU,[0,b10,c10,h10]);case 3:var i10=d10[4],m10=d10[3],n10=d10[2];return a6(b10,c10,d10[1]),a6(b10,c10,n10),a6(b10,c10,m10),a10<50?aU(a10+1|0,b10,c10,i10):r(aU,[0,b10,c10,i10]);default:var o10=d10[1];d10[1]=0;var k10=o10-1|0,p10=0;if(k10>=0)for(var e10=p10;;){a6(b10,c10,j(d10[3],e10)[1+e10]);var q10=e10+1|0;if(k10===e10)break;e10=q10}return}}function q3(a10){return i(cU(at,q4),cW,zG(20))}function c3(a10,b10){var c10=[0,0];a6(c10,a10,b10);var d10=2<=c10[1]?1:0;return d10&&q3(0)}function am(a10){return bL([5,a10])}function aP(a10){return a10}function ac(a10,b10){if(a10[0]===1){var c10=a10[4];if(c10[0]===5)return c10[1]=b10,c3(0,a10)}throw g([0,f,q5],1)}function bM(a10){if(a10[0]===1){var b10=a10[4];if(b10[0]===5)return b10[1]}throw g([0,f,q6],1)}function bN(a10,b10,c10){for(var k10=a10,h10=b10,d10=c10;;)switch(d10[0]){case 0:return k10;case 1:var e10=d10[2];if(typeof e10=="number")throw g([0,f,q$],1);switch(e10[0]){case 0:if(e10[1]!==h10)throw g([0,f,ra],1);var o10=0;break;case 1:var B2=e10[2],C2=e10[1];if(C2===h10)var D2=[0,B2];else{if(B2!==h10)throw g([0,f,rb],1);var D2=[0,C2]}var o10=D2;break;case 2:var u10=e10[3],v10=e10[2],w10=e10[1];if(w10===h10)var x10=[1,v10,u10];else if(v10===h10)var x10=[1,w10,u10];else{if(u10!==h10)throw g([0,f,rc],1);var x10=[1,w10,v10]}var o10=x10;break;case 3:var p10=e10[4],q10=e10[3],r10=e10[2],s10=e10[1];if(s10===h10)var t10=[2,r10,q10,p10];else if(r10===h10)var t10=[2,s10,q10,p10];else if(q10===h10)var t10=[2,s10,r10,p10];else{if(p10!==h10)throw g([0,f,rd],1);var t10=[2,s10,r10,q10]}var o10=t10;break;default:var n10=cd(d10,h10);if(j(e10[3],n10)[1+n10]!==h10)throw g([0,f,re],1);var m10=e10[2]-1|0;if(e10[2]=m10,n10>>2|0))var U2=mm(e10[3],0,K2>>>1|0),M2=[4,e10[1],e10[2],U2];else var M2=e10;var J2=M2}var o10=J2}if(d10[2]=o10,typeof o10!="number")return k10;var y10=d10[1];d10[1]=1;var l10=d10[4];switch(l10[0]){case 0:h10=d10,d10=l10[1];break;case 1:var N2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=N2;break;case 2:var O2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=O2;break;case 3:var P2=l10[2];k10=bN(k10,d10,l10[1]),h10=d10,d10=P2;break;case 4:var z10=l10[2],A2=bN(k10,d10,l10[1]);if(!z10)return A2;var Q2=z10[1];l10[2]=0,k10=A2,h10=d10,d10=Q2;break;case 5:return k10;case 6:if(typeof y10=="number")return k10;var R2=y10[1];try{return i(l10[2],d10,R2),k10}catch(f10){var S2=L(f10);return[0,[0,S2,pB(0)],k10]}default:var T2=l10[1];k10=bN(k10,d10,l10[2]),h10=d10,d10=T2}break;default:throw g([0,f,rf],1)}}function a7(a10,b10){for(var e10=a10,c10=b10;;)switch(c10[0]){case 0:return;case 1:var n10=typeof c10[2]=="number"?1:0,d10=c10[2];if(typeof d10=="number")var k10=[0,e10];else switch(d10[0]){case 0:var k10=[1,e10,d10[1]];break;case 1:var k10=[2,e10,d10[1],d10[2]];break;case 2:var k10=[3,e10,d10[1],d10[2],d10[3]];break;case 3:for(var o10=[0,d10[1],d10[2],d10[3],d10[4],e10,bK,bK,bK],l10=0;;){hs(c10,l10,j(o10,l10)[1+l10]);var w10=l10+1|0;if(l10===4)break;l10=w10}var k10=[4,5,5,o10];break;default:var i10=d10[2];if(i10>>1|0)}function hC(a10,b10,c10){if(typeof a10!="number"){if(a10[0]!==0){if(a10[2]!==b10)throw g([0,f,rO],1);a10[2]=c10;return}if(a10[2]===b10){a10[2]=c10;return}if(a10[4]===b10){a10[4]=c10;return}}throw g([0,f,rN],1)}function fw(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[4];if(typeof d10!="number"&&d10[0]!==1){var h10=c10[5],e10=d10[2];if(typeof e10=="number")var i10=0;else{if(e10[0]!==0)throw g([0,f,rS],1);e10[5]=c10;var i10=e10}return d10[2]=c10,c10[4]=i10,c10[5]=d10,d10[5]=h10,hC(h10,c10,d10),eK(b10,c10),a10<50?cp(a10+1|0,b10,d10):r(cp,[0,b10,d10])}}throw g([0,f,rR],1)}function rP(a10,b10){return bA(fw(0,a10,b10))}function fv(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[2];if(typeof d10!="number"&&d10[0]!==1){var h10=c10[5],e10=d10[4];if(typeof e10=="number")var i10=0;else{if(e10[0]!==0)throw g([0,f,rU],1);e10[5]=c10;var i10=e10}return d10[4]=c10,c10[2]=i10,c10[5]=d10,d10[5]=h10,hC(h10,c10,d10),eK(b10,c10),a10<50?cp(a10+1|0,b10,d10):r(cp,[0,b10,d10])}}throw g([0,f,rT],1)}function rQ(a10,b10){return bA(fv(0,a10,b10))}function jf(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[4];a:if(typeof d10!="number"&&d10[0]===0){var e10=bP(d10[2]);if(eJ(bP(d10[4]),e10)){rQ(b10,d10);break a}}return a10<50?fw(a10+1|0,b10,c10):r(fw,[0,b10,c10])}throw g([0,f,rV],1)}function je(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=c10[2];a:if(typeof d10!="number"&&d10[0]===0){var e10=bP(d10[4]);if(eJ(bP(d10[2]),e10)){rP(b10,d10);break a}}return a10<50?fv(a10+1|0,b10,c10):r(fv,[0,b10,c10])}throw g([0,f,rW],1)}function cp(a10,b10,c10){if(typeof c10!="number"&&c10[0]===0){var d10=bP(c10[2]),e10=bP(c10[4]);return d10>>2|0)}function az(a10,b10){if(typeof a10=="number")var c10=b10;else{if(typeof b10!="number"){var d10=c8(b10);return[1,(hH(c8(a10),d10)+1|0)<<2,a10,b10]}var c10=a10}return c10}function hI(a10){return typeof a10=="number"?0:a10[0]===0?[0,a10[2]]:[1,a10[2],a10[3]]}var eL=1,eM=2,sr=3;function hJ(a10){return a10===-1?1:0}function eN(a10){return a10!==-1?1:0}function bQ(a10){return(a10&3)===3?1:0}function hK(a10){return(a10&3)===1?1:0}function hL(a10){return(a10&3)===2?1:0}function hM(a10){return a10|3}function ss(a10){return a10>>>2|0}function hN(a10){return a10<<2|2}function ch(a10){return a10&ls(sr)}function hO(a10){return a10[2]}function hP(a10){return a10[3]}function hQ(a10){return[0,0,0,0]}function c9(a10){a10[1]=a10[1]+1|0}function c_(a10){a10[2]=a10[2]+1|0}function c$(a10){a10[3]=a10[3]+1|0}function eO(a10,b10,c10){for(var d10=c10;;){if(typeof d10=="number")return;if(d10[0]===0){var e10=d10[1],i10=(e10&3)!==3?1:0,l10=i10&&(e10&3?1:0);if(l10){if(e10&b10)throw g([0,f,su],1);c9(a10),c$(a10),d10[1]=e10|3}return}var h10=d10[1],j10=(h10&3)!==3?1:0,k10=j10&&(h10&3?1:0);if(!k10)return k10;if(h10&b10)throw g([0,f,sv],1);c9(a10),c$(a10),d10[1]=h10|3,eO(a10,b10,d10[2]),d10=d10[3]}}function da(a10,b10,c10,d10){if(typeof d10!="number"){if(d10[0]===0){var e10=d10[1];e10&c10||(c9(a10),e10&3?(d10[1]=-1,c$(a10),c_(a10)):d10[1]=e10|c10);var g10=e10!==-1?1:0,h10=g10&&((e10&3)===3?1:0);return h10&&(d10[1]=-1,c_(a10))}var f10=d10[1];f10&c10||(c9(a10),f10&3?(d10[1]=-1,c$(a10),c_(a10),eO(a10,c10,d10[2]),eO(a10,c10,d10[3])):(d10[1]=f10|c10,ej(d10,b10)));var i10=f10!==-1?1:0,j10=i10&&((f10&3)===3?1:0);return j10&&(d10[1]=-1,c_(a10))}}function eP(a10,b10,c10){var d10=gP(b10);if(typeof d10!="number"&&d10[0]===1){var e10=(d10[1]&3)===c10?1:0;return e10&&(da(a10,b10,c10,d10[2]),da(a10,b10,c10,d10[3]))}throw g([0,f,sw],1)}function hR(a10,b10,c10){for(;;){if(ek(b10))return;eP(a10,b10,c10)}}function sx(a10,b10,c10,d10){for(;;){if(ek(c10))return hR(b10,d10,eM);if(ek(d10))return hR(a10,c10,eL);eP(a10,c10,eL),eP(b10,d10,eM)}}function eQ(a10){var b10=a10[6];return a10[6]=b10+1|0,b10}function eR(a10){for(var b10=a10;;){if(typeof b10=="number")return;if(b10[0]===0){var c10=b10[1];if(typeof c10!="number"&&c10[0]===0){var e10=c10[1],i10=eN(e10),l10=i10&&bQ(e10);l10&&(c10[1]=ch(e10));return}throw g([0,f,sC],1)}var d10=b10[1];if(typeof d10!="number"&&d10[0]===1){var h10=d10[1],m10=b10[4],n10=b10[3],j10=eN(h10),k10=j10&&bQ(h10);if(!k10)return k10;d10[1]=ch(h10),eR(n10),b10=m10;continue}throw g([0,f,sD],1)}}function hS(a10,b10){for(var c10=b10;;){if(typeof c10=="number")return;if(c10[0]===0){var d10=c10[1];if(typeof d10!="number"&&d10[0]===0){var e10=d10[1],u10=c10[2];if(!hK(e10)){if(hJ(e10)){var k10=eQ(a10);j(a10[4],k10)[1+k10]=d10,j(a10[5],k10)[1+k10]=[0,c10,0],d10[1]=hN(k10);return}if(hL(e10)){var n10=ss(e10),v10=[0,c10,j(a10[5],n10)[1+n10]];j(a10[5],n10)[1+n10]=v10;return}var q10=bQ(e10);if(q10)throw g([0,f,sG],1);return q10}var m10=a10[2];if(-1a10[3]))throw g([0,f,sF],1);d10[1]=ch(e10);return}throw g([0,f,sE],1)}var h10=c10[1];if(typeof h10!="number"&&h10[0]===1){var r10=c10[4],s10=c10[3],i10=h10[1],w10=c10[2];if(hJ(i10)){var l10=eQ(a10);return j(a10[4],l10)[1+l10]=h10,j(a10[5],l10)[1+l10]=[0,c10,0],h10[1]=hN(l10),eR(s10),eR(r10)}if(!hK(i10)){if(hL(i10)){var o10=i10>>>2|0,x10=[0,c10,j(a10[5],o10)[1+o10]];j(a10[5],o10)[1+o10]=x10;return}var t10=bQ(i10);if(t10)throw g([0,f,sJ],1);return t10}if(-1a10[3])throw g([0,f,sI],1)}h10[1]=ch(i10),hS(a10,s10),c10=r10;continue}throw g([0,f,sH],1)}}function ci(a10,b10){if(typeof b10=="number")return 0;if(b10[0]!==0){var i10=b10[1];if(i10===-1){var l10=eQ(a10);b10[1]=0,j(a10[4],l10)[1+l10]=b10;var p10=ci(a10,b10[2]);return[1,b10,0,p10,ci(a10,b10[3])]}if(!bQ(i10)){b10[1]=ch(b10[1]);var r10=ci(a10,b10[2]);return[1,b10,0,r10,ci(a10,b10[3])]}var d10=i10>>>2|0,k10=j(a10[5],d10)[1+d10];if(!k10)throw g([0,f,sM],1);var m10=k10[2],q10=k10[1];return j(a10[5],d10)[1+d10]=m10,m10===0&&(b10[1]=0),q10}var e10=b10[1];if(eN(e10)&&bQ(e10)){var c10=e10>>>2|0,h10=j(a10[5],c10)[1+c10];if(!h10)return[0,b10,0];var n10=h10[2],o10=h10[1];return j(a10[5],c10)[1+c10]=n10,o10}return b10[1]=0,[0,b10,0]}var eS=[0,0,[0],0,0];function st(a10){return a10[1]}function sy(a10){return a10[1]}function sz(a10){return a10[2]}function sA(a10,b10){var c10=hQ(0),d10=hQ(0),e10=eh(0),f10=eh(0);return da(c10,e10,eL,a10),da(d10,f10,eM,b10),sx(c10,d10,e10,f10),[0,c10,d10]}function sB(a10){if(typeof a10!="number"){if(a10[0]===0){a10[1]=0;return}var b10=c8(a10[3]);a10[1]=(hH(c8(a10[2]),b10)+1|0)<<2}}function sK(a10){var e10=a10[6]-1|0,h10=0;if(e10>=0)for(var b10=h10;;){var c10=j(a10[4],b10)[1+b10];typeof c10!="number"&&(c10[0],c10[1]=hM(c10[1]));var d10=j(a10[5],b10)[1+b10];if(!d10)throw g([0,f,sL],1);if(d10[2]){var i10=a3(d10);j(a10[5],b10)[1+b10]=i10}var k10=b10+1|0;if(e10===b10)break;b10=k10}}function hT(a10,b10,c10){if(typeof b10=="number"){if(typeof c10=="number")return[0,eS,0]}else if(b10[1]===c10)return[0,eS,b10];var t10=typeof b10=="number"?cg:b10[1],m10=sA(t10,c10),i10=sy(m10),n10=sz(m10),u10=hP(n10),v10=hP(i10)+u10|0,o10=st(i10)-v10|0,w10=hO(n10),p10=hO(i10)+w10|0,x10=0,y10=ap(p10,0),z10=ap(p10,0),A2=a10?o10:-1,B2=a10?0:-1,C2=a10?ap(o10,0):[0],d10=[0,C2,B2,A2,z10,y10,x10];if(hS(d10,b10),d10[2]!==d10[3])throw g([0,f,sN],1);sK(d10);var q10=ci(d10,c10),r10=d10[6]-1|0;if(r10>=0)for(var h10=r10;;){sB(j(d10[4],h10)[1+h10]);var F2=h10-1|0;if(h10===0)break;h10=F2}if(!a10)return[0,eS,q10];var k10=[0,0],l10=[0,0],s10=d10[6]-1|0,D2=0;if(s10>=0)for(var e10=D2;;){a4(function(a11){if(typeof a11!="number")if(a11[0]===0){var b11=a11[2];if(b11)return k10[1]=[0,b11[1],k10[1]],0}else{var c11=a11[2];if(c11)return l10[1]=[0,c11[1],l10[1]],0}return 0},j(d10[5],e10)[1+e10]);var E2=e10+1|0;if(s10===e10)break;e10=E2}return[0,[0,d10[2],d10[1],k10[1],l10[1]],q10]}function sO(d10,b10){if(typeof b10=="number")return 0;function c10(a10){a:if(typeof a10!="number"){b:{if(a10[0]===0){var b11=a10[1];if(typeof b11!="number"&&b11[0]===0){var e10=a10[2];if(e10){var j10=e10[1];break b}var k10=h(d10[1],b11[2]);return a10[2]=[0,k10],k10}break a}var l10=a10[2];if(!l10){var n10=c10(a10[3]),o10=c10(a10[4]),m10=i(d10[2],n10,o10);return a10[2]=[0,m10],m10}var j10=l10[1]}return j10}throw g([0,f,sP],1)}return[0,c10(b10)]}function db(a10,b10){return[0,[0,a10,b10],0]}function dc(a10){return sO(a10[1],a10[2])}function sQ(a10,b10){var c10=a10[1];return[0,c10,hT(0,a10[2],b10)[2]]}function eT(a10,b10){var d10=a10[1],c10=hT(1,a10[2],b10);return[0,c10[1],[0,d10,c10[2]]]}function dd(a10,b10,c10,d10){var e10=[0,d10];if(v===a10)var h10=c10[1],g10=0;else if(j7<=a10)var h10=c10[2].length-1,g10=c10[1];else var h10=c10[2].length-1,g10=0;var k10=h10-1|0;if(k10>=g10)for(var f10=g10;;){var l10=j(c10[2],f10)[1+f10];l10&&(e10[1]=i(b10,l10[1],e10[1]));var m10=f10+1|0;if(k10===f10)break;f10=m10}j7>a10&&a4(function(a11){return e10[1]=i(b10,a11,e10[1]),0},c10[3]),v!==a10&&a4(function(a11){return e10[1]=i(b10,a11,e10[1]),0},c10[4])}function eU(a10,b10,c10){if(typeof c10=="number")throw g([0,f,sR],1);if(c10[0]===0)return h(a10,c10[2]);var d10=eU(a10,b10,c10[3]);return i(b10,eU(a10,b10,c10[2]),d10)}function bj(a10,b10,c10){var d10=b10[2],e10=b10[1],f10=c2(c10);if(f10){var g10=f10[1];return Q(typeof g10=="number"?e10:eU(a10,d10,g10))}var h10=[0,db(a10,d10)];return l(c10,function(a11){var b11=sQ(h10[1],a11);h10[1]=b11;var c11=dc(b11);return c11?c11[1]:e10})}var aQ=[0,cg,az];function sS(a10,b10){return c5(b10,aQ,a10)}function de(a10){return sS(a10,J)}function hU(a10){function e10(a11,b10){for(var c10=a11,d10=b10;;){if(typeof c10=="number")return d10;if(c10[0]===0)return[0,c10[2],d10];var f10=e10(c10[3],d10);c10=c10[2],d10=f10}}return e10(a10,0)}var hV=[0,Q(0),function(a10,b10){return cc(a10,b10,az)}];function eV(c10,b10){return bj(function(a10){return J(h(c10,a10))},aQ,b10)}function sT(a10,b10){return hr(bj(b10,hV,a10))}function bk(a10){return sT(a10,function(a11){return l(a11,J)})}var bl=e;function sU(a10){return a10[kO]}function hW(a10,b10){var c10=a10?a10[1]:bl;return z5(b10).join(c10)}function eW(a10){return sU(a10)===0?1:0}function df(a10,b10){return k3(a10,b10)}p.Number;var eX=null,sV=void 0;function cj(a10){return a10===eX?1:0}function sW(a10){return a10===sV?1:0}function bR(a10){var b10=cj(a10);return b10||sW(a10)}function hX(a10){return 1-bR(a10)}function dg(a10,b10){return bR(b10)?0:[0,h(a10,b10)]}var k=p;function eY(a10,b10){var c10=a10[b10];return bR(c10)?0:[0,c10]}function eZ(a10){return new k[jX](a10)}function hY(a10){return a10[kO]}function hZ(c10,b10){return gM(hY(b10),function(a10){return h(c10,b10[a10])})}function h0(a10,b10){var d10=b10.length-1,e10=eZ(d10),f10=d10-1|0,g10=0;if(f10>=0)for(var c10=g10;;){e10[c10]=h(a10,j(b10,c10)[1+c10]);var i10=c10+1|0;if(f10===c10)break;c10=i10}return e10}function e0(f10,b10){return function(a10,b11,c10){for(var e10=a10,d10=c10;;){if(!d10)return b11;var g10=d10[2];b11[e10]=h(f10,d10[1]),e10=e10+1|0,d10=g10}}(0,eZ(0),b10)}function s1(a10,b10){var c10=new k.Error(b10);return a10&&(c10[cq]=a10[1]),c10}var s3=Symbol.iterator;function s5(a10){return a10.next()}function s6(a10){var b10=dg(function(a11){return a11|0},a10.done);return b10?b10[1]:0}function s7(a10){return a10[dE]}function h1(i10,g10,c10,d10,e10){return function(a10,b10){for(var d11=b10;;){var e11=s5(a10);if(s6(e11))return d11;var f10=s7(e11),j10=h(g10,f10[1]);d11=x(c10,h(i10,f10[0]),j10,d11)}}(d10,e10)}k.Promise;function sZ(a10){return as(a10)}function bm(a10,b10,c10){return dZ(a10,sZ(b10),c10)}function aA(a10){return as(a10)}function A(a10){return H(a10)}function bS(a10,b10){return a10 instanceof b10?1:0}var sX=!0;function sY(a10,b10){a10[b10]}function s0(c10,b10){return lY(hY(b10),function(a10){return h(c10,b10[a10])})}function s2(a10,b10){return h(function(a11){throw a11},s1(a10,b10))}function s4(a10){return a10[s3]()}k.Event;function e1(a10){return a10[fy]}function h2(a10,b10,c10,d10){var e10=a10?a10[1]:{},f10=by(1,c10);return d10.addEventListener(b10,f10,e10),function(a11){return d10.removeEventListener(b10,f10,e10),0}}function h3(a10){return h(a10,0)}var e2="change",dh="click";k.ArrayBuffer,k.DataView;function s8(a10){return a10.preventDefault(),0}var s9="DOMContentLoaded",s_=kd,s$="scroll",ta="wheel";k.Blob,k.File;var h4=k.JSON;k.encodeURI,k.decodeURI,k.encodeURIComponent,k.decodeURIComponent,k.URL,k.URLSearchParams;function aR(a10,b10){return[0,a10,b10]}var di=[0,bl,bl];function e3(a10){return[0,a10,bl]}function h5(a10){return a10}var ck=kx,e4=jQ,h6=cq,h7=jC,e5="type",e6=dE,te="for";function aS(a10){return aR(ck,a10)}function h8(a10){return aR(te,a10)}var tg=e3(jo),ti=e3("required");function dj(a10){return aR(h7,a10)}var tj=e3("selected"),bn=k.document;function tb(a10){return h4.stringify(a10)}function tc(a10){try{var c10=h4.parse(a10)}catch(f10){var b10=L(f10);if(b10[1]===eA)return[1,b10[2]];throw g(b10,0)}return[0,c10]}function td(a10,b10){return a10?b10:di}var tf="placeholder";function th(a10){return aR(e4,a10)}function tk(a10){return aR(e5,a10)}function tl(a10){return aR(e6,a10)}function tm(a10){return a10.ownerDocument}bR(bn)||bn[jL];function tn(a10,b10){return a10.appendChild(b10),0}function to(a10,b10,c10,d10){for(var g10=b10,f10=c10,e10=d10;;){if(!e10){g10!==0&&a10.setAttribute(jC,hW([0,";"],a3(g10))),f10!==0&&a10.setAttribute(kx,hW([0,aE],a3(f10)));return}var h10=e10[2],k10=e10[1],i10=k10[2],j10=k10[1];if(eW(j10))e10=h10;else if(df(j10,h7))g10=[0,i10,g10],e10=h10;else if(df(j10,ck)){var l10=eW(i10)?f10:[0,i10,f10];f10=l10,e10=h10}else a10.setAttribute(j10,i10),e10=h10}}function h9(a10,b10,c10,d10){var f10=a10?a10[1]:bn,g10=b10?b10[1]:0,e10=f10.createElement(c10);return to(e10,0,0,g10),a4(function(a11){return tn(e10,a11)},d10),e10}function bo(a10,b10){var c10=a10?a10[1]:bn;return c10.createTextNode(A(b10))}function h_(a10,b10,c10){return eW(a10)?0:b10?(c10.setAttribute(a10,b10[1]),0):(c10.removeAttribute(a10),0)}function h$(a10,b10,c10){return b10?(c10[jp].add(a10),0):(c10[jp].remove(a10),0)}var ia="div";function ty(a10,b10,c10,d10){return h9(b10,c10,a10,d10)}function ib(a10,b10,c10){return ty(ia,a10,b10,c10)}function ic(a10){return a10[jL]}function dk(a10,b10,c10){return dZ(a10,b10,c10),0}var dl=k[kS];function dm(a10){return z2(function(a11,b10,c10){for(var e10=b10,d10=c10;;){if(!d10)return a11;var f10=d10[2];a11[e10]=d10[1],e10=e10+1|0,d10=f10}}(eZ(0),0,a10))}function ah(a10){return dk(dl,tB,dm(a10))}function e7(a10){return dk(dl,tG,dm(a10))}k[kS],k.navigator;var tJ=k.performance,dn=k[ks];sY(k,tK);function tp(a10,b10){dZ(a10,kI,ee(b10))}function tq(a10,b10,c10){var e10=a10?a10[1]:k[ks],d10=e10.getComputedStyle(c10)[b10];return bR(d10)?bl:d10}function tr(a10,b10){var c10=a10?a10[1]:kk,d10=kk<=c10?1:0;return b10.scrollIntoView(!!d10),0}var ts="button",tt="form",tu=kd,tv="label",tw="option",tx="select";function tz(a10){var b10=a10.body;return hX(b10)?b10:s2(0,"Document body is null. Try to defer your script execution.")}function tA(a10){return dg(function(a11){return a11},a10.activeElement)}function tC(a10){return dk(dl,tD,dm(a10))}function tE(a10){return dk(dl,tF,dm(a10))}function tH(a10){return a10}function tI(a10){return a10.now()}function tL(a10,b10){return k.setTimeout(by(1,b10),a10)}function tM(a10){k.clearTimeout(a10)}function tN(a10){k.requestAnimationFrame(by(1,a10))}k.ClipboardItem,k.FormData,k.Headers,k.Request,k.Response,k.fetch,k.MediaStream,k.MediaRecorder,k.MessageChannel,k.BroadcastChannel,k.Notification,k.WebSocket;function tO(a10){return a10.localStorage}function tP(a10,b10){function c10(a11){return a11}return function(a11){return dg(c10,a11)}(a10.getItem(b10))}function tQ(a10,b10,c10){try{a10.setItem(b10,c10);return}catch(f10){var d10=L(f10);if(d10[1]===eA)return;throw g(d10,0)}}function aB(a10,b10,c10){return[0,a10,b10,c10]}function id2(a10){var b10=a10[1];return b10===82||83<=b10?gy(c2(a10[2])):1}function dp(a10){return cL(c2(a10))}function tR(a10){return d$(cM(function(a11){var b10=a11[1];return b10===82?[0,dp(a11[2]),0]:83<=b10?hU(dp(a11[2])):[0,a11[2],0]},a10))}function ie(a10){if(!a10)return tS;var b10=l2(id2,a10),c10=b10[2];return[0,tR(b10[1]),c10]}var ig=kI,e8="before";function tV(a10){return[0,a10]}function tW(a10,b10){return[1,eX,a10,b10]}var tX="remove",tY="contains";function ih(a10){var b10=tA(tm(a10));return b10?bm(a10,tY,[0,b10[1]])|0:0}function ii(e10,b10){var c10=[0,db(tV,tW)];return l(b10,function(a10){var b11=eT(c10[1],a10),d10=b11[2],g10=b11[1];c10[1]=d10,dd(v,function(a11,b12){return a11[0]===0?a11[1][dD]=sX:0},g10,0);var h10=ih(e10),i10=dc(d10);if(i10){var f10=function(d11,b12){if(b12[0]!==0){if(!cj(b12[1]))return b12[1];var l10=f10(d11,b12[3]),k10=f10(l10,b12[2]);return b12[1]=k10,k10}var c11=b12[1];if(delete c11[dD],c11.parentNode!==e10)cj(d11)?bm(e10,ig,[0,c11]):bm(d11,e8,[0,c11]);else{var a11=c11.nextSibling!==d11?1:0;if(a11){if(h10)var g11=ih(c11),i11=g11&&function(a12){for(;;){var b13=c11.nextSibling;if(b13===d11)return 1;if(cj(b13))return 0;bm(c11,e8,[0,b13])}}(0);else var i11=h10;var j10=1-i11}else var j10=a11;j10&&(cj(d11)?bm(e10,ig,[0,c11]):bm(d11,e8,[0,c11]))}return c11};f10(eX,i10[1])}return dd(v,function(a11,b12){if(a11[0]!==0)return 0;var c11=a11[1],d11=hX(c11[dD]),e11=d11&&(delete c11[dD],bm(c11,tX,[0]),0);return e11},g10,0),e10})}var dq=Q(0),e9=[0,bl,bl];function tT(a10){if(!a10)return tU;var b10=a10[1],c10=b10[1];if(c10===82){if(!a10[2])return[0,0,[0,l(b10[2],J)]]}else if(83<=c10){if(!a10[2])return[0,0,[0,b10[2]]]}else if(!a10[2])return[0,[0,b10[2],0],0];return l0(id2,a10)?[0,d$(cM(function(a11){var b11=a11[1];return b11===82?[0,dp(a11[2]),0]:83<=b11?hU(dp(a11[2])):[0,a11[2],0]},a10)),0]:[0,0,[0,c5(function(a11){var b11=a11[1];return b11===82?l(a11[2],J):83<=b11?a11[2]:Q(J(a11[2]))},hV,a10)]]}function ij(c10,b10){function d10(a10){var b11=a10[2],d11=a10[1];return df(d11,ck)?h$(b11,1,c10):h_(d11,[0,b11],c10)}function e10(a10){var b11=a10[1],d11=a10[2];return df(b11,ck)?h$(d11,0,c10):h_(b11,0,c10)}function h10(a10){var b11=[0,e9];return function(a11){b11[1]!==e9&&e10(b11[1]);var c11=a11;return d10(c11),b11[1]=c11,0}}return c5(function(a10){var b11=a10[1];if(b11===82){var i10=a10[2];return l(i10,h10(0))}if(83>b11)throw g([0,f,tZ],1);var j10=a10[2],c11=[0,db(function(a11){var b12=a11;return d10(b12),b12},function(a11,b12){return e9})];return l(j10,function(a11){var b12=eT(c11[1],a11),d11=b12[2],f10=b12[1];return c11[1]=d11,dd(v,function(a12,b13){return e10(a12)},f10,0),dc(d11),0})},[0,dq,function(a10,b11){return dq}],b10)}function e_(a10,b10){return h2(b10[1],b10[2],b10[3],a10)}function t0(c10,b10){return c5(function(a10){var b11=a10[1];if(b11===82){var d10=[0,0];return l(a10[2],function(a11){var b12=d10[1];return b12&&h3(b12[1]),d10[1]=[0,e_(c10,a11)],0})}if(83>b11)throw g([0,f,t1],1);var h10=a10[2],e10=[0,db(function(a11){return e_(c10,a11)},function(a11,b12){return a11})];return l(h10,function(a11){var b12=eT(e10[1],a11),c11=b12[2],d11=b12[1];return e10[1]=c11,dd(v,function(a12,b13){return h3(a12)},d11,0),dc(c11),0})},[0,dq,function(a10,b11){return dq}],b10)}function ik(a10,b10,c10,d10,e10,f10){var q10=b10?b10[1]:0,r10=c10?c10[1]:0,s10=d10?d10[1]:function(a11){},m10=ie(q10),k10=m10[2],t10=m10[1],n10=ie(r10),o10=n10[2],u10=n10[1],p10=tT(f10),i10=p10[2],g10=h9(a10,[0,t10],e10,p10[1]);if(h(s10,g10),k10)if(i10)var v10=ii(g10,i10[1]),j10=cc(ij(g10,k10),v10,function(a11,b11){return b11});else var j10=l(ij(g10,k10),function(a11){return g10});else var j10=i10?ii(g10,i10[1]):Q(g10);a4(function(a11){return e_(g10,a11),0},u10);var w10=o10?cc(t0(g10,o10),j10,function(a11,b11){return b11}):j10;return w10}function bT(a10,b10,c10,d10,e10,f10){return ik(b10,c10,d10,e10,a10,f10)}function t2(a10,b10,c10,d10,e10,f10){return ik(b10,c10,d10,e10,a10,0)}function e$(a10,b10,c10,d10,e10){return bT(ts,a10,b10,c10,d10,e10)}function R(a10,b10,c10,d10,e10){return bT(ia,a10,b10,c10,d10,e10)}function il(a10,b10,c10,d10,e10){return t2(tu,a10,b10,c10,d10,e10)}function im(a10,b10,c10,d10,e10){return bT(tv,a10,b10,c10,d10,e10)}function t3(a10,b10,c10,d10,e10){return bT(tt,a10,b10,c10,d10,e10)}function t4(a10,b10,c10,d10,e10){return bT(tw,a10,b10,c10,d10,e10)}function t5(a10,b10,c10,d10,e10){return bT(tx,a10,b10,c10,d10,e10)}function dr(a10,b10){return b10=c10)return uk;if(b10===jl)return uj;if(b10==="cyan")return ui;if(b10==="green")return uh;if(b10==="magenta")return ug;if(b10==="red")return uf;if(b10==="reset")return ue;if(b10==="white")return ud;if(b10==="yellow")return uc}else{if(b10==="Black")return ut;if(b10==="Blue")return us;if(b10==="Cyan")return ur;if(b10==="Green")return uq;if(b10==="Magenta")return up;if(b10==="Red")return uo;if(b10==="White")return un;if(b10==="Yellow")return um;if(b10==="black")return ul}throw g(fb,1)}function iq(a10,b10){return a5(b10,a10),uv}function ir(a10){try{mE(a10),mF(a10)}catch(f10){var b10=L(f10);if(b10!==eg)throw g(b10,0)}return uw}var is=[q,ux,ae(0)],uu=0;function uy(a10,b10,c10){if(c10[1]===is)return iq(a10,c10[2]);if(c10[1]!==b$)return h(b10,c10);var e10=c10[2];try{var f10=iq(a10,ip(e10));return f10}catch(f11){var d10=L(f11);if(d10===fb)return h(b10,c10);throw g(d10,0)}}function uz(a10,b10,c10){if(c10[1]===is)return ir(a10);if(c10[1]!==b$)return h(b10,c10);var e10=c10[2];try{ip(e10)}catch(f10){var d10=L(f10);if(d10===fb)return h(b10,c10);throw g(d10,0)}return ir(a10)}function uA(a10){var c10=bC(0);p$(a10,1);var b10=qa(a10,0),d10=b10[2],e10=b10[1];return qb(a10,[0,function(a11){return uy(c10,e10,a11)},function(a11){return uz(c10,d10,a11)},b10[3],b10[4]])}function uB(a10,b10){var d10=b8(64),c10=ez(d10),e10=a10&&uu;return e10&&uA(c10),qH(function(a11){return bJ(c10,0),cQ(d10)},c10,b10)}function uC(a10){return uB(1,a10)}function uD(a10,b10){return l4(a10,b10)}function uE(a10){try{var c10=[0,k$(a10)];return c10}catch(f10){var b10=L(f10);if(b10[1]===b3)return 0;throw g(b10,0)}}function uF(a10){return a10|0}function uH(a10,b10,c10,d10){for(var g10=a10,f10=b10,e10=d10;;){if(!e10){g10[1+f10]=0;return}var j10=e10[2],i10=[0,h(c10,e10[1]),kj];g10[1+f10]=i10,g10=i10,f10=1,e10=j10}}function uG(a10,b10){if(!b10)return 0;var d10=b10[2],c10=[0,h(a10,b10[1]),kj];return uH(c10,1,a10,d10),c10}function fc(a10,b10){return b10?[0,h(a10,b10[1])]:0}function uI(a10,b10,c10){return c10?h(b10,c10[1]):a10}function uJ(a10,b10){if(b10)return h(a10,b10[1])}function uK(a10,b10){return b10?b10[1]:a10}function uL(a10,b10){return a10?a10[1]:b10}function uM(a10){return a10?[0,a10[1],0]:0}function uN(a10,b10){return b10[0]===0?h(a10,b10[1]):[1,b10[1]]}function uO(a10,b10){return uN(b10,a10)}function uP(a10){var b10=mw(a10);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b10[37],,,,,,,,,,,b10[23]]}function uQ(a10){var b10=uP(a10);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b10[40],,,,,,,,,,,,,,,,,,,,b10[51]]}function uR(e10,b10){var d10=n(e10);if(dr(d10,n(b10)))return 0;var f10=n(b10)-d10|0;return function(a10){for(var c10=a10;;){if(t6(c10,d10))return 1;if(_(b10,f10+c10|0)!==_(e10,c10))return 0;c10=c10+1|0}}(0)}function fd(a10,b10){return uR(a10,b10)?[0,ec(b10,0,n(b10)-n(a10)|0)]:0}var it=[q,uT,ae(0)];function iu(a10){return[0,[0,a10]]}function bp(a10,b10,c10,d10){return[1,a10,b10,c10,d10]}function uV(a10){return a10[0]===0&&typeof a10[1]=="number"?1:0}function iv(a10,b10){if(b10[0]===0){var c10=b10[1];if(typeof c10=="number")return iu(a10);switch(c10[0]){case 0:return[0,[1,a10,c10[1]]];case 1:return[0,[2,a10,c10[1],c10[2]]];default:return bp(4,[1,a10,c10[1]],uU,[1,c10[2],c10[3]])}}var d10=b10[2],f10=b10[1];if(typeof d10!="number")switch(d10[0]){case 0:break;case 1:return bp(f10+1|0,[2,a10,d10[1],d10[2]],b10[3],b10[4]);default:var e10=b10[3],h10=d10[3],i10=d10[2],j10=d10[1],g10=aw(e10),k10=aD===g10?e10[1]:ba===g10?cK(e10):e10;return bp(f10+1|0,[1,a10,j10],[ba,function(a11){return iv([0,i10,h10],k10)}],b10[4])}return bp(f10+1|0,[1,a10,d10[1]],b10[3],b10[4])}function iw(a10){if(a10[0]===0){var b10=a10[1];if(typeof b10=="number")throw g(it,1);switch(b10[0]){case 0:return[0,uS,b10[1]];case 1:var n10=b10[2];return[0,iu(b10[1]),n10];default:return[0,[0,[1,b10[1],b10[2]]],b10[3]]}}var d10=a10[3],e10=a10[2],f10=a10[1],i10=aw(d10),j10=aD===i10?d10[1]:ba===i10?cK(d10):d10,h10=a10[4];if(typeof h10!="number"&&h10[0]!==0){var c10=a10[4];if(typeof c10!="number"&&c10[0]===2){var q10=c10[3];return[0,bp(f10-1|0,e10,d10,[1,c10[1],c10[2]]),q10]}var p10=c10[2];return[0,bp(f10-1|0,e10,d10,[0,c10[1]]),p10]}var k10=h10[1];if(uV(j10))return[0,[0,e10],k10];var l10=iw(j10),m10=l10[2],o10=[1,m10[1],m10[2]];return[0,bp(f10-1|0,e10,lI(l10[1]),o10),k10]}function uX(a10){if(typeof a10=="number")return 0;switch(a10[0]){case 0:return 1;case 1:return 2;default:return 3}}function uW(a10){try{var c10=[0,iw(a10)];return c10}catch(f10){var b10=L(f10);if(b10===it)return 0;throw g(b10,0)}}function uY(a10){return a10[0]===0?uX(a10[1]):a10[1]}function uZ(a10){return a10.height}function u0(a10){return a10}function u3(a10){switch(a10){case 0:return u4;case 1:return u5;default:return u6}}function u1(a10){return a10.contentRect}function u2(a10){a10[fy]}function u7(a10,b10,c10){var d10=b10?[0,c10,{box:A(u3(b10[1]))}]:[0,c10];return dZ(a10,"observe",d10),0}function u8(c10){return new k.ResizeObserver(function(a10,b10){return i(c10,s0(function(a11){return a11},a10),b10)})}var u9=jy,u_="pattern",ix=uQ([0,ed]);function u$(a10,b10){return h(a10,b10),b10}function va(a10){var b10=fd(vb,a10);if(b10){var c10=b10[1],d10=uE(c10);if(d10)return[0,[0,d10[1]]];var g10=function(a11){return[0,a11]};return function(a11){return fc(g10,a11)}(fa(c10))}var e10=fd(vc,a10);if(e10){var h10=function(a11){return[1,a11]};return function(a11){return fc(h10,a11)}(fa(e10[1]))}var f10=fd(vd,a10);if(!f10)return 0;function i10(a11){return[1,a11]}return function(a11){return fc(i10,a11)}(fa(f10[1]))}function iy(a10){switch(a10[0]){case 0:var b10=a10[1];return h(C(ve),b10);case 1:var c10=a10[1];return h(C(vf),c10);default:var d10=a10[1];return h(C(vg),d10)}}function iz(a10){var c10=a10?a10[1]:ic(bn);function b10(a11){var b11=va(as(tq(0,"font-size",a11)));if(!b11)return 16;var c11=b11[1];return c11[0]===0?c11[1]:aK(vh)}return function(a11){switch(a11[0]){case 0:return a11[1];case 1:var d10=a11[1];return d10*b10(ic(bn));default:var e10=a11[1];return e10*b10(c10)}}}function vi(e10,b10,c10,d10){function f10(a10,b11){return cc(d10,a10,b11)}function g10(a10,b11){return x(e10,b11[1],b11[2],a10)}return function(a10){return f10(a10,g10)}(cc(b10,c10,function(a10,b11){return[0,a10,b11]}))}var vl=[q,vk,ae(0)],vn=[q,vm,ae(0)];function iA(a10){return[0,0]}function iB(a10,b10){if(a10[1])throw g(vn,1);return a10[1]=[0,b10],0}function iC(a10){var b10=a10[1];if(b10)return b10[1];throw g(vl,1)}function vj(a10,b10,c10){return vi(function(a11,b11,c11){return[0,a11,b11,c11]},a10,b10,c10)}function vo(a10){return tb(a10)}function vp(a10){var b10=tc(a10);return b10[0]===0?[0,b10[1]]:(tC([0,b10[1],0]),vq)}var iD=eu(0,64),iE=tO(dn);function vr(a10){return pT(iD,a10)?aK(h(C(vs),a10)):pQ(iD,a10,0)}function iF(c10,b10){return function(a10){return tQ(iE,c10,a10)}(vo(b10))}function vt(a10){var b10=tP(iE,a10);function c10(a11){return vp(a11)}var d10=b10?[0,b10[1]]:vu;return uO(d10,c10)}function vv(a10,b10){var c10=vt(a10);if(c10[0]===0)return c10[1];var d10=c10[1];return typeof d10=="number"||tE([0,d10[2],0]),h(b10,0)}function vw(d10,b10){iF(d10,b10);var a10=am(b10),c10=eE(0,a10);return eF(c10,function(a11){return iF(d10,bO(c10)),0}),bO(c10),a10}function vx(a10,b10){vr(a10);var c10=H(a10);return vw(c10,vv(c10,b10))}function iG(a10,b10){return vx(a10,function(a11){return b10})}var vz=ix[49],vy=ix[29];function vA(a10){return uG(function(a11){return[0,80,aS(H(a11))]},vz(a10))}var vB=0;function a8(d10,b10,c10){var a10=b10[1],e10=a10===82?[0,82,l(b10[2],function(a11){return function(a12){return aR(d10,a12)}(H(a11))})]:83<=a10?aK(vE):[0,80,function(a11){return aR(d10,a11)}(H(b10[2]))];return[0,e10,c10]}function fe(d10,b10,c10){return b10?[0,[0,80,function(a10){return aR(d10,a10)}(H(b10[1]))],c10]:c10}function iH(a10,b10){var c10=b10[1];return c10===82?[0,82,l(b10[2],a10)]:83<=c10?[0,83,eV(a10,b10[2])]:[0,80,h(a10,b10[2])]}function vG(a10){return a10[0]===0?aS(H(a10[1])):a10[1]}function ff(a10,b10){return[0,iH(vG,a10),b10]}function au(a10){return ff(a10,0)}function ds(a10,b10){return ff(a10,b10)}function vC(a10,b10){var d10=vA(b10[1]),e10=b10[2],c10=function(a11){return bB(e10,a11)}(d10);return a10?[0,[0,80,th(H(a10[1]))],c10]:c10}function vD(a10){return[0,vy(a10),vB]}function vF(a10,b10,c10){return b10?[0,[0,80,a10],c10]:c10}function vH(a10){return ff(iH(function(a11){return[0,a11]},a10),0)}function vI(a10,b10){return b10[0]===0?(a10.scroll(0,b10[1]),0):tr(0,b10[1])}function vJ(a10,b10,c10,d10,e10){var g10=a10?a10[1]:0,h10=b10?b10[1]:0,f10=am(1),i10=ds(vK,ds([0,82,l(f10,function(a11){return a11?[1,aS("locked")]:[1,di]})],g10)),j10=vH(vL),k10=[0,[0,80,aB(0,dh,function(a11){return ac(f10,1)})],0],m10=R(0,[0,j10],[0,k10],0,[0,[0,82,e$(0,0,0,0,[0,[0,80,bo(0,vM)],0])],0]),n10=aB(0,ta,function(a11){var b11=bM(f10);return b11&&ac(f10,0)});return R(0,[0,i10],[0,[0,[0,80,n10],h10]],c10,[0,[0,82,l(vj(e10,f10,d10),function(a11){var b11=a11[1],c11=a11[3];return a11[2]&&uJ(function(a12){return vI(b11,a12)},c11),b11})],[0,[0,82,m10],0]])}function dt(a10,b10){return typeof b10=="number"?0:b10[0]===0?[0,h(a10,b10[1])]:[1,b10[1]]}function vN(e10,b10,c10){var d10=am(c10);return[0,aB(0,b10,function(a10){return ac(d10,h(e10,e1(a10)[dE]))}),d10]}function iI(a10,b10,c10,d10,e10,f10,g10,h10,i10,j10){var l10=d10?d10[1]:0,m10=f10?f10[1]:0,n10=function(a11){return fe(u_,h10,a11)}(function(a11){return vF(ti,m10,a11)}([0,[0,80,tk(H(i10))],l10])),o10=uL(b10,function(a11){return[0,a11]}),k10=vN(a10,g10,j10),p10=k10[2],q10=k10[1];return[0,il(c10,[0,n10],[0,[0,[0,80,q10],uM(e10)]],0,0),p10,o10]}function du(a10,b10,c10,d10,e10,f10,g10,h10){var i10=c10?c10[1]:0,j10=function(a11){return fe(e6,h10,a11)}(function(a11){return fe(tf,g10,a11)}(i10));return iI(aA,a10,b10,[0,j10],d10,e10,s_,f10,vP,uK(vO,h10))}function dv(a10,b10,c10,d10){var e10=b10?b10[1]:0;return iI(function(a11){return 0},0,a10,[0,a8(e6,d10,e10)],c10,0,e2,0,vQ,0)}function aC(a10,b10){return l(a10,function(a11){return[0,a11,b10]})}function dw(a10,b10,c10,d10){return function(g10){var i10=[0,[0,cg,function(a11){return a11}],function(a11,b11){var c11=b11[2],d11=a11[2];return[0,az(a11[1],b11[1]),function(a12){return h(c11,h(d11,a12))}]}];function j10(a11){var b11=a11[1],c11=a11[2];function d11(a12){var c12=bM(b11[2]);return h(b11[3],c12)}return[0,J(b11[1]),function(a12){var b12=d11(0);return h(h(c11,a12),b12)}]}var e10=function(a11){return bj(j10,i10,a11)}(bk(d10[2])),f10=[0,82,l(e10,function(a11){var b11=a11[2];return aB(0,u9,function(a12){return h(g10,h(b11,d10[1])),s8(a12)})})],k10=l(e10,function(a11){return a11[1]}),m10=uI([0,f10,0],function(a11){return lU(f10,a11)},c10);return t3(a10,b10,[0,m10],0,[0,[0,83,bk(k10)],0])}}function iJ(a10,b10){return a10?h(C(vR),b10):b10}function vS(a10,b10,c10,d10){var e10=a10?a10[1]:1,f10=b10?b10[1]:0,g10=c10?c10[1]:0;return function(a11){var b11=iJ(1,d10[1]),h10=iJ(0,d10[1]),c11=e10?iG(b11,d10[2]):am(d10[2]),i10=d10[3];im(0,[0,[0,[0,80,h8(H(b11))],0]],0,0,i10);var j10=[0,80,h10],k10=function(a12){return a8(e5,vT,a12)}(function(a12){return a8(h6,j10,a12)}(a8(e4,[0,80,b11],f10))),m10=[0,[0,80,aB(0,e2,function(a12){return ac(c11,aA(e1(a12)[dE]))})],g10];return[0,t5(0,[0,k10],[0,m10],0,[0,[0,83,bk(eV(function(a12){var b12=a12[1],d11=a12[2],e11=au([0,80,[1,tl(H(b12))]]),f11=ds([0,82,l(c11,function(a13){return[1,td(t_(a13,b12),tj)]})],e11);return t4(0,[0,f11],0,0,[0,[0,80,bo(0,d11)],0])},a11))],0]),,c11]}}function iK(a10,b10,c10,d10,e10,f10,g10){var m10=b10?b10[1]:0,n10=c10?c10[1]:function(a11){},j10=h(uC(vU),d10);function k10(a11){return a11?[0,e10]:0}a:{if(a10&&a10[1]){var o10=iG(j10,k10(g10)),i10=o10;break a}var i10=am(k10(g10))}var p10=im(0,[0,[0,[0,80,h8(H(j10))],0]],0,0,f10),q10=[0,80,d10],r10=function(a11){return a8(e5,vV,a11)}(function(a11){return a8(h6,q10,a11)}(a8(e4,[0,80,j10],0))),s10=[0,[0,82,l(i10,function(a11){return a11?tg:di})],r10];return[0,R(0,0,0,0,[0,[0,82,il(0,[0,s10],[0,[0,[0,80,aB(0,e2,function(a11){var b11=k10(e1(a11)[jo]|0);return h(n10,b11),ac(i10,b11)})],m10]],0,0)],[0,[0,82,p10],0]]),i10]}function vW(a10){var d10=ef(a10);return[0,,function(a11){return uY(a11[1])},function(a11){},,function(a11,b10,c10){var e10=d10[4].call(null,b10,c10,a11[2]);return[0,iv(b10,a11[1]),e10]},function(a11){var c10=uW(a11[1]);if(!c10)return[0,a11,0];var e10=c10[1],b10=e10[2],f10=e10[1],g10=[0,[0,b10,d10[28].call(null,b10,a11[2])]];return[0,[0,f10,d10[7].call(null,b10,a11[2])],g10]},function(a11,b10){return d10[29].call(null,b10,a11[2])}]}function vX(a10){var b10=vW(a10);return[0,function(a11){b10[3].call(null,0),b10[3].call(null,0)}]}function vZ(a10){return bj(function(a11){return J(R(0,0,0,0,a11[3]))},aQ,a10)}function v0(a10){return c4(bj(function(a11){return a11[2]},[0,v4,function(a11,b10){return i(C(v3),a11,b10)}],a10),function(a11){return i(C(v2),v1,a11)})}iz(0)(v8);function vY(a10,b10,c10){return[0,a10,b10,c10]}function v5(a10){return v0(a10[1][1])}function v6(a10){var b10=iy(a10[2]),c10=[0,[0,80,aS(jn)],0],d10=[0,[0,80,aS("lwdui-lazy-table-header")],c10],e10=[0,[0,80,dj(H(h(C(v7),b10)))],d10];return R(0,[0,e10],0,0,[0,[0,83,bk(vZ(a10[1][1]))],0])}var v9=vX([0,uD]),dx=k.yjs;function v_(d10,b10,c10){return function(a10){var r10=a10[3],s10=a10[2],f10=iA(0),g10=iA(0),k10=iy(d10[2]),u10=h(C(wa),k10),v10=cf(function(a11,b12){return J([0,eI(a11),a11,r10])},aQ,s10);eu(0,2048),function(a11){return v9[1].call(null,50)}(0);var e10=am(0),m10=Q(function(a11){return a11}),b11=eE(0,qS(m10,e10));eF(b11,function(a11){var c11=bO(b11);return c11[2]?h(c11[1],0):0}),bO(b11);function t10(a11){return i(C(v$),k10,a11)}function j10(a11){var b12=[0,aS("row_spacer"),0];return ib(0,[0,[0,dj(H(t10(a11))),b12]],0)}var w10=l(bj(function(a11){var b12=a11[1],c11=a11[3],d11=a11[2],e11=a8(ck,wb,0),f11=[0,80,dj(H(u10))];return b12?[0,0,J(R(0,[0,[0,f11,e11]],0,0,[0,[0,83,bk(i(c11,d11,b12[1]))],0])),0]:[0,1,cg,0]},[0,[0,0,cg,0],function(a11,b12){var f11=b12[3],g11=b12[2],c11=b12[1],d11=a11[3],e11=a11[2],h10=a11[1],k11=hI(e11),i10=hI(g11);if(typeof k11=="number")return typeof i10=="number"?[0,((h10+d11|0)+c11|0)+f11|0,e11,0]:[0,(h10+d11|0)+c11|0,g11,f11];if(typeof i10=="number")return[0,h10,e11,(d11+c11|0)+f11|0];var l10=dr(d11+c11|0,0)?function(a12){return az(e11,a12)}(az(J(Q(j10(d11+c11|0))),g11)):az(e11,g11);return[0,h10,l10,f11]}],v10),function(a11){var b12=a11[3],c11=a11[2],d11=a11[1],e11=dr(d11,0)?az(J(Q(j10(d11))),c11):c11;return dr(b12,0)?az(e11,J(Q(j10(b12)))):e11}),x10=v6(d10),y10=u8(function(a11,b12){var d11=lV(a11);u2(d11);var c11=uZ(u1(d11)),f11=bM(e10);return f11?t7(f11[1],c11)?ac(e10,[0,c11]):0:ac(e10,[0,c11])}),z10=au(wc),n10=R(0,[0,z10],0,[0,function(a11){return iB(f10,a11)}],[0,[0,83,bk(w10)],0]),o10=au(wd),p10=[0,[0,82,l(m10,function(c11){return aB(0,s$,function(a11){var d11=[0,0],b12=[0,-1];function e11(e12){var a12=800,f11=tI(tJ);t8(b12[1],0)&&tM(b12[1]),b12[1]=tL(a12,function(a13){return h(c11,e12)});var g11=t9(f11-d11[1],a12);return g11&&(d11[1]=f11,h(c11,e12))}return iC(g10),function(a12){return e11(a12)}(0),0})})],0];function q10(a11){return iB(g10,a11)}var A2=c10?vJ([0,o10],[0,p10],[0,q10],l(c10[1],function(a11){var b12=iC(f10),c11=d10[2];return[0,[0,cC(a11,uF(iz([0,b12])(c11)))]]}),n10):R(0,[0,o10],[0,p10],[0,q10],[0,[0,82,n10],0]);function B2(a11){return u7(y10,0,a11)}function D2(a11){return u$(B2,a11)}var E2=function(a11){return l(a11,D2)}(A2),F2=vC(0,vD(we));return R(0,[0,[0,[0,82,l(v5(d10),function(a11){return dj(H(a11))})],F2]],0,0,[0,[0,82,x10],[0,[0,82,E2],0]])}}var fg=ef([0,ed]),fh=dx.Text,fi=dx[jX],fj=dx.Map,bU=ho(wj,wi),a9=ho(wl,wk);function wf(a10,b10){return[0,a10,b10]}function iL(a10){return bS(a10,fi)?[0,aW,a10]:bS(a10,fj)?[0,v,a10]:bS(a10,fh)?[0,bv,a10]:[0,T,a10]}function wm(a10){var b10=eY(a10,wn);if(b10)return[0,b10[1]];var c10=eY(a10,wo);if(c10)return[1,hZ(iL,c10[1])];var d10=eY(a10,wp);if(d10)return[2,d10[1]];throw g([0,f,wq],1)}hq(wr,bU,[0,function(a10){return new fi},function(a10,b10,c10){return a10.insert(b10,h0(function(a11){var b11=a11[1];return bv<=b11?(aW<=b11,a11[2]):(v<=b11,a11[2])},c10)),0},function(a10,b10,c10){return a10.delete(b10,c10),0},function(a10,b10){return a10.push(h0(function(a11){var b11=a11[1];return bv<=b11?(aW<=b11,a11[2]):(v<=b11,a11[2])},b10)),0},function(a10,d10){return a10.forEach(function(a11,b10,c10){return x(d10,b10,iL(a11),c10)}),0},function(a10,b10){function c10(a11){return h(b10,wf(wm,a11))}return a10.observe(c10),c10}]);function fk(a10){return bS(a10,fi)?[0,aW,a10]:bS(a10,fj)?[0,v,a10]:bS(a10,fh)?[0,bv,a10]:[0,T,a10]}function iM(a10,b10){return function(a11){return dg(fk,a11)}(a10.get(A(b10)))}function ws(a10){return a10}function wt(a10){return a10[fy]}function wu(a10){var b10=aA(a10.action);if(b10!=="add")if(b10!==jI){if(b10!=="update")throw g([0,cH,h(C(wv),b10)],1);var c10=1}else var c10=2;else var c10=0;var d10=a10.oldValue,e10=bR(d10)?0:[0,fk(d10)];return[0,c10,0,e10]}function iN(a10){return s4(a10.entries())}hq(ww,a9,[0,function(a10){return new fj},[0,function(d10){var a10=d10[jP].keys.entries();return h1(aA,wu,function(a11,b10,c10){var e10=iM(wt(d10),a11);return fg[4].call(null,a11,[0,b10[1],e10,b10[3]],c10)},a10,fg[1])}],iM,function(a10,b10,c10){var d10=c10[1],e10=bv<=d10?(aW<=d10,c10[2]):(v<=d10,c10[2]);return a10.set(A(b10),e10),0},function(a10,b10){return a10.delete(A(b10)),0},iN,function(a10,d10,c10){return h1(aA,fk,function(a11,b10,c11){return x(d10,a11,b10,c11)},iN(a10),c10)},function(a10,b10){function c10(a11){return h(b10,a11)}return a10.observe(c10),c10}]);var wx=dx.Doc;function iO(a10,b10){return a10.getArray(A(b10))}function bq(a10,b10){return a10.transact(by(1,b10)),0}function iP(a10){return a10}var ai=a9[4],aT=a9[3],cl=a9[1],dy=bU[5],fl=bU[4],iQ=bU[3],iR=bU[1];function wg(a10){var b10=a10[1];return[0,function(a11){return hZ(b10,a11)}(a10[2][jP].delta)]}function wh(a10,b10){var c10=a10?[0,A(a10[1])]:[0];return z1(fh,c10)}function wy(a10){return new wx}var wz=a9[8],wA=a9[7],wB=a9[5],wC=a9[2][1],wD=bU[6];function wE(a10){return a10}var wF=k.IndexeddbPersistence;function wG(a10,b10){var c10=b10;new wF(A(a10),c10)}var wH=k.WebrtcProvider;function wI(a10,b10,c10){var e10=d_(function(a11){return[0,wJ,e0(A,a11)]},b10),d10=[0,[0,wM,{config:{iceServers:e0(function(a11){return a11},cM(function(a11){return{urls:A(h(C(wL),a11))}},wK))}}]];ah([0,d10,0]);var f10=lc(ee(gC(function(a11){return a11})([0,e10,[0,d10,0]]))),g10=c10;return new wH(A(a10),g10,f10)}var iS=k.Quill,wN=k.QuillCursors;function wP(a10){switch(a10){case 0:var b10=wQ;break;case 1:var b10=wR;break;case 2:var b10=wS;break;case 3:var b10=wT;break;default:var b10=wU}return A(b10)}function wO(a10,b10){iS.register(A(a10),b10)}function wV(a10,b10,c10,d10){var e10=a10?a10[1]:0,f10=e10?wW:wZ,g10=d_(function(a11){return[0,wX,!!a11]},b10),h10=[0,g10,[0,d_(function(a11){return[0,wY,e0(wP,a11[1])]},c10),0]],i10=lc(ee(gC(function(a11){return a11})(h10)));return{theme:A(f10),modules:i10}}function w0(a10,b10){return new iS(a10,b10)}function w1(a10){return a10}var w2=k.QuillBinding;function w3(a10,b10){var c10=b10;new w2(a10,c10)}function w4(a10,b10,c10){return x(eq2(t,w5),b10,c10,a10)}function iT(a10,b10,c10){var d10=0<=c10?1:0;if(d10)var e10=0<=b10?1:0,f10=e10&&((b10+c10|0)<=a10?1:0);else var f10=d10;var g10=1-f10;return g10&&w4(a10,b10,c10)}var w6=[0];function w7(a10,b10,c10,d10){var e10=ap(a10,b10);return cP(c10,0,e10,0,d10),e10}function iU(a10,b10){return b10<=a10?a10:b10}function iV(a10){return eq2(t,a10)}function w8(a10,b10){var c10=a10[1];return i(iV(w9),b10,c10)}function w_(a10,b10){return i(iV(w$),a10,b10.length-1)}function cm(a10,b10){var c10=1-(a10<=b10.length-1?1:0);return c10&&w_(a10,b10)}function iW(a10){return[0,0,0,w6]}function cn(a10){return a10[1]}function xa(a10,b10){return a10[3][1+b10]}function iX(a10){var b10=a10[1],c10=a10[3];if(cm(b10,c10),0>>4|0));var f11=b11+1|0;function i11(a11,b12,c12){a0(a11,b12,c12)}return function(a11){return i11(d11,f11,a11)}(h10(g10,c11&15))}for(;!(4<=d10[1]);){var n10=y(b10,d10[1]);f10(e10,c10[1],n10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(6<=d10[1]);){var m10=y(b10,d10[1]);f10(e10,c10[1],m10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(8<=d10[1]);){var l10=y(b10,d10[1]);f10(e10,c10[1],l10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;!(10<=d10[1]);){var k10=y(b10,d10[1]);f10(e10,c10[1],k10),c10[1]=c10[1]+2|0,d10[1]++}for(c10[1]++;;){if(16<=d10[1])return $(e10);var j10=y(b10,d10[1]);f10(e10,c10[1],j10),c10[1]=c10[1]+2|0,d10[1]++}}var xn=gX(0),an=wy(0);wO(xp,wN);var dz=wI(xr,xq,an);wG(xs,an),dn.yjsdoc=an,dn.yjsprovider=dz,dz.on(A(xu),by(1,function(a10){return ah(xt)})),dz.on(A(xw),by(1,function(a10){return ah([0,xv,[0,a10,0]])})),dz.on(A(xy),by(1,function(a10){return ah([0,xx,[0,a10,0]])}));function xo(a10){return xk(xn,0)}function xz(a10,b10){var c10=a10?a10[1]:64,d10=hz(0);return[0,d10,eu(0,c10)]}function i0(a10,b10,c10){var e10=g4(a10[2],b10);if(e10)var d10=e10[1];else{var g10=eH(0,a10[1]);g5(a10[2],b10,g10);var d10=g10}var f10=eI(d10);return f10?ac(f10[1][2],[0,c10]):rH(d10,[0,b10,am([0,c10])])}function fn(a10,b10){var c10=g4(a10[2],b10);if(c10)var d10=c10[1];else{var f10=a10[1],e10=eH([0,[0,b10,am(0)]],f10);g5(a10[2],b10,e10);var d10=e10}return cL(eI(d10))[2]}function fo(a10,b10){return l(fn(a10,b10),function(a11){if(!a11)return 0;var b11=a11[1];if(typeof b11!="number"&&T===b11[1])return[0,aA(b11[2])];throw g([0,f,xA],1)})}function xB(a10){var b10=hz(0);return[0,b10,iW(0)]}function xC(a10){try{var c10=[0,iZ(a10[2],0)];return c10}catch(f10){var b10=L(f10);if(b10[1]===cH)return 0;throw g(b10,0)}}function i1(a10,b10){var c10=eH(a10,b10[1]);return xd(b10[2],c10)}function i2(a10,b10,c10,d10){var e10=[0,b10,[0,c10,[0,cn(d10),0]]];e7([0,xD,[0,cn(a10),e10]]);var f10=cn(d10),g10=iZ(a10,0);return fm(d10,gM(c10,function(a11){return g10})),xh(a10,b10,d10,f10,c10)}function xE(i10,b10,c10){var e10=[0,0],j10=i10[2],d10=iW(0);gN(function(a11){switch(a11[0]){case 0:var m10=a11[1];return i2(j10,e10[1],m10,d10),e10[1]=e10[1]+m10|0,0;case 1:var c11=a11[1];if(cn(d10)!==0){var o10=[0,iX(d10)];return fm(d10,gO(function(a12){var d11=h(b10,a12),c12=rD([0,d11],o10[1]);return o10[1]=c12,c12},c11))}var n10=xC(i10);if(!n10)return gN(function(a12){var c12=h(b10,a12);return i1([0,c12],[0,i10[1],d10])},c11);var s10=n10[1];return fm(d10,gO(function(a12){return rB([0,h(b10,a12)],s10)},c11));default:var k11=a11[1],t10=e10[1]===0?sk(i10[1]):hG(iX(d10)),p10=[0,t10],u10=1;if(k11>=1)for(var l10=u10;;){var q10=p10[1];if(!q10)throw g([0,f,xF],1);var r10=q10[1];p10[1]=hG(r10),rK(r10);var v10=l10+1|0;if(k11===l10)break;l10=v10}return e10[1]=e10[1]+k11|0,0}},c10);var k10=e10[1],a10=cn(j10)-k10|0;return 0}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template K,V\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template {Map} MAP\n * @template {MAP extends Map ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n", "/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value ?? undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n", "/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n\n/**\n * @template {ArrayLike} ARR\n * @template {function(ARR extends ArrayLike ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n", "/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n\n/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n/* c8 ignore end */\n", "/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n", "/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n", "import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n", "/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * \u2022 Transforms data to a binary format (not to a string)\n * \u2022 Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * \u2022 Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) \u21D2 RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n", "/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n", "/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n", "/* eslint-env browser */\n\nexport const subtle = crypto.subtle\nexport const getRandomValues = crypto.getRandomValues.bind(crypto)\n", "/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\nimport { getRandomValues } from 'lib0/webcrypto'\n\nexport const rand = Math.random\n\nexport const uint32 = () => getRandomValues(new Uint32Array(1))[0]\n\nexport const uint53 = () => {\n const arr = getRandomValues(new Uint32Array(8))\n return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0)\n}\n\n/**\n * @template T\n * @param {Array} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\n\n/**\n * @return {string}\n */\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n", "/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10\u03BCs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n", "/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve,function(Error):void):any} f\n * @return {Promise}\n */\nexport const create = f => /** @type {Promise} */ (new Promise(f))\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template {unknown[] | []} PS\n *\n * @param {PS} ps\n * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>}\n */\nexport const all = Promise.all.bind(Promise)\n\n/**\n * @param {Error} [reason]\n * @return {Promise}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @template T\n * @param {T} res\n * @return {Promise}\n */\nexport const resolveWith = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n * @deprecated use untilAsync instead\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* c8 ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {()=>Promise|boolean} check\n * @param {number} timeout\n * @param {number} intervalResolution\n * @return {Promise}\n */\nexport const untilAsync = async (check, timeout = 0, intervalResolution = 10) => {\n const startTime = time.getUnixTime()\n const noTimeout = timeout <= 0\n // eslint-disable-next-line no-unmodified-loop-condition\n while (noTimeout || time.getUnixTime() - startTime <= timeout) {\n if (await check()) return\n await wait(intervalResolution)\n }\n throw new Error('Timeout')\n}\n\n/**\n * @param {number} timeout\n * @return {Promise}\n */\nexport const wait = timeout => create((resolve, _reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n", "/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n", "/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined' && localStorage) {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n", "/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @deprecated use object.size instead\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n", "/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n", "/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module environment\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next 2 */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {string}\n */\n/* c8 ignore next 5 */\nexport const ensureConf = (name) => {\n const c = getConf(name)\n if (c == null) throw new Error(`Expected configuration \"${name.toUpperCase().replaceAll('-', '_')}\"`)\n return c\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\n/**\n * Color is enabled by default if the terminal supports it.\n *\n * Explicitly enable color using `--color` parameter\n * Disable color using `--no-color` parameter or using `NO_COLOR=1` environment variable.\n * `FORCE_COLOR=1` enables color and takes precedence over all.\n */\nexport const supportsColor = forceColor || (\n !hasParam('--no-colors') && // @todo deprecate --no-colors\n !hasConf('no-color') &&\n (!isNode || process.stdout.isTTY) && (\n !isNode ||\n hasParam('--color') ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n )\n)\n/* c8 ignore stop */\n", "/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as array from './array.js'\nimport * as math from './math.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Implements base64url - see https://datatracker.ietf.org/doc/html/rfc4648#section-5\n * @param {Uint8Array} buf\n */\nexport const toBase64UrlEncoded = buf => toBase64(buf).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n\n/**\n * @param {string} base64\n */\nexport const fromBase64UrlEncoded = base64 => fromBase64(base64.replaceAll('-', '+').replaceAll('_', '/'))\n\n/**\n * Base64 is always a more efficient choice. This exists for utility purposes only.\n *\n * @param {Uint8Array} buf\n */\nexport const toHexString = buf => array.map(buf, b => b.toString(16).padStart(2, '0')).join('')\n\n/**\n * Note: This function expects that the hex doesn't start with 0x..\n *\n * @param {string} hex\n */\nexport const fromHexString = hex => {\n const hlen = hex.length\n const buf = new Uint8Array(math.ceil(hlen / 2))\n for (let i = 0; i < hlen; i += 2) {\n buf[buf.length - i / 2 - 1] = Number.parseInt(hex.slice(hlen - i - 2, hlen - i), 16)\n }\n return buf\n}\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data =>\n encoding.encode(encoder => encoding.writeAny(encoder, data))\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n\n/**\n * Shift Byte Array {N} bits to the left. Does not expand byte array.\n *\n * @param {Uint8Array} bs\n * @param {number} N should be in the range of [0-7]\n */\nexport const shiftNBitsLeft = (bs, N) => {\n if (N === 0) return bs\n bs = new Uint8Array(bs)\n bs[0] <<= N\n for (let i = 1; i < bs.length; i++) {\n bs[i - 1] |= bs[i] >>> (8 - N)\n bs[i] <<= N\n }\n return bs\n}\n", "/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array>} arr\n * @param {function(L, R):X} f\n * @return {Array}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n", "/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* c8 ignore start */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\nexport const createTextNode = text => doc.createTextNode(text)\n\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array>} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array|HTMLCollection} children\n * @return {DocumentFragment}\n */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array} nodes\n * @return {Element}\n */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array|pair.Pair>} attrs Array of key-value pairs\n * @param {Array} children\n * @return {Element}\n */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair} pair\n */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array>} pairs\n * @return {string}\n */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map} m\n * @return {string}\n */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf}\n */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nconst _parse = html => domParser.parseFromString(`${html}`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n/* c8 ignore stop */\n", "/**\n * JSON utility functions.\n *\n * @module json\n */\n\n/**\n * Transform JavaScript object to JSON.\n *\n * @param {any} object\n * @return {string}\n */\nexport const stringify = JSON.stringify\n\n/**\n * Parse JSON object.\n *\n * @param {string} json\n * @return {any}\n */\nexport const parse = JSON.parse\n", "/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n", "import * as symbol from './symbol.js'\nimport * as time from './time.js'\nimport * as env from './environment.js'\nimport * as func from './function.js'\nimport * as json from './json.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n * @return {Array}\n */\nexport const computeNoColorLoggingArgs = args => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n if (arg === undefined) {\n break\n } else if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else if (arg.constructor === Object) {\n break\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/* c8 ignore start */\n/**\n * @param {function(...any):void} _print\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (_print, moduleName) => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null &&\n (debugRegexVar === '*' || debugRegexVar === 'true' ||\n new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n return !doLogging\n ? func.nop\n : (...args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = args[0]()\n }\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n _print(\n color,\n moduleName,\n UNCOLOR,\n ...args.map((arg) => {\n if (arg != null && arg.constructor === Uint8Array) {\n arg = Array.from(arg)\n }\n const t = typeof arg\n switch (t) {\n case 'string':\n case 'symbol':\n return arg\n default: {\n return json.stringify(arg)\n }\n }\n }),\n color,\n ' +' + timeDiff + 'ms'\n )\n }\n}\n/* c8 ignore stop */\n", "/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as set from './set.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as common from './logging.common.js'\n\nexport { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js'\n\n/**\n * @type {Object>}\n */\nconst _browserStyleMap = {\n [common.BOLD]: pair.create('font-weight', 'bold'),\n [common.UNBOLD]: pair.create('font-weight', 'normal'),\n [common.BLUE]: pair.create('color', 'blue'),\n [common.GREEN]: pair.create('color', 'green'),\n [common.GREY]: pair.create('color', 'grey'),\n [common.RED]: pair.create('color', 'red'),\n [common.PURPLE]: pair.create('color', 'purple'),\n [common.ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [common.UNCOLOR]: pair.create('color', 'black')\n}\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst computeBrowserLoggingArgs = (args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n break\n }\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst computeLoggingArgs = env.supportsColor\n ? computeBrowserLoggingArgs\n : common.computeNoColorLoggingArgs\n/* c8 ignore stop */\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.print(args))\n}\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(common.ORANGE)\n vconsoles.forEach((vc) => vc.print(args))\n}\n/* c8 ignore stop */\n\n/**\n * @param {Error} err\n */\n/* c8 ignore start */\nexport const printError = (err) => {\n console.error(err)\n vconsoles.forEach((vc) => vc.printError(err))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\n/* c8 ignore start */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log(\n '%c ',\n `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`\n )\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach((vc) => vc.printImg(url, height))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} base64\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printImgBase64 = (base64, height) =>\n printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.group(args))\n}\n\n/**\n * @param {Array} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupEnd())\n}\n\n/**\n * @param {function():Node} createNode\n */\n/* c8 ignore next 2 */\nexport const printDom = (createNode) =>\n vconsoles.forEach((vc) => vc.printDom(createNode()))\n\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printCanvas = (canvas, height) =>\n printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = set.create()\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst _computeLineSpans = (args) => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n let arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n arg = 'undefined '\n }\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [\n pair.create('style', dom.mapToStyleString(currentStyle))\n ], [dom.text(arg.toString())])\n if (span.innerHTML === '') {\n span.innerHTML = ' '\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(\n dom.element('span', [], [dom.text(/** @type {string} */ (content))])\n )\n }\n }\n return spans\n}\n/* c8 ignore stop */\n\nconst lineStyle =\n 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* c8 ignore start */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [\n pair.create('hidden', collapsed),\n pair.create('style', 'color:grey;font-size:120%;')\n ], [dom.text('\u25BC')])\n const triangleRight = dom.element('span', [\n pair.create('hidden', !collapsed),\n pair.create('style', 'color:grey;font-size:125%;')\n ], [dom.text('\u25B6')])\n const content = dom.element(\n 'div',\n [pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )],\n [triangleDown, triangleRight, dom.text(' ')].concat(\n _computeLineSpans(args)\n )\n )\n const nextContainer = dom.element('div', [\n pair.create('hidden', collapsed)\n ])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', (_event) => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('div', [\n pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )\n ], _computeLineSpans(args))\n ])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([common.RED, common.BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('img', [\n pair.create('src', url),\n pair.create('height', `${math.round(height * 1.5)}px`)\n ])\n ])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n/* c8 ignore stop */\n\n/**\n * @param {Element} dom\n */\n/* c8 ignore next */\nexport const createVConsole = (dom) => new VConsole(dom)\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName)\n", "/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator} iterator\n * @param {function(T):R} f\n * @return {IterableIterator}\n */\nexport const mapIterator = (iterator, f) => ({\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult} next\n * @return {IterableIterator}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n", "import { ObservableV2 } from 'lib0/observable'\n\nimport {\n Doc // eslint-disable-line\n} from '../internals.js'\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {ObservableV2}\n */\nexport class AbstractConnector extends ObservableV2 {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super()\n this.doc = ydoc\n this.awareness = awareness\n }\n}\n", "import {\n findIndexSS,\n getState,\n splitItem,\n iterateStructs,\n UpdateEncoderV2,\n DSDecoderV1, DSEncoderV1, DSDecoderV2, DSEncoderV2, Item, GC, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as array from 'lib0/array'\nimport * as math from 'lib0/math'\nimport * as map from 'lib0/map'\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\n\nexport class DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock\n /**\n * @type {number}\n */\n this.len = len\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nexport class DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid))\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i]\n iterateStructs(transaction, structs, del.clock, del.len, f)\n }\n })\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nexport const findIndexDS = (dis, clock) => {\n let left = 0\n let right = dis.length - 1\n while (left <= right) {\n const midindex = math.floor((left + right) / 2)\n const mid = dis[midindex]\n const midclock = mid.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client)\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n}\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock)\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1]\n const right = dels[i]\n if (left.clock + left.len >= right.clock) {\n left.len = math.max(left.len, right.clock + right.len - left.clock)\n } else {\n if (j < i) {\n dels[j] = right\n }\n j++\n }\n }\n dels.length = j\n })\n}\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nexport const mergeDeleteSets = dss => {\n const merged = new DeleteSet()\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice()\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || [])\n }\n merged.clients.set(client, dels)\n }\n })\n }\n sortAndMergeDeleteSet(merged)\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([])).push(new DeleteItem(clock, length))\n}\n\nexport const createDeleteSet = () => new DeleteSet()\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nexport const createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet()\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = []\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i]\n if (struct.deleted) {\n const clock = struct.id.clock\n let len = struct.length\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {\n len += next.length\n }\n }\n dsitems.push(new DeleteItem(clock, len))\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems)\n }\n })\n return ds\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size)\n\n // Ensure that the delete set is written in a deterministic order\n array.from(ds.clients.entries())\n .sort((a, b) => b[0] - a[0])\n .forEach(([client, dsitems]) => {\n encoder.resetDsCurVal()\n encoding.writeVarUint(encoder.restEncoder, client)\n const len = dsitems.length\n encoding.writeVarUint(encoder.restEncoder, len)\n for (let i = 0; i < len; i++) {\n const item = dsitems[i]\n encoder.writeDsClock(item.clock)\n encoder.writeDsLen(item.len)\n }\n })\n}\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nexport const readDeleteSet = decoder => {\n const ds = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([]))\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()))\n }\n }\n }\n return ds\n}\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {Uint8Array|null} Returns a v2 update containing all deletes that couldn't be applied yet; or null if all deletes were applied successfully.\n *\n * @private\n * @function\n */\nexport const readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n const structs = store.clients.get(client) || []\n const state = getState(store, client)\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock()\n const clockEnd = clock + decoder.readDsLen()\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state)\n }\n let index = findIndexSS(structs, clock)\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index]\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n index++ // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++]\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock))\n }\n struct.delete(transaction)\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock)\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n const ds = new UpdateEncoderV2()\n encoding.writeVarUint(ds.restEncoder, 0) // encode 0 structs\n writeDeleteSet(ds, unappliedDS)\n return ds.toUint8Array()\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds1\n * @param {DeleteSet} ds2\n */\nexport const equalDeleteSets = (ds1, ds2) => {\n if (ds1.clients.size !== ds2.clients.size) return false\n for (const [client, deleteItems1] of ds1.clients.entries()) {\n const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client))\n if (deleteItems2 === undefined || deleteItems1.length !== deleteItems2.length) return false\n for (let i = 0; i < deleteItems1.length; i++) {\n const di1 = deleteItems1[i]\n const di2 = deleteItems2[i]\n if (di1.clock !== di2.clock || di1.len !== di2.len) {\n return false\n }\n }\n }\n return true\n}\n", "/**\n * @module Y\n */\n\nimport {\n StructStore,\n AbstractType,\n YArray,\n YText,\n YMap,\n YXmlElement,\n YXmlFragment,\n transact,\n ContentDoc, Item, Transaction, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport { ObservableV2 } from 'lib0/observable'\nimport * as random from 'lib0/random'\nimport * as map from 'lib0/map'\nimport * as array from 'lib0/array'\nimport * as promise from 'lib0/promise'\n\nexport const generateNewClientId = random.uint32\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {string | null} [DocOpts.collectionid] Associate this document with a collection. This only plays a role if your provider has a concept of collection.\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n * @property {boolean} [DocOpts.shouldLoad] Whether the document should be synced by the provider now. This is toggled to true when you call ydoc.load()\n */\n\n/**\n * @typedef {Object} DocEvents\n * @property {function(Doc):void} DocEvents.destroy\n * @property {function(Doc):void} DocEvents.load\n * @property {function(boolean, Doc):void} DocEvents.sync\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.update\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.updateV2\n * @property {function(Doc):void} DocEvents.beforeAllTransactions\n * @property {function(Transaction, Doc):void} DocEvents.beforeTransaction\n * @property {function(Transaction, Doc):void} DocEvents.beforeObserverCalls\n * @property {function(Transaction, Doc):void} DocEvents.afterTransaction\n * @property {function(Transaction, Doc):void} DocEvents.afterTransactionCleanup\n * @property {function(Doc, Array):void} DocEvents.afterAllTransactions\n * @property {function({ loaded: Set, added: Set, removed: Set }, Doc, Transaction):void} DocEvents.subdocs\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends ObservableV2\n */\nexport class Doc extends ObservableV2 {\n /**\n * @param {DocOpts} opts configuration\n */\n constructor ({ guid = random.uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {\n super()\n this.gc = gc\n this.gcFilter = gcFilter\n this.clientID = generateNewClientId()\n this.guid = guid\n this.collectionid = collectionid\n /**\n * @type {Map>>}\n */\n this.share = new Map()\n this.store = new StructStore()\n /**\n * @type {Transaction | null}\n */\n this._transaction = null\n /**\n * @type {Array}\n */\n this._transactionCleanups = []\n /**\n * @type {Set}\n */\n this.subdocs = new Set()\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null\n this.shouldLoad = shouldLoad\n this.autoLoad = autoLoad\n this.meta = meta\n /**\n * This is set to true when the persistence provider loaded the document from the database or when the `sync` event fires.\n * Note that not all providers implement this feature. Provider authors are encouraged to fire the `load` event when the doc content is loaded from the database.\n *\n * @type {boolean}\n */\n this.isLoaded = false\n /**\n * This is set to true when the connection provider has successfully synced with a backend.\n * Note that when using peer-to-peer providers this event may not provide very useful.\n * Also note that not all providers implement this feature. Provider authors are encouraged to fire\n * the `sync` event when the doc has been synced (with `true` as a parameter) or if connection is\n * lost (with false as a parameter).\n */\n this.isSynced = false\n this.isDestroyed = false\n /**\n * Promise that resolves once the document has been loaded from a presistence provider.\n */\n this.whenLoaded = promise.create(resolve => {\n this.on('load', () => {\n this.isLoaded = true\n resolve(this)\n })\n })\n const provideSyncedPromise = () => promise.create(resolve => {\n /**\n * @param {boolean} isSynced\n */\n const eventHandler = (isSynced) => {\n if (isSynced === undefined || isSynced === true) {\n this.off('sync', eventHandler)\n resolve()\n }\n }\n this.on('sync', eventHandler)\n })\n this.on('sync', isSynced => {\n if (isSynced === false && this.isSynced) {\n this.whenSynced = provideSyncedPromise()\n }\n this.isSynced = isSynced === undefined || isSynced === true\n if (this.isSynced && !this.isLoaded) {\n this.emit('load', [this])\n }\n })\n /**\n * Promise that resolves once the document has been synced with a backend.\n * This promise is recreated when the connection is lost.\n * Note the documentation about the `isSynced` property.\n */\n this.whenSynced = provideSyncedPromise()\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this)\n }, null, true)\n }\n this.shouldLoad = true\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @template T\n * @param {function(Transaction):T} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n * @return T\n *\n * @public\n */\n transact (f, origin = null) {\n return transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`\n *\n * After this method is called, the type is also available on `ydoc.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Y.Doc instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @template {typeof AbstractType} Type\n * @example\n * const ydoc = new Y.Doc(..)\n * const appState = {\n * document: ydoc.getText('document')\n * comments: ydoc.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {InstanceType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = /** @type {any} */ (AbstractType)) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor()\n t._integrate(this, null)\n return t\n })\n const Constr = type.constructor\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor()\n t._map = type._map\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t\n }\n })\n t._start = type._start\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t\n }\n t._length = type._length\n this.share.set(name, t)\n t._integrate(this, null)\n return /** @type {InstanceType} */ (t)\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return /** @type {InstanceType} */ (type)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n return /** @type {YArray} */ (this.get(name, YArray))\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n return this.get(name, YText)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n return /** @type {YMap} */ (this.get(name, YMap))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlElement}\n *\n * @public\n */\n getXmlElement (name = '') {\n return /** @type {YXmlElement<{[key:string]:string}>} */ (this.get(name, YXmlElement))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n * Doesn't log types that have not been defined (using ydoc.getType(..)).\n *\n * @deprecated Do not use this method and rather call toJSON directly on the shared types.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {}\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON()\n })\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n this.isDestroyed = true\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy())\n const item = this._item\n if (item !== null) {\n this._item = null\n const content = /** @type {ContentDoc} */ (item.content)\n content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false })\n content.doc._item = item\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n const doc = content.doc\n if (!item.deleted) {\n transaction.subdocsAdded.add(doc)\n }\n transaction.subdocsRemoved.add(this)\n }, null, true)\n }\n // @ts-ignore\n this.emit('destroyed', [true]) // DEPRECATED!\n this.emit('destroy', [this])\n super.destroy()\n }\n}\n", "import * as buffer from 'lib0/buffer'\nimport * as decoding from 'lib0/decoding'\nimport {\n ID, createID\n} from '../internals.js'\n\nexport class DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nexport class UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nexport class DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n /**\n * @private\n */\n this.dsCurrVal = 0\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder)\n return this.dsCurrVal\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1\n this.dsCurrVal += diff\n return diff\n }\n}\n\nexport class UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder)\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = []\n decoding.readVarUint(decoder) // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder))\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read()\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read()\n this.keys.push(key)\n return key\n }\n }\n}\n", "import * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nimport {\n ID // eslint-disable-line\n} from '../internals.js'\n\nexport class DSEncoderV1 {\n constructor () {\n this.restEncoder = encoding.createEncoder()\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n}\n\nexport class UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed))\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key)\n }\n}\n\nexport class DSEncoderV2 {\n constructor () {\n this.restEncoder = encoding.createEncoder() // encodes all the rest / non-optimized\n this.dsCurrVal = 0\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal\n this.dsCurrVal = clock\n encoding.writeVarUint(this.restEncoder, diff)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase()\n }\n encoding.writeVarUint(this.restEncoder, len - 1)\n this.dsCurrVal += len\n }\n}\n\nexport class UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super()\n /**\n * @type {Map}\n */\n this.keyMap = new Map()\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.clientEncoder = new encoding.UintOptRleEncoder()\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.stringEncoder = new encoding.StringEncoder()\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.typeRefEncoder = new encoding.UintOptRleEncoder()\n this.lenEncoder = new encoding.UintOptRleEncoder()\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, 0) // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder))\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder))\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array())\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder))\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client)\n this.leftClockEncoder.write(id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client)\n this.rightClockEncoder.write(id.clock)\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed)\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key)\n if (clock === undefined) {\n /**\n * @todo uncomment to introduce this feature finally\n *\n * Background. The ContentFormat object was always encoded using writeKey, but the decoder used to use readString.\n * Furthermore, I forgot to set the keyclock. So everything was working fine.\n *\n * However, this feature here is basically useless as it is not being used (it actually only consumes extra memory).\n *\n * I don't know yet how to reintroduce this feature..\n *\n * Older clients won't be able to read updates when we reintroduce this feature. So this should probably be done using a flag.\n *\n */\n // this.keyMap.set(key, this.keyClock)\n this.keyClockEncoder.write(this.keyClock++)\n this.stringEncoder.write(key)\n } else {\n this.keyClockEncoder.write(clock)\n }\n }\n}\n", "/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\nimport {\n findIndexSS,\n getState,\n createID,\n getStateVector,\n readAndApplyDeleteSet,\n writeDeleteSet,\n createDeleteSetFromStructStore,\n transact,\n readItemContent,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n DSEncoderV2,\n DSDecoderV1,\n DSEncoderV1,\n mergeUpdates,\n mergeUpdatesV2,\n Skip,\n diffUpdateV2,\n convertUpdateFormatV2ToV1,\n DSDecoderV2, Doc, Transaction, GC, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as binary from 'lib0/binary'\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as array from 'lib0/array'\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n clock = math.max(clock, structs[0].id.clock) // make sure the first id exists\n const startNewStructs = findIndexSS(structs, clock)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs)\n encoder.writeClient(client)\n encoding.writeVarUint(encoder.restEncoder, clock)\n const firstStruct = structs[startNewStructs]\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock)\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0)\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nexport const writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map()\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock)\n }\n })\n getStateVector(store).forEach((_clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0)\n }\n })\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size)\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n writeStructs(encoder, /** @type {Array} */ (store.clients.get(client)), client, clock)\n })\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder The decoder object to read data from.\n * @param {Doc} doc\n * @return {Map }>}\n *\n * @private\n * @function\n */\nexport const readClientsStructRefs = (decoder, doc) => {\n /**\n * @type {Map }>}\n */\n const clientRefs = map.create()\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n // const start = performance.now()\n clientRefs.set(client, { i: 0, refs })\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n switch (binary.BITS5 & info) {\n case 0: { // GC\n const len = decoder.readLen()\n refs[i] = new GC(createID(client, clock), len)\n clock += len\n break\n }\n case 10: { // Skip Struct (nothing to apply)\n // @todo we could reduce the amount of checks by adding Skip struct to clientRefs so we know that something is missing.\n const len = decoding.readVarUint(decoder.restDecoder)\n refs[i] = new Skip(createID(client, clock), len)\n clock += len\n break\n }\n default: { // Item with content\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // left\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct\n clock += struct.length\n }\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n}\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {Map} clientsStructRefs\n * @return { null | { update: Uint8Array, missing: Map } }\n *\n * @private\n * @function\n */\nconst integrateStructs = (transaction, store, clientsStructRefs) => {\n /**\n * @type {Array}\n */\n const stack = []\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n let clientsStructRefsIds = array.from(clientsStructRefs.keys()).sort((a, b) => a - b)\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n const getNextStructTarget = () => {\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop()\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n } else {\n return null\n }\n }\n return nextStructsTarget\n }\n let curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n return null\n }\n\n /**\n * @type {StructStore}\n */\n const restStructs = new StructStore()\n const missingSV = new Map()\n /**\n * @param {number} client\n * @param {number} clock\n */\n const updateMissingSv = (client, clock) => {\n const mclock = missingSV.get(client)\n if (mclock == null || mclock > clock) {\n missingSV.set(client, clock)\n }\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]\n // caching the state because it is used very often\n const state = new Map()\n\n const addStackToRestSS = () => {\n for (const item of stack) {\n const client = item.id.client\n const unapplicableItems = clientsStructRefs.get(client)\n if (unapplicableItems) {\n // decrement because we weren't able to apply previous operation\n unapplicableItems.i--\n restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i))\n clientsStructRefs.delete(client)\n unapplicableItems.i = 0\n unapplicableItems.refs = []\n } else {\n // item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue\n restStructs.clients.set(client, [item])\n }\n // remove client from clientsStructRefsIds to prevent users from applying the same update again\n clientsStructRefsIds = clientsStructRefsIds.filter(c => c !== client)\n }\n stack.length = 0\n }\n\n // iterate over all struct readers until we are done\n while (true) {\n if (stackHead.constructor !== Skip) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client))\n const offset = localClock - stackHead.id.clock\n if (offset < 0) {\n // update from the same client is missing\n stack.push(stackHead)\n updateMissingSv(stackHead.id.client, stackHead.id.clock - 1)\n // hid a dead wall, add all items from stack to restSS\n addStackToRestSS()\n } else {\n const missing = stackHead.getMissing(transaction, store)\n if (missing !== null) {\n stack.push(stackHead)\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(/** @type {number} */ (missing)) || { refs: [], i: 0 }\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message that doesn't exist yet\n updateMissingSv(/** @type {number} */ (missing), getState(store, missing))\n addStackToRestSS()\n } else {\n stackHead = structRefs.refs[structRefs.i++]\n continue\n }\n } else if (offset === 0 || offset < stackHead.length) {\n // all fine, apply the stackhead\n stackHead.integrate(transaction, offset)\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length)\n }\n }\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop())\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n } else {\n curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n }\n }\n }\n if (restStructs.clients.size > 0) {\n const encoder = new UpdateEncoderV2()\n writeClientsStructs(encoder, restStructs, new Map())\n // write empty deleteset\n // writeDeleteSet(encoder, new DeleteSet())\n encoding.writeVarUint(encoder.restEncoder, 0) // => no need for an extra function call, just write 0 deletes\n return { missing: missingSV, update: encoder.toUint8Array() }\n }\n return null\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {UpdateDecoderV1 | UpdateDecoderV2} [structDecoder]\n *\n * @function\n */\nexport const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n // force that transaction.local is set to non-local\n transaction.local = false\n let retry = false\n const doc = transaction.doc\n const store = doc.store\n // let start = performance.now()\n const ss = readClientsStructRefs(structDecoder, doc)\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const restStructs = integrateStructs(transaction, store, ss)\n const pending = store.pendingStructs\n if (pending) {\n // check if we can apply something\n for (const [client, clock] of pending.missing) {\n if (clock < getState(store, client)) {\n retry = true\n break\n }\n }\n if (restStructs) {\n // merge restStructs into store.pending\n for (const [client, clock] of restStructs.missing) {\n const mclock = pending.missing.get(client)\n if (mclock == null || mclock > clock) {\n pending.missing.set(client, clock)\n }\n }\n pending.update = mergeUpdatesV2([pending.update, restStructs.update])\n }\n } else {\n store.pendingStructs = restStructs\n }\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store)\n if (store.pendingDs) {\n // @todo we could make a lower-bound state-vector check as we do above\n const pendingDSUpdate = new UpdateDecoderV2(decoding.createDecoder(store.pendingDs))\n decoding.readVarUint(pendingDSUpdate.restDecoder) // read 0 structs, because we only encode deletes in pendingdsupdate\n const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store)\n if (dsRest && dsRest2) {\n // case 1: ds1 != null && ds2 != null\n store.pendingDs = mergeUpdatesV2([dsRest, dsRest2])\n } else {\n // case 2: ds1 != null\n // case 3: ds2 != null\n // case 4: ds1 == null && ds2 == null\n store.pendingDs = dsRest || dsRest2\n }\n } else {\n // Either dsRest == null && pendingDs == null OR dsRest != null\n store.pendingDs = dsRest\n }\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n if (retry) {\n const update = /** @type {{update: Uint8Array}} */ (store.pendingStructs).update\n store.pendingStructs = null\n applyUpdateV2(transaction.doc, update)\n }\n }, transactionOrigin, false)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder))\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nexport const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update)\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder))\n}\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1)\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nexport const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector)\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store))\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {UpdateEncoderV1 | UpdateEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {\n const targetStateVector = decodeStateVector(encodedTargetStateVector)\n writeStateAsUpdate(encoder, doc, targetStateVector)\n const updates = [encoder.toUint8Array()]\n // also add the pending updates (if there are any)\n if (doc.store.pendingDs) {\n updates.push(doc.store.pendingDs)\n }\n if (doc.store.pendingStructs) {\n updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector))\n }\n if (updates.length > 1) {\n if (encoder.constructor === UpdateEncoderV1) {\n return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)))\n } else if (encoder.constructor === UpdateEncoderV2) {\n return mergeUpdatesV2(updates)\n }\n }\n return updates[0]\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new UpdateEncoderV1())\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder)\n const clock = decoding.readVarUint(decoder.restDecoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\n// export const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVector = decodedState => readStateVector(new DSDecoderV1(decoding.createDecoder(decodedState)))\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Map} sv\n * @function\n */\nexport const writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size)\n array.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n encoding.writeVarUint(encoder.restEncoder, client) // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock)\n })\n return encoder\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Doc} doc\n *\n * @function\n */\nexport const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store))\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n if (doc instanceof Map) {\n writeStateVector(encoder, doc)\n } else {\n writeDocumentStateVector(encoder, doc)\n }\n return encoder.toUint8Array()\n}\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVector = doc => encodeStateVectorV2(doc, new DSEncoderV1())\n", "import * as f from 'lib0/function'\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nexport class EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = []\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nexport const createEventHandler = () => new EventHandler()\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nexport const addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f)\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nexport const removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l\n const len = l.length\n eventHandler.l = l.filter(g => f !== g)\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.')\n }\n}\n\n/**\n * Removes all event listeners.\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n *\n * @private\n * @function\n */\nexport const removeAllEventHandlerListeners = eventHandler => {\n eventHandler.l.length = 0\n}\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nexport const callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1])\n", "import { AbstractType } from '../internals.js' // eslint-disable-line\n\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as error from 'lib0/error'\n\nexport class ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nexport const createID = (client, clock) => new ID(client, clock)\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nexport const writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client)\n encoding.writeVarUint(encoder, id.clock)\n}\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nexport const readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nexport const findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n}\n", "import { AbstractType, Item } from '../internals.js' // eslint-disable-line\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nexport const isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item\n }\n return false\n}\n", "import {\n AbstractType // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nexport const logType = type => {\n const res = []\n let n = type._start\n while (n) {\n res.push(n)\n n = n.right\n }\n console.log('Children: ', res)\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content))\n}\n", "import {\n YArray,\n YMap,\n readDeleteSet,\n writeDeleteSet,\n createDeleteSet,\n DSEncoderV1, DSDecoderV1, ID, DeleteSet, YArrayEvent, Transaction, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as decoding from 'lib0/decoding'\n\nimport { mergeDeleteSets, isDeleted } from './DeleteSet.js'\n\nexport class PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map()\n this.yusers = storeType\n this.doc = doc\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map()\n this.dss = dss\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds')\n const ids = user.get('ids')\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription)\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]))\n }\n })\n })\n })\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))))\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n )\n ids.forEach(addClientId)\n }\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n )\n })\n // add intial data\n storeType.forEach(initUser)\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} conf\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers\n let user = users.get(userDescription)\n if (!user) {\n user = new YMap()\n user.set('ids', new YArray())\n user.set('ds', new YArray())\n users.set(userDescription, user)\n }\n user.get('ids').push([clientid])\n users.observe(_event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription)\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid])\n }\n })\n const encoder = new DSEncoderV1()\n const ds = this.dss.get(userDescription)\n if (ds) {\n writeDeleteSet(encoder, ds)\n user.get('ds').push([encoder.toUint8Array()])\n }\n }\n }, 0)\n })\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds')\n const ds = transaction.deleteSet\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1()\n writeDeleteSet(encoder, ds)\n yds.push([encoder.toUint8Array()])\n }\n })\n })\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n", "import {\n writeID,\n readID,\n compareIDs,\n getState,\n findRootTypeKey,\n Item,\n createID,\n ContentType,\n followRedone,\n getItem,\n ID, Doc, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as error from 'lib0/error'\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nexport class RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n * @param {number} assoc\n */\n constructor (type, tname, item, assoc = 0) {\n /**\n * @type {ID|null}\n */\n this.type = type\n /**\n * @type {string|null}\n */\n this.tname = tname\n /**\n * @type {ID | null}\n */\n this.item = item\n /**\n * A relative position is associated to a specific character. By default\n * assoc >= 0, the relative position is associated to the character\n * after the meant position.\n * I.e. position 1 in 'ab' is associated to character 'b'.\n *\n * If assoc < 0, then the relative position is associated to the caharacter\n * before the meant position.\n *\n * @type {number}\n */\n this.assoc = assoc\n }\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {any}\n */\nexport const relativePositionToJSON = rpos => {\n const json = {}\n if (rpos.type) {\n json.type = rpos.type\n }\n if (rpos.tname) {\n json.tname = rpos.tname\n }\n if (rpos.item) {\n json.item = rpos.item\n }\n if (rpos.assoc != null) {\n json.assoc = rpos.assoc\n }\n return json\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc)\n\nexport class AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n */\n constructor (type, index, assoc = 0) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n /**\n * @type {number}\n */\n this.index = index\n this.assoc = assoc\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc)\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createRelativePosition = (type, item, assoc) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = findRootTypeKey(type)\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock)\n }\n return new RelativePosition(typeid, tname, item, assoc)\n}\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @param {number} [assoc]\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {\n let t = type._start\n if (assoc < 0) {\n // associated to the left character or the beginning of a type, increment index if possible.\n if (index === 0) {\n return createRelativePosition(type, null, assoc)\n }\n index--\n }\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc)\n }\n index -= t.length\n }\n if (t.right === null && assoc < 0) {\n // left-associated position, return last available id\n return createRelativePosition(type, t.lastId, assoc)\n }\n t = t.right\n }\n return createRelativePosition(type, null, assoc)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nexport const writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item, assoc } = rpos\n if (item !== null) {\n encoding.writeVarUint(encoder, 0)\n writeID(encoder, item)\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1)\n encoding.writeVarString(encoder, tname)\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2)\n writeID(encoder, type)\n } else {\n throw error.unexpectedCase()\n }\n encoding.writeVarInt(encoder, assoc)\n return encoder\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nexport const encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder()\n writeRelativePosition(encoder, rpos)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition}\n *\n * @function\n */\nexport const readRelativePosition = decoder => {\n let type = null\n let tname = null\n let itemID = null\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder)\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder)\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder)\n }\n }\n const assoc = decoding.hasContent(decoder) ? decoding.readVarInt(decoder) : 0\n return new RelativePosition(type, tname, itemID, assoc)\n}\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition}\n */\nexport const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))\n\n/**\n * Transform a relative position to an absolute position.\n *\n * If you want to share the relative position with other users, you should set\n * `followUndoneDeletions` to false to get consistent results across all clients.\n *\n * When calculating the absolute position, we try to follow the \"undone deletions\". This yields\n * better results for the user who performed undo. However, only the user who performed the undo\n * will get the better results, the other users don't know which operations recreated a deleted\n * range of content. There is more information in this ticket: https://github.com/yjs/yjs/issues/638\n *\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @param {boolean} followUndoneDeletions - whether to follow undone deletions - see https://github.com/yjs/yjs/issues/638\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nexport const createAbsolutePositionFromRelativePosition = (rpos, doc, followUndoneDeletions = true) => {\n const store = doc.store\n const rightID = rpos.item\n const typeID = rpos.type\n const tname = rpos.tname\n const assoc = rpos.assoc\n let type = null\n let index = 0\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followUndoneDeletions ? followRedone(store, rightID) : { item: getItem(store, rightID), diff: 0 }\n const right = res.item\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent)\n if (type._item === null || !type._item.deleted) {\n index = (right.deleted || !right.countable) ? 0 : (res.diff + (assoc >= 0 ? 0 : 1)) // adjust position based on left association if necessary\n let n = right.left\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length\n }\n n = n.left\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname)\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) }\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n if (assoc >= 0) {\n index = type._length\n } else {\n index = 0\n }\n }\n return createAbsolutePosition(type, index, rpos.assoc)\n}\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc\n)\n", "import {\n isDeleted,\n createDeleteSetFromStructStore,\n getStateVector,\n getItemCleanStart,\n iterateDeletedStructs,\n writeDeleteSet,\n writeStateVector,\n readDeleteSet,\n readStateVector,\n createDeleteSet,\n createID,\n getState,\n findIndexSS,\n UpdateEncoderV2,\n applyUpdateV2,\n LazyStructReader,\n equalDeleteSets,\n UpdateDecoderV1, UpdateDecoderV2, DSEncoderV1, DSEncoderV2, DSDecoderV1, DSDecoderV2, Transaction, Doc, DeleteSet, Item, // eslint-disable-line\n mergeDeleteSets\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as set from 'lib0/set'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\n\nexport class Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nexport const equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients\n const ds2 = snap2.ds.clients\n const sv1 = snap1.sv\n const sv2 = snap2.sv\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || []\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i]\n const dsitem2 = dsitems2[i]\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n */\nexport const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds)\n writeStateVector(encoder, snapshot.sv)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nexport const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DSEncoderV1())\n\n/**\n * @param {Uint8Array} buf\n * @param {DSDecoderV1 | DSDecoderV2} [decoder]\n * @return {Snapshot}\n */\nexport const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nexport const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)))\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nexport const createSnapshot = (ds, sm) => new Snapshot(ds, sm)\n\nexport const emptySnapshot = createSnapshot(createDeleteSet(), new Map())\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nexport const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store))\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined\n ? !item.deleted\n : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nexport const splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create)\n const store = transaction.doc.store\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n })\n iterateDeletedStructs(transaction, snapshot.ds, _item => {})\n meta.add(snapshot)\n }\n}\n\n/**\n * @example\n * const ydoc = new Y.Doc({ gc: false })\n * ydoc.getText().insert(0, 'world!')\n * const snapshot = Y.snapshot(ydoc)\n * ydoc.getText().insert(0, 'hello ')\n * const restored = Y.createDocFromSnapshot(ydoc, snapshot)\n * assert(restored.getText().toString() === 'world!')\n *\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nexport const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('Garbage-collection must be disabled in `originDoc`!')\n }\n const { sv, ds } = snapshot\n\n const encoder = new UpdateEncoderV2()\n originDoc.transact(transaction => {\n let size = 0\n sv.forEach(clock => {\n if (clock > 0) {\n size++\n }\n })\n encoding.writeVarUint(encoder.restEncoder, size)\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n const structs = originDoc.store.clients.get(client) || []\n const lastStructIndex = findIndexSS(structs, clock - 1)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1)\n encoder.writeClient(client)\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0)\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0)\n }\n }\n writeDeleteSet(encoder, ds)\n })\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot')\n return newDoc\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n */\nexport const snapshotContainsUpdateV2 = (snapshot, update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n if ((snapshot.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) {\n return false\n }\n }\n const mergedDS = mergeDeleteSets([snapshot.ds, readDeleteSet(updateDecoder)])\n return equalDeleteSets(snapshot.ds, mergedDS)\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n */\nexport const snapshotContainsUpdate = (snapshot, update) => snapshotContainsUpdateV2(snapshot, update, UpdateDecoderV1)\n", "import {\n GC,\n splitItem,\n Transaction, ID, Item, DSDecoderV2 // eslint-disable-line\n} from '../internals.js'\n\nimport * as math from 'lib0/math'\nimport * as error from 'lib0/error'\n\nexport class StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n /**\n * @type {null | { missing: Map, update: Uint8Array }}\n */\n this.pendingStructs = null\n /**\n * @type {null | Uint8Array}\n */\n this.pendingDs = null\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nexport const getStateVector = store => {\n const sm = new Map()\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1]\n sm.set(client, struct.id.clock + struct.length)\n })\n return sm\n}\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nexport const getState = (store, client) => {\n const structs = store.clients.get(client)\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1]\n return lastStruct.id.clock + lastStruct.length\n}\n\n/**\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const integretyCheck = store => {\n store.clients.forEach(structs => {\n for (let i = 1; i < structs.length; i++) {\n const l = structs[i - 1]\n const r = structs[i]\n if (l.id.clock + l.length !== r.id.clock) {\n throw new Error('StructStore failed integrety check')\n }\n }\n })\n}\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nexport const addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client)\n if (structs === undefined) {\n structs = []\n store.clients.set(struct.id.client, structs)\n } else {\n const lastStruct = structs[structs.length - 1]\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct)\n}\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nexport const findIndexSS = (structs, clock) => {\n let left = 0\n let right = structs.length - 1\n let mid = structs[right]\n let midclock = mid.id.clock\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right) // pivoting the search\n while (left <= right) {\n mid = structs[midindex]\n midclock = mid.id.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n midindex = math.floor((left + right) / 2)\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nexport const find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n return structs[findIndexSS(structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nexport const getItem = /** @type {function(StructStore,ID):Item} */ (find)\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nexport const findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock)\n const struct = structs[index]\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n return index + 1\n }\n return index\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client))\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n const index = findIndexSS(structs, id.clock)\n const struct = structs[index]\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1))\n }\n return struct\n}\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nexport const replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client))\n structs[findIndexSS(structs, struct.id.clock)] = newStruct\n}\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len\n let index = findIndexCleanStart(transaction, structs, clockStart)\n let struct\n do {\n struct = structs[index++]\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd)\n }\n f(struct)\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n}\n", "import {\n getState,\n writeStructsFromTransaction,\n writeDeleteSet,\n DeleteSet,\n sortAndMergeDeleteSet,\n getStateVector,\n findIndexSS,\n callEventHandlerListeners,\n Item,\n generateNewClientId,\n createID,\n cleanupYTextAfterTransaction,\n UpdateEncoderV1, UpdateEncoderV2, GC, StructStore, AbstractType, AbstractStruct, YEvent, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as set from 'lib0/set'\nimport * as logging from 'lib0/logging'\nimport { callAll } from 'lib0/function'\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const ydoc = new Y.Doc()\n * const map = ydoc.getMap('map')\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * ydoc.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nexport class Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet()\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store)\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map()\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map>,Set>}\n */\n this.changed = new Map()\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map>,Array>>}\n */\n this.changedParentTypes = new Map()\n /**\n * @type {Array}\n */\n this._mergeStructs = []\n /**\n * @type {any}\n */\n this.origin = origin\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map()\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set()\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set()\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set()\n /**\n * @type {boolean}\n */\n this._needFormattingCleanup = false\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nexport const writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet)\n writeStructsFromTransaction(encoder, transaction)\n writeDeleteSet(encoder, transaction.deleteSet)\n return true\n}\n\n/**\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const nextID = transaction => {\n const y = transaction.doc\n return createID(y.clientID, getState(y.store, y.clientID))\n}\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType>} type\n * @param {string|null} parentSub\n */\nexport const addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub)\n }\n}\n\n/**\n * @param {Array} structs\n * @param {number} pos\n * @return {number} # of merged structs\n */\nconst tryToMergeWithLefts = (structs, pos) => {\n let right = structs[pos]\n let left = structs[pos - 1]\n let i = pos\n for (; i > 0; right = left, left = structs[--i - 1]) {\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left))\n }\n continue\n }\n }\n break\n }\n const merged = pos - i\n if (merged) {\n // remove all merged structs from the array\n structs.splice(pos + 1 - merged, merged)\n }\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n const endDeleteItemClock = deleteItem.clock + deleteItem.len\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si]\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false)\n }\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiency and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1))\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[si]\n ) {\n si -= 1 + tryToMergeWithLefts(structs, si)\n }\n }\n })\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nexport const tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter)\n tryMergeDeleteSet(ds, store)\n}\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i]\n const doc = transaction.doc\n const store = doc.store\n const ds = transaction.deleteSet\n const mergeStructs = transaction._mergeStructs\n try {\n sortAndMergeDeleteSet(ds)\n transaction.afterState = getStateVector(transaction.doc.store)\n doc.emit('beforeObserverCalls', [transaction, doc])\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = []\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs)\n }\n })\n )\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n )\n events\n .forEach(event => {\n event.currentTarget = type\n // path is relative to the current target\n event._path = null\n })\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length)\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction)\n }\n })\n })\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]))\n callAll(fs, [])\n if (transaction._needFormattingCleanup) {\n cleanupYTextAfterTransaction(transaction)\n }\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter)\n }\n tryMergeDeleteSet(ds, store)\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1)\n for (let i = structs.length - 1; i >= firstChangePos;) {\n i -= 1 + tryToMergeWithLefts(structs, i)\n }\n }\n })\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = mergeStructs.length - 1; i >= 0; i--) {\n const { client, clock } = mergeStructs[i].id\n const structs = /** @type {Array} */ (store.clients.get(client))\n const replacedStructPos = findIndexSS(structs, clock)\n if (replacedStructPos + 1 < structs.length) {\n if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {\n continue // no need to perform next check, both are already merged\n }\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLefts(structs, replacedStructPos)\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.')\n doc.clientID = generateNewClientId()\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc])\n if (doc._observers.has('update')) {\n const encoder = new UpdateEncoderV1()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction\n if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {\n subdocsAdded.forEach(subdoc => {\n subdoc.clientID = doc.clientID\n if (subdoc.collectionid == null) {\n subdoc.collectionid = doc.collectionid\n }\n doc.subdocs.add(subdoc)\n })\n subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc))\n doc.emit('subdocs', [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction])\n subdocsRemoved.forEach(subdoc => subdoc.destroy())\n }\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = []\n doc.emit('afterAllTransactions', [doc, transactionCleanups])\n } else {\n cleanupTransactions(transactionCleanups, i + 1)\n }\n }\n }\n}\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @template T\n * @param {Doc} doc\n * @param {function(Transaction):T} f\n * @param {any} [origin=true]\n * @return {T}\n *\n * @function\n */\nexport const transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups\n let initialCall = false\n /**\n * @type {any}\n */\n let result = null\n if (doc._transaction === null) {\n initialCall = true\n doc._transaction = new Transaction(doc, origin, local)\n transactionCleanups.push(doc._transaction)\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc])\n }\n doc.emit('beforeTransaction', [doc._transaction, doc])\n }\n try {\n result = f(doc._transaction)\n } finally {\n if (initialCall) {\n const finishCleanup = doc._transaction === transactionCleanups[0]\n doc._transaction = null\n if (finishCleanup) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0)\n }\n }\n }\n return result\n}\n", "import {\n mergeDeleteSets,\n iterateDeletedStructs,\n keepItem,\n transact,\n createID,\n redoItem,\n isParentOf,\n followRedone,\n getItemCleanStart,\n isDeleted,\n addToDeleteSet,\n YEvent, Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as time from 'lib0/time'\nimport * as array from 'lib0/array'\nimport * as logging from 'lib0/logging'\nimport { ObservableV2 } from 'lib0/observable'\n\nexport class StackItem {\n /**\n * @param {DeleteSet} deletions\n * @param {DeleteSet} insertions\n */\n constructor (deletions, insertions) {\n this.insertions = insertions\n this.deletions = deletions\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map()\n }\n}\n/**\n * @param {Transaction} tr\n * @param {UndoManager} um\n * @param {StackItem} stackItem\n */\nconst clearUndoManagerStackItem = (tr, um, stackItem) => {\n iterateDeletedStructs(tr, stackItem.deletions, item => {\n if (item instanceof Item && um.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false)\n }\n })\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {'undo'|'redo'} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Keep a reference to the transaction so we can fire the event with the changedParentTypes\n * @type {any}\n */\n let _tr = null\n const doc = undoManager.doc\n const scope = undoManager.scope\n transact(doc, transaction => {\n while (stack.length > 0 && undoManager.currStackItem === null) {\n const store = doc.store\n const stackItem = /** @type {StackItem} */ (stack.pop())\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set()\n /**\n * @type {Array}\n */\n const itemsToDelete = []\n let performedChange = false\n iterateDeletedStructs(transaction, stackItem.insertions, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id)\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff))\n }\n struct = item\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct)\n }\n }\n })\n iterateDeletedStructs(transaction, stackItem.deletions, struct => {\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.\n !isDeleted(stackItem.insertions, struct.id)\n ) {\n itemsToRedo.add(struct)\n }\n })\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange\n })\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i]\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction)\n performedChange = true\n }\n }\n undoManager.currStackItem = performedChange ? stackItem : null\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0\n }\n })\n _tr = transaction\n }, undoManager)\n const res = undoManager.currStackItem\n if (res != null) {\n const changedParentTypes = _tr.changedParentTypes\n undoManager.emit('stack-item-popped', [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager])\n undoManager.currStackItem = null\n }\n return res\n}\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Transaction):boolean} [UndoManagerOptions.captureTransaction] Do not capture changes of a Transaction if result false.\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter what an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n * @property {boolean} [ignoreRemoteMapChanges] Experimental. By default, the UndoManager will never overwrite remote changes. Enable this property to enable overwriting remote changes on key-value changes (Y.Map, properties on Y.Xml, etc..).\n * @property {Doc} [doc] The document that this UndoManager operates on. Only needed if typeScope is empty.\n */\n\n/**\n * @typedef {Object} StackItemEvent\n * @property {StackItem} StackItemEvent.stackItem\n * @property {any} StackItemEvent.origin\n * @property {'undo'|'redo'} StackItemEvent.type\n * @property {Map>,Array>>} StackItemEvent.changedParentTypes\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {ObservableV2<{'stack-item-added':function(StackItemEvent, UndoManager):void, 'stack-item-popped': function(StackItemEvent, UndoManager):void, 'stack-cleared': function({ undoStackCleared: boolean, redoStackCleared: boolean }):void, 'stack-item-updated': function(StackItemEvent, UndoManager):void }>}\n */\nexport class UndoManager extends ObservableV2 {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, {\n captureTimeout = 500,\n captureTransaction = _tr => true,\n deleteFilter = () => true,\n trackedOrigins = new Set([null]),\n ignoreRemoteMapChanges = false,\n doc = /** @type {Doc} */ (array.isArray(typeScope) ? typeScope[0].doc : typeScope.doc)\n } = {}) {\n super()\n /**\n * @type {Array>}\n */\n this.scope = []\n this.doc = doc\n this.addToScope(typeScope)\n this.deleteFilter = deleteFilter\n trackedOrigins.add(this)\n this.trackedOrigins = trackedOrigins\n this.captureTransaction = captureTransaction\n /**\n * @type {Array}\n */\n this.undoStack = []\n /**\n * @type {Array}\n */\n this.redoStack = []\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false\n this.redoing = false\n /**\n * The currently popped stack item if UndoManager.undoing or UndoManager.redoing\n *\n * @type {StackItem|null}\n */\n this.currStackItem = null\n this.lastChange = 0\n this.ignoreRemoteMapChanges = ignoreRemoteMapChanges\n this.captureTimeout = captureTimeout\n /**\n * @param {Transaction} transaction\n */\n this.afterTransactionHandler = transaction => {\n // Only track certain transactions\n if (\n !this.captureTransaction(transaction) ||\n !this.scope.some(type => transaction.changedParentTypes.has(type)) ||\n (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))\n ) {\n return\n }\n const undoing = this.undoing\n const redoing = this.redoing\n const stack = undoing ? this.redoStack : this.undoStack\n if (undoing) {\n this.stopCapturing() // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.clear(false, true)\n }\n const insertions = new DeleteSet()\n transaction.afterState.forEach((endClock, client) => {\n const startClock = transaction.beforeState.get(client) || 0\n const len = endClock - startClock\n if (len > 0) {\n addToDeleteSet(insertions, client, startClock, len)\n }\n })\n const now = time.getUnixTime()\n let didAdd = false\n if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1]\n lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet])\n lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions])\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, insertions))\n didAdd = true\n }\n if (!undoing && !redoing) {\n this.lastChange = now\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true)\n }\n })\n /**\n * @type {[StackItemEvent, UndoManager]}\n */\n const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this]\n if (didAdd) {\n this.emit('stack-item-added', changeEvent)\n } else {\n this.emit('stack-item-updated', changeEvent)\n }\n }\n this.doc.on('afterTransaction', this.afterTransactionHandler)\n this.doc.on('destroy', () => {\n this.destroy()\n })\n }\n\n /**\n * @param {Array> | AbstractType} ytypes\n */\n addToScope (ytypes) {\n ytypes = array.isArray(ytypes) ? ytypes : [ytypes]\n ytypes.forEach(ytype => {\n if (this.scope.every(yt => yt !== ytype)) {\n if (ytype.doc !== this.doc) logging.warn('[yjs#509] Not same Y.Doc') // use MultiDocUndoManager instead. also see https://github.com/yjs/yjs/issues/509\n this.scope.push(ytype)\n }\n })\n }\n\n /**\n * @param {any} origin\n */\n addTrackedOrigin (origin) {\n this.trackedOrigins.add(origin)\n }\n\n /**\n * @param {any} origin\n */\n removeTrackedOrigin (origin) {\n this.trackedOrigins.delete(origin)\n }\n\n clear (clearUndoStack = true, clearRedoStack = true) {\n if ((clearUndoStack && this.canUndo()) || (clearRedoStack && this.canRedo())) {\n this.doc.transact(tr => {\n if (clearUndoStack) {\n this.undoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.undoStack = []\n }\n if (clearRedoStack) {\n this.redoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.redoStack = []\n }\n this.emit('stack-cleared', [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }])\n })\n }\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true\n let res\n try {\n res = popStackItem(this, this.undoStack, 'undo')\n } finally {\n this.undoing = false\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true\n let res\n try {\n res = popStackItem(this, this.redoStack, 'redo')\n } finally {\n this.redoing = false\n }\n return res\n }\n\n /**\n * Are undo steps available?\n *\n * @return {boolean} `true` if undo is possible\n */\n canUndo () {\n return this.undoStack.length > 0\n }\n\n /**\n * Are redo steps available?\n *\n * @return {boolean} `true` if redo is possible\n */\n canRedo () {\n return this.redoStack.length > 0\n }\n\n destroy () {\n this.trackedOrigins.delete(this)\n this.doc.off('afterTransaction', this.afterTransactionHandler)\n super.destroy()\n }\n}\n", "import * as binary from 'lib0/binary'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as error from 'lib0/error'\nimport * as f from 'lib0/function'\nimport * as logging from 'lib0/logging'\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as string from 'lib0/string'\n\nimport {\n ContentAny,\n ContentBinary,\n ContentDeleted,\n ContentDoc,\n ContentEmbed,\n ContentFormat,\n ContentJSON,\n ContentString,\n ContentType,\n createID,\n decodeStateVector,\n DSEncoderV1,\n DSEncoderV2,\n GC,\n Item,\n mergeDeleteSets,\n readDeleteSet,\n readItemContent,\n Skip,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n writeDeleteSet,\n YXmlElement,\n YXmlHook\n} from '../internals.js'\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n */\nfunction * lazyStructReaderGenerator (decoder) {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n // @todo use switch instead of ifs\n if (info === 10) {\n const len = decoding.readVarUint(decoder.restDecoder)\n yield new Skip(createID(client, clock), len)\n clock += len\n } else if ((binary.BITS5 & info) !== 0) {\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n // @ts-ignore Force writing a string here.\n cantCopyParentInfo ? (decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n yield struct\n clock += struct.length\n } else {\n const len = decoder.readLen()\n yield new GC(createID(client, clock), len)\n clock += len\n }\n }\n }\n}\n\nexport class LazyStructReader {\n /**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {boolean} filterSkips\n */\n constructor (decoder, filterSkips) {\n this.gen = lazyStructReaderGenerator(decoder)\n /**\n * @type {null | Item | Skip | GC}\n */\n this.curr = null\n this.done = false\n this.filterSkips = filterSkips\n this.next()\n }\n\n /**\n * @return {Item | GC | Skip |null}\n */\n next () {\n // ignore \"Skip\" structs\n do {\n this.curr = this.gen.next().value || null\n } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip)\n return this.curr\n }\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const logUpdate = update => logUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n logging.print('Structs: ', structs)\n const ds = readDeleteSet(updateDecoder)\n logging.print('DeleteSet: ', ds)\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n return {\n structs,\n ds: readDeleteSet(updateDecoder)\n }\n}\n\nexport class LazyStructWriter {\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n constructor (encoder) {\n this.currClient = 0\n this.startClock = 0\n this.written = 0\n this.encoder = encoder\n /**\n * We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client.\n *\n * This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder.\n *\n * We fragment the restEncoder and store a slice of it per-client until we know how many clients there are.\n * When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information.\n *\n * @type {Array<{ written: number, restEncoder: Uint8Array }>}\n */\n this.clientStructs = []\n }\n}\n\n/**\n * @param {Array} updates\n * @return {Uint8Array}\n */\nexport const mergeUpdates = updates => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof DSEncoderV1 | typeof DSEncoderV2} YEncoder\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {\n const encoder = new YEncoder()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let size = 0\n let currClient = curr.id.client\n let stopCounting = curr.id.clock !== 0 // must start at 0\n let currClock = stopCounting ? 0 : curr.id.clock + curr.length\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n if (currClock !== 0) {\n size++\n // We found a new client\n // write what we have to the encoder\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n currClient = curr.id.client\n currClock = 0\n stopCounting = curr.id.clock !== 0\n }\n // we ignore skips\n if (curr.constructor === Skip) {\n stopCounting = true\n }\n if (!stopCounting) {\n currClock = curr.id.clock + curr.length\n }\n }\n // write what we have\n if (currClock !== 0) {\n size++\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n // prepend the size of the state vector\n const enc = encoding.createEncoder()\n encoding.writeVarUint(enc, size)\n encoding.writeBinaryEncoder(enc, encoder.restEncoder)\n encoder.restEncoder = enc\n return encoder.toUint8Array()\n } else {\n encoding.writeVarUint(encoder.restEncoder, 0)\n return encoder.toUint8Array()\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdate = update => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {{ from: Map, to: Map }}\n */\nexport const parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {\n /**\n * @type {Map}\n */\n const from = new Map()\n /**\n * @type {Map}\n */\n const to = new Map()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let currClient = curr.id.client\n let currClock = curr.id.clock\n // write the beginning to `from`\n from.set(currClient, currClock)\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n // We found a new client\n // write the end to `to`\n to.set(currClient, currClock)\n // write the beginning to `from`\n from.set(curr.id.client, curr.id.clock)\n // update currClient\n currClient = curr.id.client\n }\n currClock = curr.id.clock + curr.length\n }\n // write the end to `to`\n to.set(currClient, currClock)\n }\n return { from, to }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {{ from: Map, to: Map }}\n */\nexport const parseUpdateMeta = update => parseUpdateMetaV2(update, UpdateDecoderV1)\n\n/**\n * This method is intended to slice any kind of struct and retrieve the right part.\n * It does not handle side-effects, so it should only be used by the lazy-encoder.\n *\n * @param {Item | GC | Skip} left\n * @param {number} diff\n * @return {Item | GC}\n */\nconst sliceStruct = (left, diff) => {\n if (left.constructor === GC) {\n const { client, clock } = left.id\n return new GC(createID(client, clock + diff), left.length - diff)\n } else if (left.constructor === Skip) {\n const { client, clock } = left.id\n return new Skip(createID(client, clock + diff), left.length - diff)\n } else {\n const leftItem = /** @type {Item} */ (left)\n const { client, clock } = leftItem.id\n return new Item(\n createID(client, clock + diff),\n null,\n createID(client, clock + diff - 1),\n null,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n }\n}\n\n/**\n *\n * This function works similarly to `readUpdateV2`.\n *\n * @param {Array} updates\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n * @return {Uint8Array}\n */\nexport const mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n if (updates.length === 1) {\n return updates[0]\n }\n const updateDecoders = updates.map(update => new YDecoder(decoding.createDecoder(update)))\n let lazyStructDecoders = updateDecoders.map(decoder => new LazyStructReader(decoder, true))\n\n /**\n * @todo we don't need offset because we always slice before\n * @type {null | { struct: Item | GC | Skip, offset: number }}\n */\n let currWrite = null\n\n const updateEncoder = new YEncoder()\n // write structs lazily\n const lazyStructEncoder = new LazyStructWriter(updateEncoder)\n\n // Note: We need to ensure that all lazyStructDecoders are fully consumed\n // Note: Should merge document updates whenever possible - even from different updates\n // Note: Should handle that some operations cannot be applied yet ()\n\n while (true) {\n // Write higher clients first ⇒ sort by clientID & clock and remove decoders without content\n lazyStructDecoders = lazyStructDecoders.filter(dec => dec.curr !== null)\n lazyStructDecoders.sort(\n /** @type {function(any,any):number} */ (dec1, dec2) => {\n if (dec1.curr.id.client === dec2.curr.id.client) {\n const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock\n if (clockDiff === 0) {\n // @todo remove references to skip since the structDecoders must filter Skips.\n return dec1.curr.constructor === dec2.curr.constructor\n ? 0\n : dec1.curr.constructor === Skip ? 1 : -1 // we are filtering skips anyway.\n } else {\n return clockDiff\n }\n } else {\n return dec2.curr.id.client - dec1.curr.id.client\n }\n }\n )\n if (lazyStructDecoders.length === 0) {\n break\n }\n const currDecoder = lazyStructDecoders[0]\n // write from currDecoder until the next operation is from another client or if filler-struct\n // then we need to reorder the decoders and find the next operation to write\n const firstClient = /** @type {Item | GC} */ (currDecoder.curr).id.client\n\n if (currWrite !== null) {\n let curr = /** @type {Item | GC | null} */ (currDecoder.curr)\n let iterated = false\n\n // iterate until we find something that we haven't written already\n // remember: first the high client-ids are written\n while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {\n curr = currDecoder.next()\n iterated = true\n }\n if (\n curr === null || // current decoder is empty\n curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`\n (iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) // the above while loop was used and we are potentially missing updates\n ) {\n continue\n }\n\n if (firstClient !== currWrite.struct.id.client) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n } else {\n if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {\n // @todo write currStruct & set currStruct = Skip(clock = currStruct.id.clock + currStruct.length, length = curr.id.clock - self.clock)\n if (currWrite.struct.constructor === Skip) {\n // extend existing skip\n currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock\n } else {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length\n /**\n * @type {Skip}\n */\n const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff)\n currWrite = { struct, offset: 0 }\n }\n } else { // if (currWrite.struct.id.clock + currWrite.struct.length >= curr.id.clock) {\n const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock\n if (diff > 0) {\n if (currWrite.struct.constructor === Skip) {\n // prefer to slice Skip because the other struct might contain more information\n currWrite.struct.length -= diff\n } else {\n curr = sliceStruct(curr, diff)\n }\n }\n if (!currWrite.struct.mergeWith(/** @type {any} */ (curr))) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n }\n }\n }\n } else {\n currWrite = { struct: /** @type {Item | GC} */ (currDecoder.curr), offset: 0 }\n currDecoder.next()\n }\n for (\n let next = currDecoder.curr;\n next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip;\n next = currDecoder.next()\n ) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: next, offset: 0 }\n }\n }\n if (currWrite !== null) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = null\n }\n finishLazyStructWriting(lazyStructEncoder)\n\n const dss = updateDecoders.map(decoder => readDeleteSet(decoder))\n const ds = mergeDeleteSets(dss)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n */\nexport const diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n const state = decodeStateVector(sv)\n const encoder = new YEncoder()\n const lazyStructWriter = new LazyStructWriter(encoder)\n const decoder = new YDecoder(decoding.createDecoder(update))\n const reader = new LazyStructReader(decoder, false)\n while (reader.curr) {\n const curr = reader.curr\n const currClient = curr.id.client\n const svClock = state.get(currClient) || 0\n if (reader.curr.constructor === Skip) {\n // the first written struct shouldn't be a skip\n reader.next()\n continue\n }\n if (curr.id.clock + curr.length > svClock) {\n writeStructToLazyStructWriter(lazyStructWriter, curr, math.max(svClock - curr.id.clock, 0))\n reader.next()\n while (reader.curr && reader.curr.id.client === currClient) {\n writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0)\n reader.next()\n }\n } else {\n // read until something new comes up\n while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {\n reader.next()\n }\n }\n }\n finishLazyStructWriting(lazyStructWriter)\n // write ds\n const ds = readDeleteSet(decoder)\n writeDeleteSet(encoder, ds)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n */\nexport const diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {LazyStructWriter} lazyWriter\n */\nconst flushLazyStructWriter = lazyWriter => {\n if (lazyWriter.written > 0) {\n lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: encoding.toUint8Array(lazyWriter.encoder.restEncoder) })\n lazyWriter.encoder.restEncoder = encoding.createEncoder()\n lazyWriter.written = 0\n }\n}\n\n/**\n * @param {LazyStructWriter} lazyWriter\n * @param {Item | GC} struct\n * @param {number} offset\n */\nconst writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {\n // flush curr if we start another client\n if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {\n flushLazyStructWriter(lazyWriter)\n }\n if (lazyWriter.written === 0) {\n lazyWriter.currClient = struct.id.client\n // write next client\n lazyWriter.encoder.writeClient(struct.id.client)\n // write startClock\n encoding.writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset)\n }\n struct.write(lazyWriter.encoder, offset)\n lazyWriter.written++\n}\n/**\n * Call this function when we collected all parts and want to\n * put all the parts together. After calling this method,\n * you can continue using the UpdateEncoder.\n *\n * @param {LazyStructWriter} lazyWriter\n */\nconst finishLazyStructWriting = (lazyWriter) => {\n flushLazyStructWriter(lazyWriter)\n\n // this is a fresh encoder because we called flushCurr\n const restEncoder = lazyWriter.encoder.restEncoder\n\n /**\n * Now we put all the fragments together.\n * This works similarly to `writeClientsStructs`\n */\n\n // write # states that were updated - i.e. the clients\n encoding.writeVarUint(restEncoder, lazyWriter.clientStructs.length)\n\n for (let i = 0; i < lazyWriter.clientStructs.length; i++) {\n const partStructs = lazyWriter.clientStructs[i]\n /**\n * Works similarly to `writeStructs`\n */\n // write # encoded structs\n encoding.writeVarUint(restEncoder, partStructs.written)\n // write the rest of the fragment\n encoding.writeUint8Array(restEncoder, partStructs.restEncoder)\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @param {function(Item|GC|Skip):Item|GC|Skip} blockTransformer\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} YDecoder\n * @param {typeof UpdateEncoderV2 | typeof UpdateEncoderV1 } YEncoder\n */\nexport const convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n const updateEncoder = new YEncoder()\n const lazyWriter = new LazyStructWriter(updateEncoder)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0)\n }\n finishLazyStructWriting(lazyWriter)\n const ds = readDeleteSet(updateDecoder)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @typedef {Object} ObfuscatorOptions\n * @property {boolean} [ObfuscatorOptions.formatting=true]\n * @property {boolean} [ObfuscatorOptions.subdocs=true]\n * @property {boolean} [ObfuscatorOptions.yxml=true] Whether to obfuscate nodeName / hookName\n */\n\n/**\n * @param {ObfuscatorOptions} obfuscator\n */\nconst createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => {\n let i = 0\n const mapKeyCache = map.create()\n const nodeNameCache = map.create()\n const formattingKeyCache = map.create()\n const formattingValueCache = map.create()\n formattingValueCache.set(null, null) // end of a formatting range should always be the end of a formatting range\n /**\n * @param {Item|GC|Skip} block\n * @return {Item|GC|Skip}\n */\n return block => {\n switch (block.constructor) {\n case GC:\n case Skip:\n return block\n case Item: {\n const item = /** @type {Item} */ (block)\n const content = item.content\n switch (content.constructor) {\n case ContentDeleted:\n break\n case ContentType: {\n if (yxml) {\n const type = /** @type {ContentType} */ (content).type\n if (type instanceof YXmlElement) {\n type.nodeName = map.setIfUndefined(nodeNameCache, type.nodeName, () => 'node-' + i)\n }\n if (type instanceof YXmlHook) {\n type.hookName = map.setIfUndefined(nodeNameCache, type.hookName, () => 'hook-' + i)\n }\n }\n break\n }\n case ContentAny: {\n const c = /** @type {ContentAny} */ (content)\n c.arr = c.arr.map(() => i)\n break\n }\n case ContentBinary: {\n const c = /** @type {ContentBinary} */ (content)\n c.content = new Uint8Array([i])\n break\n }\n case ContentDoc: {\n const c = /** @type {ContentDoc} */ (content)\n if (subdocs) {\n c.opts = {}\n c.doc.guid = i + ''\n }\n break\n }\n case ContentEmbed: {\n const c = /** @type {ContentEmbed} */ (content)\n c.embed = {}\n break\n }\n case ContentFormat: {\n const c = /** @type {ContentFormat} */ (content)\n if (formatting) {\n c.key = map.setIfUndefined(formattingKeyCache, c.key, () => i + '')\n c.value = map.setIfUndefined(formattingValueCache, c.value, () => ({ i }))\n }\n break\n }\n case ContentJSON: {\n const c = /** @type {ContentJSON} */ (content)\n c.arr = c.arr.map(() => i)\n break\n }\n case ContentString: {\n const c = /** @type {ContentString} */ (content)\n c.str = string.repeat((i % 10) + '', c.str.length)\n break\n }\n default:\n // unknown content type\n error.unexpectedCase()\n }\n if (item.parentSub) {\n item.parentSub = map.setIfUndefined(mapKeyCache, item.parentSub, () => i + '')\n }\n i++\n return block\n }\n default:\n // unknown block-type\n error.unexpectedCase()\n }\n }\n}\n\n/**\n * This function obfuscates the content of a Yjs update. This is useful to share\n * buggy Yjs documents while significantly limiting the possibility that a\n * developer can on the user. Note that it might still be possible to deduce\n * some information by analyzing the \"structure\" of the document or by analyzing\n * the typing behavior using the CRDT-related metadata that is still kept fully\n * intact.\n *\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nexport const obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nexport const obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2)\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV1ToV2 = update => convertUpdateFormat(update, f.id, UpdateDecoderV1, UpdateEncoderV2)\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, f.id, UpdateDecoderV2, UpdateEncoderV1)\n", "import {\n isDeleted,\n Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line\n} from '../internals.js'\n\nimport * as set from 'lib0/set'\nimport * as array from 'lib0/array'\nimport * as error from 'lib0/error'\n\nconst errorComputeChanges = 'You must not compute changes after the event-handler fired.'\n\n/**\n * @template {AbstractType} T\n * YEvent describes the changes on a YType.\n */\nexport class YEvent {\n /**\n * @param {T} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {T}\n */\n this.target = target\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction\n /**\n * @type {Object|null}\n */\n this._changes = null\n /**\n * @type {null | Map}\n */\n this._keys = null\n /**\n * @type {null | Array<{ insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object }>}\n */\n this._delta = null\n /**\n * @type {Array|null}\n */\n this._path = null\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n return this._path || (this._path = getPathTo(this.currentTarget, this.target))\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * @type {Map}\n */\n get keys () {\n if (this._keys === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const keys = new Map()\n const target = this.target\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key))\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action\n let oldValue\n if (this.adds(item)) {\n let prev = item.left\n while (prev !== null && this.adds(prev)) {\n prev = prev.left\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete'\n oldValue = array.last(prev.content.getContent())\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update'\n oldValue = array.last(prev.content.getContent())\n } else {\n action = 'add'\n oldValue = undefined\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete'\n oldValue = array.last(/** @type {Item} */ item.content.getContent())\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue })\n }\n })\n this._keys = keys\n }\n return this._keys\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {Array<{insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object}>}\n */\n get delta () {\n return this.changes.delta\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n let changes = this._changes\n if (changes === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const target = this.target\n const added = set.create()\n const deleted = set.create()\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = []\n changes = {\n added,\n deleted,\n delta,\n keys: this.keys\n }\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp)\n }\n }\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp()\n lastOp = { delete: 0 }\n }\n lastOp.delete += item.length\n deleted.add(item)\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp()\n lastOp = { insert: [] }\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent())\n added.add(item)\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp()\n lastOp = { retain: 0 }\n }\n lastOp.retain += item.length\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp()\n }\n }\n this._changes = changes\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = []\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub)\n } else {\n // parent is array-ish\n let i = 0\n let c = /** @type {AbstractType} */ (child._item.parent)._start\n while (c !== child._item && c !== null) {\n if (!c.deleted && c.countable) {\n i += c.length\n }\n c = c.right\n }\n path.unshift(i)\n }\n child = /** @type {AbstractType} */ (child._item.parent)\n }\n return path\n}\n", "import {\n removeEventHandlerListener,\n callEventHandlerListeners,\n addEventHandlerListener,\n createEventHandler,\n getState,\n isVisible,\n ContentType,\n createID,\n ContentAny,\n ContentBinary,\n getItemCleanStart,\n ContentDoc, YText, YArray, UpdateEncoderV1, UpdateEncoderV2, Doc, Snapshot, Transaction, EventHandler, YEvent, Item, // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as iterator from 'lib0/iterator'\nimport * as error from 'lib0/error'\nimport * as math from 'lib0/math'\nimport * as log from 'lib0/logging'\n\n/**\n * https://docs.yjs.dev/getting-started/working-with-shared-types#caveats\n */\nexport const warnPrematureAccess = () => { log.warn('Invalid access: Add Yjs type to a document before reading data.') }\n\nconst maxSearchMarker = 80\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0\n\nexport class ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true\n this.p = p\n this.index = index\n this.timestamp = globalSearchMarkerTimestamp++\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++ }\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false\n marker.p = p\n p.marker = true\n marker.index = index\n marker.timestamp = globalSearchMarkerTimestamp++\n}\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b)\n overwriteMarker(marker, p, index)\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index)\n searchMarker.push(pm)\n return pm\n }\n}\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nexport const findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b)\n let p = yarray._start\n let pindex = 0\n if (marker !== null) {\n p = marker.p\n pindex = marker.index\n refreshMarkerTimestamp(marker) // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length\n }\n p = p.right\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex)\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n}\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nexport const updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i]\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p\n p.marker = false\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1)\n continue\n }\n m.p = p\n p.marker = true\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len)\n }\n }\n}\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nexport const getTypeChildren = t => {\n t.doc ?? warnPrematureAccess()\n let s = t._start\n const arr = []\n while (s) {\n arr.push(s)\n s = s.right\n }\n return arr\n}\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nexport const callTypeObservers = (type, transaction, event) => {\n const changedType = type\n const changedParentTypes = transaction.changedParentTypes\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event)\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent)\n }\n callEventHandlerListeners(changedType._eH, event, transaction)\n}\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nexport class AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null\n /**\n * @type {Map}\n */\n this._map = new Map()\n /**\n * @type {Item|null}\n */\n this._start = null\n /**\n * @type {Doc|null}\n */\n this.doc = null\n this._length = 0\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler()\n /**\n * Deep event handlers\n * @type {EventHandler>,Transaction>}\n */\n this._dEH = createEventHandler()\n /**\n * @type {null | Array}\n */\n this._searchMarker = null\n }\n\n /**\n * @return {AbstractType|null}\n */\n get parent () {\n return this._item ? /** @type {AbstractType} */ (this._item.parent) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y\n this._item = item\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {AbstractType}\n */\n clone () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder\n */\n _write (_encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} _parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, _parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f)\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f)\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} start\n * @param {number} end\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListSlice = (type, start, end) => {\n type.doc ?? warnPrematureAccess()\n if (start < 0) {\n start = type._length + start\n }\n if (end < 0) {\n end = type._length + end\n }\n let len = end - start\n const cs = []\n let n = type._start\n while (n !== null && len > 0) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n if (c.length <= start) {\n start -= c.length\n } else {\n for (let i = start; i < c.length && len > 0; i++) {\n cs.push(c[i])\n len--\n }\n start = 0\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArray = type => {\n type.doc ?? warnPrematureAccess()\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArraySnapshot = (type, snapshot) => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * Executes a provided function on once on every element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nexport const typeListForEach = (type, f) => {\n let index = 0\n let n = type._start\n type.doc ?? warnPrematureAccess()\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = []\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type))\n })\n return result\n}\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nexport const typeListCreateIterator = type => {\n let n = type._start\n /**\n * @type {Array|null}\n */\n let currentContent = null\n let currentContentIndex = 0\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent()\n currentContentIndex = 0\n n = n.right // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++]\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null\n }\n return {\n done: false,\n value\n }\n }\n }\n}\n\n/**\n * Executes a provided function on once on every element of this YArray.\n * Operates on a snapshotted state of the document.\n *\n * @param {AbstractType} type\n * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray.\n * @param {Snapshot} snapshot\n *\n * @private\n * @function\n */\nexport const typeListForEachSnapshot = (type, f, snapshot) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nexport const typeListGet = (type, index) => {\n type.doc ?? warnPrematureAccess()\n const marker = findMarker(type, index)\n let n = type._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length\n }\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const store = doc.store\n const right = referenceItem === null ? parent._start : referenceItem.right\n /**\n * @type {Array|number|null>}\n */\n let jsonContent = []\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent))\n left.integrate(transaction, 0)\n jsonContent = []\n }\n }\n content.forEach(c => {\n if (c === null) {\n jsonContent.push(c)\n } else {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c)\n break\n default:\n packJsonContent()\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))))\n left.integrate(transaction, 0)\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)))\n left.integrate(transaction, 0)\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c))\n left.integrate(transaction, 0)\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n }\n })\n packJsonContent()\n}\n\nconst lengthExceeded = () => error.create('Length exceeded!')\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index > parent._length) {\n throw lengthExceeded()\n }\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n break\n }\n index -= n.length\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * Pushing content is special as we generally want to push after the last item. So we don't have to update\n * the serach marker.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListPushGenerics = (transaction, parent, content) => {\n // Use the marker with the highest index and iterate to the right.\n const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start })\n let n = marker.p\n if (n) {\n while (n.right) {\n n = n.right\n }\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index\n const startLength = length\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n index -= n.length\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length))\n }\n n.delete(transaction)\n length -= n.length\n }\n n = n.right\n }\n if (length > 0) {\n throw lengthExceeded()\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nexport const typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key)\n if (c !== undefined) {\n c.delete(transaction)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|null|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nexport const typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let content\n if (value == null) {\n content = new ContentAny([value])\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value])\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value))\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value))\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value)\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0)\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGet = (parent, key) => {\n parent.doc ?? warnPrematureAccess()\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent.doc ?? warnPrematureAccess()\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const typeMapHas = (parent, key) => {\n parent.doc ?? warnPrematureAccess()\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAllSnapshot = (parent, snapshot) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent._map.forEach((value, key) => {\n /**\n * @type {Item|null}\n */\n let v = value\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n if (v !== null && isVisible(v, snapshot)) {\n res[key] = v.content.getContent()[v.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType & { _map: Map }} type\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nexport const createMapIterator = type => {\n type.doc ?? warnPrematureAccess()\n return iterator.iteratorFilter(type._map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)\n}\n", "/**\n * @module YArray\n */\n\nimport {\n YEvent,\n AbstractType,\n typeListGet,\n typeListToArray,\n typeListForEach,\n typeListCreateIterator,\n typeListInsertGenerics,\n typeListPushGenerics,\n typeListDelete,\n typeListMap,\n YArrayRefID,\n callTypeObservers,\n transact,\n warnPrematureAccess,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\nimport { typeListSlice } from './AbstractType.js'\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n * @extends YEvent>\n */\nexport class YArrayEvent extends YEvent {}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YArray extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Construct a new YArray containing the specified items.\n * @template {Object|Array|number|null|string|Uint8Array} T\n * @param {Array} items\n * @return {YArray}\n */\n static from (items) {\n /**\n * @type {YArray}\n */\n const a = new YArray()\n a.push(items)\n return a\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n /**\n * @return {YArray}\n */\n _copy () {\n return new YArray()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YArray}\n */\n clone () {\n /**\n * @type {YArray}\n */\n const arr = new YArray()\n arr.insert(0, this.toArray().map(el =>\n el instanceof AbstractType ? /** @type {typeof el} */ (el.clone()) : el\n ))\n return arr\n }\n\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction))\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, /** @type {any} */ (content))\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content)\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n *\n * @todo Use the following implementation in all types.\n */\n push (content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListPushGenerics(transaction, this, /** @type {any} */ (content))\n })\n } else {\n /** @type {Array} */ (this._prelimContent).push(...content)\n }\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length)\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Returns a portion of this YArray into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function once on every element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nexport const readYArray = _decoder => new YArray()\n", "/**\n * @module YMap\n */\n\nimport {\n YEvent,\n AbstractType,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapHas,\n createMapIterator,\n YMapRefID,\n callTypeObservers,\n transact,\n warnPrematureAccess,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as iterator from 'lib0/iterator'\n\n/**\n * @template T\n * @extends YEvent>\n * Event that describes the changes on a YMap.\n */\nexport class YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction)\n this.keysChanged = subs\n }\n}\n\n/**\n * @template MapType\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable<[string, MapType]>}\n */\nexport class YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super()\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null\n\n if (entries === undefined) {\n this._prelimContent = new Map()\n } else {\n this._prelimContent = new Map(entries)\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value)\n })\n this._prelimContent = null\n }\n\n /**\n * @return {YMap}\n */\n _copy () {\n return new YMap()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YMap}\n */\n clone () {\n /**\n * @type {YMap}\n */\n const map = new YMap()\n this.forEach((value, key) => {\n map.set(key, value instanceof AbstractType ? /** @type {typeof value} */ (value.clone()) : value)\n })\n return map\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs))\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n this.doc ?? warnPrematureAccess()\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1]\n map[key] = v instanceof AbstractType ? v.toJSON() : v\n }\n })\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => /** @type {any} */ ([v[0], v[1].content.getContent()[v[1].length - 1]]))\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(MapType,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n this.doc ?? warnPrematureAccess()\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this)\n }\n })\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key)\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n * @template {MapType} VAL\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {VAL} value The value of the element to add\n * @return {VAL}\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, /** @type {any} */ (value))\n })\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value)\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {MapType|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * Removes all elements from this YMap.\n */\n clear () {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n this.forEach(function (_value, key, map) {\n typeMapDelete(transaction, map, key)\n })\n })\n } else {\n /** @type {Map} */ (this._prelimContent).clear()\n }\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nexport const readYMap = _decoder => new YMap()\n", "/**\n * @module YText\n */\n\nimport {\n YEvent,\n AbstractType,\n getItemCleanStart,\n getState,\n isVisible,\n createID,\n YTextRefID,\n callTypeObservers,\n transact,\n ContentEmbed,\n GC,\n ContentFormat,\n ContentString,\n splitSnapshotAffectedStructs,\n iterateDeletedStructs,\n iterateStructs,\n findMarker,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n updateMarkerChanges,\n ContentType,\n warnPrematureAccess,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as object from 'lib0/object'\nimport * as map from 'lib0/map'\nimport * as error from 'lib0/error'\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b))\n\nexport class ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left\n this.right = right\n this.index = index\n this.currentAttributes = currentAttributes\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase()\n }\n switch (this.right.content.constructor) {\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content))\n }\n break\n default:\n if (!this.right.deleted) {\n this.index += this.right.length\n }\n break\n }\n this.left = this.right\n this.right = this.right.right\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content))\n }\n break\n default:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count))\n }\n pos.index += pos.right.length\n count -= pos.right.length\n }\n break\n }\n pos.left = pos.right\n pos.right = pos.right.right\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {boolean} useSearchMarker\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index, useSearchMarker) => {\n const currentAttributes = new Map()\n const marker = useSearchMarker ? findMarker(parent, index) : null\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes)\n return findNextPosition(transaction, pos, index)\n }\n}\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key)\n }\n currPos.forward()\n }\n const doc = transaction.doc\n const ownClientId = doc.clientID\n negatedAttributes.forEach((val, key) => {\n const left = currPos.left\n const right = currPos.right\n const nextFormat = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n nextFormat.integrate(transaction, 0)\n currPos.right = nextFormat\n currPos.forward()\n })\n}\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format\n if (value === null) {\n currentAttributes.delete(key)\n } else {\n currentAttributes.set(key, value)\n }\n}\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] ?? null, /** @type {ContentFormat} */ (currPos.right.content).value))) {\n //\n } else {\n break\n }\n currPos.forward()\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const negatedAttributes = new Map()\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key]\n const currentVal = currPos.currentAttributes.get(key) ?? null\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal)\n const { left, right } = currPos\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n }\n return negatedAttributes\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object|AbstractType} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((_val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null\n }\n })\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : (text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text))\n let { left, right, index } = currPos\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength())\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content)\n right.integrate(transaction, 0)\n currPos.right = right\n currPos.index = index\n currPos.forward()\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n // also check the attributes after the first non-format as we do not want to insert redundant negated attributes there\n // eslint-disable-next-line no-labels\n iterationLoop: while (\n currPos.right !== null &&\n (length > 0 ||\n (\n negatedAttributes.size > 0 &&\n (currPos.right.deleted || currPos.right.content.constructor === ContentFormat)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key)\n } else {\n if (length === 0) {\n // no need to further extend negatedAttributes\n // eslint-disable-next-line no-labels\n break iterationLoop\n }\n negatedAttributes.set(key, value)\n }\n currPos.right.delete(transaction)\n } else {\n currPos.currentAttributes.set(key, value)\n }\n break\n }\n default:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n break\n }\n }\n currPos.forward()\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = ''\n for (; length > 0; length--) {\n newlines += '\\n'\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} curr exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} currAttributes\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {\n /**\n * @type {Item|null}\n */\n let end = start\n /**\n * @type {Map}\n */\n const endFormats = map.create()\n while (end && (!end.countable || end.deleted)) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n const cf = /** @type {ContentFormat} */ (end.content)\n endFormats.set(cf.key, cf)\n }\n end = end.right\n }\n let cleanups = 0\n let reachedCurr = false\n while (start !== end) {\n if (curr === start) {\n reachedCurr = true\n }\n if (!start.deleted) {\n const content = start.content\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content)\n const startAttrValue = startAttributes.get(key) ?? null\n if (endFormats.get(key) !== content || startAttrValue === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction)\n cleanups++\n if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {\n if (startAttrValue === null) {\n currAttributes.delete(key)\n } else {\n currAttributes.set(key, startAttrValue)\n }\n }\n }\n if (!reachedCurr && !start.deleted) {\n updateCurrentAttributes(currAttributes, /** @type {ContentFormat} */ (content))\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right)\n }\n return cleanups\n}\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || !item.right.countable)) {\n item = item.right\n }\n const attrs = new Set()\n // iterate back until a content item is found\n while (item && (item.deleted || !item.countable)) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key\n if (attrs.has(key)) {\n item.delete(transaction)\n } else {\n attrs.add(key)\n }\n }\n item = item.left\n }\n}\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nexport const cleanupYTextFormatting = type => {\n let res = 0\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start)\n let end = type._start\n let startAttributes = map.create()\n const currentAttributes = map.copy(startAttributes)\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content))\n break\n default:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes)\n startAttributes = map.copy(currentAttributes)\n start = end\n break\n }\n }\n end = end.right\n }\n })\n return res\n}\n\n/**\n * This will be called by the transction once the event handlers are called to potentially cleanup\n * formatting attributes.\n *\n * @param {Transaction} transaction\n */\nexport const cleanupYTextAfterTransaction = transaction => {\n /**\n * @type {Set}\n */\n const needFullCleanup = new Set()\n // check if another formatting item was inserted\n const doc = transaction.doc\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (\n !item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat && item.constructor !== GC\n ) {\n needFullCleanup.add(/** @type {any} */ (item).parent)\n }\n })\n }\n // cleanup in a new transaction\n transact(doc, (t) => {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || !(/** @type {YText} */ (item.parent)._hasFormatting) || needFullCleanup.has(/** @type {YText} */ (item.parent))) {\n return\n }\n const parent = /** @type {YText} */ (item.parent)\n if (item.content.constructor === ContentFormat) {\n needFullCleanup.add(parent)\n } else {\n // If no formatting attribute was inserted or deleted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n cleanupContextlessFormattingGap(t, item)\n }\n })\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n for (const yText of needFullCleanup) {\n cleanupYTextFormatting(yText)\n }\n })\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length\n const startAttrs = map.copy(currPos.currentAttributes)\n const start = currPos.right\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentType:\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n currPos.right.delete(transaction)\n break\n }\n }\n currPos.forward()\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes)\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent)\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length)\n }\n return currPos\n}\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @extends YEvent\n * Event that describes the changes on a YText type.\n */\nexport class YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed\n */\n constructor (ytext, transaction, subs) {\n super(ytext, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.keysChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.keysChanged.add(sub)\n }\n })\n }\n\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n if (this._changes === null) {\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string|AbstractType|object, delete?:number, retain?:number}>}}\n */\n const changes = {\n keys: this.keys,\n delta: this.delta,\n added: new Set(),\n deleted: new Set()\n }\n this._changes = changes\n }\n return /** @type {any} */ (this._changes)\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc)\n /**\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n */\n const delta = []\n transact(y, transaction => {\n const currentAttributes = new Map() // saves all current attributes for insert\n const oldAttributes = new Map()\n let item = this.target._start\n /**\n * @type {string?}\n */\n let action = null\n /**\n * @type {Object}\n */\n const attributes = {} // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = ''\n let retain = 0\n let deleteLen = 0\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op = null\n switch (action) {\n case 'delete':\n if (deleteLen > 0) {\n op = { delete: deleteLen }\n }\n deleteLen = 0\n break\n case 'insert':\n if (typeof insert === 'object' || insert.length > 0) {\n op = { insert }\n if (currentAttributes.size > 0) {\n op.attributes = {}\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value\n }\n })\n }\n }\n insert = ''\n break\n case 'retain':\n if (retain > 0) {\n op = { retain }\n if (!object.isEmpty(attributes)) {\n op.attributes = object.assign({}, attributes)\n }\n }\n retain = 0\n break\n }\n if (op) delta.push(op)\n action = null\n }\n }\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentType:\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp()\n action = 'insert'\n insert = item.content.getContent()[0]\n addOp()\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += 1\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += 1\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp()\n action = 'insert'\n }\n insert += /** @type {ContentString} */ (item.content).str\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += item.length\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += item.length\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content)\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) ?? null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (equalAttrs(value, (oldAttributes.get(key) ?? null))) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (value !== null) {\n item.delete(transaction)\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value)\n const curVal = currentAttributes.get(key) ?? null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n attributes[key] = curVal\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (value === null) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (attr !== null) { // this will be cleaned up automatically by the contextless cleanup function\n item.delete(transaction)\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp()\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content))\n }\n break\n }\n }\n item = item.right\n }\n addOp()\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1]\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop()\n } else {\n break\n }\n }\n })\n this._delta = delta\n }\n return /** @type {any} */ (this._delta)\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nexport class YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super()\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : []\n /**\n * @type {Array|null}\n */\n this._searchMarker = []\n /**\n * Whether this YText contains formatting attributes.\n * This flag is updated when a formatting item is integrated (see ContentFormat.integrate)\n */\n this._hasFormatting = false\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n try {\n /** @type {Array} */ (this._pending).forEach(f => f())\n } catch (e) {\n console.error(e)\n }\n this._pending = null\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YText}\n */\n clone () {\n const text = new YText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n const event = new YTextEvent(this, transaction, parentSubs)\n callTypeObservers(this, transaction, event)\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local && this._hasFormatting) {\n transaction._needFormattingCleanup = true\n }\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n this.doc ?? warnPrematureAccess()\n let str = ''\n /**\n * @type {Item|null}\n */\n let n = this._start\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str\n }\n n = n.right\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} opts\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map())\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i]\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {})\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {})\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete)\n }\n }\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta))\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n this.doc ?? warnPrematureAccess()\n /**\n * @type{Array}\n */\n const ops = []\n const currentAttributes = new Map()\n const doc = /** @type {Doc} */ (this.doc)\n let str = ''\n let n = this._start\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {}\n let addAttributes = false\n currentAttributes.forEach((value, key) => {\n addAttributes = true\n attributes[key] = value\n })\n /**\n * @type {Object}\n */\n const op = { insert: str }\n if (addAttributes) {\n op.attributes = attributes\n }\n ops.push(op)\n str = ''\n }\n }\n const computeDelta = () => {\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange')\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'removed') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' })\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'added') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' })\n }\n } else if (cur !== undefined) {\n packStr()\n currentAttributes.delete('ychange')\n }\n str += /** @type {ContentString} */ (n.content).str\n break\n }\n case ContentType:\n case ContentEmbed: {\n packStr()\n /**\n * @type {Object}\n */\n const op = {\n insert: n.content.getContent()[0]\n }\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({})\n op.attributes = attrs\n currentAttributes.forEach((value, key) => {\n attrs[key] = value\n })\n }\n ops.push(op)\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr()\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content))\n }\n break\n }\n }\n n = n.right\n }\n packStr()\n }\n if (snapshot || prevSnapshot) {\n // snapshots are merged again after the transaction, so we need to keep the\n // transaction alive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot)\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot)\n }\n computeDelta()\n }, 'cleanup')\n } else {\n computeDelta()\n }\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes)\n if (!attributes) {\n attributes = {}\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v })\n }\n insertText(transaction, this, pos, text, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes))\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object | AbstractType} embed The Object that represents the embed.\n * @param {TextAttributes} [attributes] Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes) {\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes)\n insertText(transaction, this, pos, embed, attributes || {})\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes || {}))\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index, true), length)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length))\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, false)\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes))\n }\n }\n\n /**\n * Removes an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.removeAttribute(attributeName))\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {any} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.setAttribute(attributeName, attributeValue))\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {any} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes () {\n return typeMapGetAll(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nexport const readYText = _decoder => new YText()\n", "/**\n * @module YXml\n */\n\nimport {\n YXmlEvent,\n YXmlElement,\n AbstractType,\n typeListMap,\n typeListForEach,\n typeListInsertGenerics,\n typeListInsertGenericsAfter,\n typeListDelete,\n typeListToArray,\n YXmlFragmentRefID,\n callTypeObservers,\n transact,\n typeListGet,\n typeListSlice,\n warnPrematureAccess,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\nimport * as array from 'lib0/array'\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nexport class YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f\n this._root = root\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start)\n this._firstCall = true\n root.doc ?? warnPrematureAccess()\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode\n let type = n && n.content && /** @type {any} */ (n.content).type\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right\n break\n } else if (n.parent === this._root) {\n n = null\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nexport class YXmlFragment extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array|null}\n */\n this._prelimContent = []\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get firstChild () {\n const first = this._first\n return first ? first.content.getContent()[0] : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlFragment}\n */\n clone () {\n const el = new YXmlFragment()\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase()\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)\n const next = iterator.next()\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase()\n // @ts-ignore\n return array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction))\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment()\n if (binding !== undefined) {\n binding._createAssociation(fragment, this)\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null)\n })\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content)\n }\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at\n * @param {Array} content The array of content\n */\n insertAfter (ref, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const refItem = (ref && ref instanceof AbstractType) ? ref._item : ref\n typeListInsertGenericsAfter(transaction, this, refItem, content)\n })\n } else {\n const pc = /** @type {Array} */ (this._prelimContent)\n const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1\n if (index === 0 && ref !== null) {\n throw error.create('Reference item not found')\n }\n pc.splice(index, 0, ...content)\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length)\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content)\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {YXmlElement|YXmlText}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Returns a portion of this YXmlFragment into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Executes a provided function on once on every child element.\n *\n * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nexport const readYXmlFragment = _decoder => new YXmlFragment()\n", "import * as object from 'lib0/object'\n\nimport {\n YXmlFragment,\n transact,\n typeMapDelete,\n typeMapHas,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n typeMapGetAllSnapshot,\n typeListForEach,\n YXmlElementRefID,\n Snapshot, YXmlText, ContentType, AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @typedef {Object|number|null|Array|string|Uint8Array|AbstractType} ValueTypes\n */\n\n/**\n * An YXmlElement imitates the behavior of a\n * https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n *\n * @template {{ [key: string]: ValueTypes }} [KV={ [key: string]: string }]\n */\nexport class YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super()\n this.nodeName = nodeName\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map()\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value)\n })\n this._prelimAttrs = null\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlElement}\n */\n clone () {\n /**\n * @type {YXmlElement}\n */\n const el = new YXmlElement(this.nodeName)\n const attrs = this.getAttributes()\n object.forEach(attrs, (value, key) => {\n if (typeof value === 'string') {\n el.setAttribute(key, value)\n }\n })\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes()\n const stringBuilder = []\n const keys = []\n for (const key in attrs) {\n keys.push(key)\n }\n keys.sort()\n const keysLen = keys.length\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i]\n stringBuilder.push(key + '=\"' + attrs[key] + '\"')\n }\n const nodeName = this.nodeName.toLocaleLowerCase()\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {string} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName)\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that is to be set.\n * @param {KV[KEY]} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue)\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that identifies the\n * queried value.\n * @return {KV[KEY]|undefined} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns whether an attribute exists\n *\n * @param {string} attributeName The attribute name to check for existence.\n * @return {boolean} whether the attribute exists.\n *\n * @public\n */\n hasAttribute (attributeName) {\n return /** @type {any} */ (typeMapHas(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {{ [Key in Extract]?: KV[Key]}} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return /** @type {any} */ (snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this))\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n const value = attrs[key]\n if (typeof value === 'string') {\n dom.setAttribute(key, value)\n }\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding))\n })\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID)\n encoder.writeKey(this.nodeName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nexport const readYXmlElement = decoder => new YXmlElement(decoder.readKey())\n", "import {\n YEvent,\n YXmlText, YXmlElement, YXmlFragment, Transaction // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @extends YEvent\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nexport class YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.attributesChanged.add(sub)\n }\n })\n }\n}\n", "import {\n YMap,\n YXmlHookRefID,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2 // eslint-disable-line\n} from '../internals.js'\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nexport class YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super()\n /**\n * @type {string}\n */\n this.hookName = hookName\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlHook}\n */\n clone () {\n const el = new YXmlHook(this.hookName)\n this.forEach((value, key) => {\n el.set(key, value)\n })\n return el\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName]\n let dom\n if (hook !== undefined) {\n dom = hook.createDom(this)\n } else {\n dom = document.createElement(this.hookName)\n }\n dom.setAttribute('data-yjs-hook', this.hookName)\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID)\n encoder.writeKey(this.hookName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nexport const readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey())\n", "import {\n YText,\n YXmlTextRefID,\n ContentType, YXmlElement, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nexport class YXmlText extends YText {\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlText}\n */\n clone () {\n const text = new YXmlText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString())\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = []\n for (const nodeName in delta.attributes) {\n const attrs = []\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] })\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1)\n nestedNodes.push({ nodeName, attrs })\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1)\n // now convert to dom string\n let str = ''\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i]\n str += `<${node.nodeName}`\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j]\n str += ` ${attr.key}=\"${attr.value}\"`\n }\n str += '>'\n }\n str += delta.insert\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nexport const readYXmlText = decoder => new YXmlText()\n", "import {\n UpdateEncoderV1, UpdateEncoderV2, ID, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id\n this.length = length\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n", "import {\n AbstractStruct,\n addStruct,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nexport const structGCRefNumber = 0\n\n/**\n * @private\n */\nexport class GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.length -= offset\n }\n addStruct(transaction.doc.store, this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber)\n encoder.writeLen(this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentBinary}\n */\nexport const readContentBinary = decoder => new ContentBinary(decoder.readBuf())\n", "import {\n addToDeleteSet,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset)\n this.len = offset\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len)\n item.markDeleted()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentDeleted}\n */\nexport const readContentDeleted = decoder => new ContentDeleted(decoder.readLen())\n", "import {\n Doc, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @param {string} guid\n * @param {Object} opts\n */\nconst createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false })\n\n/**\n * @private\n */\nexport class ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.')\n }\n /**\n * @type {Doc}\n */\n this.doc = doc\n /**\n * @type {any}\n */\n const opts = {}\n this.opts = opts\n if (!doc.gc) {\n opts.gc = false\n }\n if (doc.autoLoad) {\n opts.autoLoad = true\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts))\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item\n transaction.subdocsAdded.add(this.doc)\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc)\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc)\n } else {\n transaction.subdocsRemoved.add(this.doc)\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid)\n encoder.writeAny(this.opts)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentDoc}\n */\nexport const readContentDoc = decoder => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()))\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentEmbed}\n */\nexport const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON())\n", "import {\n YText, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Item, StructStore, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key\n this.value = value\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} _offset\n * @return {ContentFormat}\n */\n splice (_offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} _right\n * @return {boolean}\n */\n mergeWith (_right) {\n return false\n }\n\n /**\n * @param {Transaction} _transaction\n * @param {Item} item\n */\n integrate (_transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n const p = /** @type {YText} */ (item.parent)\n p._searchMarker = null\n p._hasFormatting = true\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key)\n encoder.writeJSON(this.value)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentFormat}\n */\nexport const readContentFormat = decoder => new ContentFormat(decoder.readKey(), decoder.readJSON())\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c))\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentJSON}\n */\nexport const readContentJSON = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n const c = decoder.readString()\n if (c === 'undefined') {\n cs.push(undefined)\n } else {\n cs.push(JSON.parse(c))\n }\n }\n return new ContentJSON(cs)\n}\n", "import {\n UpdateEncoderV1, UpdateEncoderV2, UpdateDecoderV1, UpdateDecoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nimport * as env from 'lib0/environment'\nimport * as object from 'lib0/object'\n\nconst isDevMode = env.getVariable('node_env') === 'development'\n\nexport class ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n isDevMode && object.deepFreeze(arr)\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeAny(c)\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentAny}\n */\nexport const readContentAny = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny())\n }\n return new ContentAny(cs)\n}\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset))\n this.str = this.str.slice(0, offset)\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1)\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�'\n // replace right as well\n right.str = '�' + right.str.slice(1)\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset))\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentString}\n */\nexport const readContentString = decoder => new ContentString(decoder.readString())\n", "import {\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item, YEvent, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @type {Array>}\n * @private\n */\nexport const typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n]\n\nexport const YArrayRefID = 0\nexport const YMapRefID = 1\nexport const YTextRefID = 2\nexport const YXmlElementRefID = 3\nexport const YXmlFragmentRefID = 4\nexport const YXmlHookRefID = 5\nexport const YXmlTextRefID = 6\n\n/**\n * @private\n */\nexport class ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item)\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction)\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // This will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item)\n }\n item = item.right\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction)\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // same as above\n transaction._mergeStructs.push(item)\n }\n })\n transaction.changed.delete(this.type)\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start\n while (item !== null) {\n item.gc(store, true)\n item = item.right\n }\n this.type._start = null\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true)\n item = item.left\n }\n })\n this.type._map = new Map()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentType}\n */\nexport const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder))\n", "import {\n GC,\n getState,\n AbstractStruct,\n replaceStruct,\n addStruct,\n addToDeleteSet,\n findRootTypeKey,\n compareIDs,\n getItem,\n getItemCleanEnd,\n getItemCleanStart,\n readContentDeleted,\n readContentBinary,\n readContentJSON,\n readContentAny,\n readContentString,\n readContentEmbed,\n readContentDoc,\n createID,\n readContentFormat,\n readContentType,\n addChangedTypeToTransaction,\n isDeleted,\n StackItem, DeleteSet, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ContentType, ContentDeleted, StructStore, ID, AbstractType, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\nimport * as binary from 'lib0/binary'\nimport * as array from 'lib0/array'\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nexport const followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id\n let diff = 0\n let item\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff)\n }\n item = getItem(store, nextID)\n diff = nextID.clock - item.id.clock\n nextID = item.redone\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n}\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nexport const keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep\n item = /** @type {AbstractType} */ (item.parent)._item\n }\n}\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nexport const splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n if (leftItem.deleted) {\n rightItem.markDeleted()\n }\n if (leftItem.keep) {\n rightItem.keep = true\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff)\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem)\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem)\n }\n leftItem.length = diff\n return rightItem\n}\n\n/**\n * @param {Array} stack\n * @param {ID} id\n */\nconst isDeletedByUndoStack = (stack, id) => array.some(stack, /** @param {StackItem} s */ s => isDeleted(s.deletions, id))\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n * @param {DeleteSet} itemsToDelete\n * @param {boolean} ignoreRemoteMapChanges\n * @param {import('../utils/UndoManager.js').UndoManager} um\n *\n * @return {Item|null}\n *\n * @private\n */\nexport const redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {\n const doc = transaction.doc\n const store = doc.store\n const ownClientID = doc.clientID\n const redone = item.redone\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item\n /**\n * @type {Item|null}\n */\n let left = null\n /**\n * @type {Item|null}\n */\n let right\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true) {\n // try to undo parent if it will be undone anyway\n if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {\n return null\n }\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone)\n }\n }\n const parentType = parentItem === null ? /** @type {AbstractType} */ (item.parent) : /** @type {ContentType} */ (parentItem.content).type\n\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left\n right = item\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone)\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace\n break\n }\n left = left.left\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone)\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace\n break\n }\n right = right.right\n }\n } else {\n right = null\n if (item.right && !ignoreRemoteMapChanges) {\n left = item\n // Iterate right while right is in itemsToDelete\n // If it is intended to delete right while item is redone, we can expect that item should replace right.\n while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) {\n left = left.right\n // follow redone\n while (left.redone) left = getItemCleanStart(transaction, left.redone)\n }\n if (left && left.right !== null) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n } else {\n left = parentType._map.get(item.parentSub) || null\n }\n }\n const nextClock = getState(store, ownClientID)\n const nextId = createID(ownClientID, nextClock)\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentType,\n item.parentSub,\n item.content.copy()\n )\n item.redone = nextId\n keepItem(redoneItem, true)\n redoneItem.integrate(transaction, 0)\n return redoneItem\n}\n\n/**\n * Abstract class that represents any content.\n */\nexport class Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength())\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub\n /**\n * If this type's effect is redone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null\n /**\n * @type {AbstractContent}\n */\n this.content = content\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin)\n this.origin = this.left.lastId\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin)\n this.rightOrigin = this.right.id\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null\n } else if (!this.parent) {\n // only set parent if this shouldn't be garbage collected\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent\n this.parentSub = this.left.parentSub\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent\n this.parentSub = this.right.parentSub\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent)\n if (parentItem.constructor === GC) {\n this.parent = null\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1))\n this.origin = this.left.lastId\n this.content = this.content.splice(offset)\n this.length -= offset\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left\n\n /**\n * @type {Item|null}\n */\n let o\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (o !== null && o.left !== null) {\n o = o.left\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set()\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set()\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o)\n conflictingItems.add(o)\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o\n conflictingItems.clear()\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o\n conflictingItems.clear()\n }\n } else {\n break\n }\n o = o.right\n }\n this.left = left\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right\n this.right = right\n this.left.right = this\n } else {\n let r\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (r !== null && r.left !== null) {\n r = r.left\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this\n }\n this.right = r\n }\n if (this.right !== null) {\n this.right.left = this\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this)\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction)\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length\n }\n addStruct(transaction.doc.store, this)\n this.content.integrate(transaction, this)\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub)\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction)\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0)\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left\n while (n !== null && n.deleted) {\n n = n.left\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n this.constructor === right.constructor &&\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n const searchMarker = /** @type {AbstractType} */ (this.parent)._searchMarker\n if (searchMarker) {\n searchMarker.forEach(marker => {\n if (marker.p === right) {\n // right is going to be \"forgotten\" so we need to update the marker\n marker.p = this\n // adjust marker index\n if (!this.deleted && this.countable) {\n marker.index -= this.length\n }\n }\n })\n }\n if (right.keep) {\n this.keep = true\n }\n this.right = right.right\n if (this.right !== null) {\n this.right.left = this\n }\n this.length += right.length\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent)\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length\n }\n this.markDeleted()\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length)\n addChangedTypeToTransaction(transaction, parent, this.parentSub)\n this.content.delete(transaction)\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store)\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length))\n } else {\n this.content = new ContentDeleted(this.length)\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin\n const rightOrigin = this.rightOrigin\n const parentSub = this.parentSub\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6) // parentSub is non-null\n encoder.writeInfo(info)\n if (origin !== null) {\n encoder.writeLeftID(origin)\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin)\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent)\n if (parent._item !== undefined) {\n const parentItem = parent._item\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent)\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(ykey)\n } else {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parentItem.id)\n }\n } else if (parent.constructor === String) { // this edge case was added by differential updates\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(parent)\n } else if (parent.constructor === ID) {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parent)\n } else {\n error.unexpectedCase()\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub)\n }\n }\n this.content.write(encoder, offset)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {number} info\n */\nexport const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder)\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nexport const contentRefs = [\n () => { error.unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc, // 9\n () => { error.unexpectedCase() } // 10 - Skip is not ItemContent\n]\n\n/**\n * Do not implement this class!\n */\nexport class AbstractContent {\n /**\n * @return {number}\n */\n getLength () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Should return false if this Item is some kind of meta information\n * (e.g. format information).\n *\n * * Whether this Item should be addressable via `yarray.get(i)`\n * * Whether this Item should be counted when computing yarray.length\n *\n * @return {boolean}\n */\n isCountable () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractContent}\n */\n copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {number} _offset\n * @return {AbstractContent}\n */\n splice (_offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractContent} _right\n * @return {boolean}\n */\n mergeWith (_right) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} _transaction\n * @param {Item} _item\n */\n integrate (_transaction, _item) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} _transaction\n */\n delete (_transaction) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {StructStore} _store\n */\n gc (_store) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder\n * @param {number} _offset\n */\n write (_encoder, _offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n getRef () {\n throw error.methodUnimplemented()\n }\n}\n", "import {\n AbstractStruct,\n UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\nimport * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nexport const structSkipRefNumber = 10\n\n/**\n * @private\n */\nexport class Skip extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {Skip} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n // skip structs cannot be integrated\n error.unexpectedCase()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structSkipRefNumber)\n // write as VarUint because Skips can't make use of predictable length-encoding\n encoding.writeVarUint(encoder.restEncoder, this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n", "/** eslint-env browser */\n\nexport {\n Doc,\n Transaction,\n YArray as Array,\n YMap as Map,\n YText as Text,\n YXmlText as XmlText,\n YXmlHook as XmlHook,\n YXmlElement as XmlElement,\n YXmlFragment as XmlFragment,\n YXmlEvent,\n YMapEvent,\n YArrayEvent,\n YTextEvent,\n YEvent,\n Item,\n AbstractStruct,\n GC,\n Skip,\n ContentBinary,\n ContentDeleted,\n ContentDoc,\n ContentEmbed,\n ContentFormat,\n ContentJSON,\n ContentAny,\n ContentString,\n ContentType,\n AbstractType,\n getTypeChildren,\n createRelativePositionFromTypeIndex,\n createRelativePositionFromJSON,\n createAbsolutePositionFromRelativePosition,\n compareRelativePositions,\n AbsolutePosition,\n RelativePosition,\n ID,\n createID,\n compareIDs,\n getState,\n Snapshot,\n createSnapshot,\n createDeleteSet,\n createDeleteSetFromStructStore,\n cleanupYTextFormatting,\n snapshot,\n emptySnapshot,\n findRootTypeKey,\n findIndexSS,\n getItem,\n typeListToArraySnapshot,\n typeMapGetSnapshot,\n typeMapGetAllSnapshot,\n createDocFromSnapshot,\n iterateDeletedStructs,\n applyUpdate,\n applyUpdateV2,\n readUpdate,\n readUpdateV2,\n encodeStateAsUpdate,\n encodeStateAsUpdateV2,\n encodeStateVector,\n UndoManager,\n decodeSnapshot,\n encodeSnapshot,\n decodeSnapshotV2,\n encodeSnapshotV2,\n decodeStateVector,\n logUpdate,\n logUpdateV2,\n decodeUpdate,\n decodeUpdateV2,\n relativePositionToJSON,\n isDeleted,\n isParentOf,\n equalSnapshots,\n PermanentUserData, // @TODO experimental\n tryGc,\n transact,\n AbstractConnector,\n logType,\n mergeUpdates,\n mergeUpdatesV2,\n parseUpdateMeta,\n parseUpdateMetaV2,\n encodeStateVectorFromUpdate,\n encodeStateVectorFromUpdateV2,\n encodeRelativePosition,\n decodeRelativePosition,\n diffUpdate,\n diffUpdateV2,\n convertUpdateFormatV1ToV2,\n convertUpdateFormatV2ToV1,\n obfuscateUpdate,\n obfuscateUpdateV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n UpdateDecoderV1,\n UpdateDecoderV2,\n equalDeleteSets,\n mergeDeleteSets,\n snapshotContainsUpdate\n} from './internals.js'\n\nconst glo = /** @type {any} */ (typeof globalThis !== 'undefined'\n ? globalThis\n : typeof window !== 'undefined'\n ? window\n // @ts-ignore\n : typeof global !== 'undefined' ? global : {})\n\nconst importIdentifier = '__ $YJS$ __'\n\nif (glo[importIdentifier] === true) {\n /**\n * Dear reader of this message. Please take this seriously.\n *\n * If you see this message, make sure that you only import one version of Yjs. In many cases,\n * your package manager installs two versions of Yjs that are used by different packages within your project.\n * Another reason for this message is that some parts of your project use the commonjs version of Yjs\n * and others use the EcmaScript version of Yjs.\n *\n * This often leads to issues that are hard to debug. We often need to perform constructor checks,\n * e.g. `struct instanceof GC`. If you imported different versions of Yjs, it is impossible for us to\n * do the constructor checks anymore - which might break the CRDT algorithm.\n *\n * https://github.com/yjs/yjs/issues/438\n */\n console.error('Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438')\n}\nglo[importIdentifier] = true\n", "/* eslint-env browser */\n\n/**\n * Tiny websocket connection handler.\n *\n * Implements exponential backoff reconnects, ping/pong, and a nice event system using [lib0/observable].\n *\n * @module websocket\n */\n\nimport { Observable } from './observable.js'\nimport * as time from './time.js'\nimport * as math from './math.js'\n\nconst reconnectTimeoutBase = 1200\nconst maxReconnectTimeout = 2500\n// @todo - this should depend on awareness.outdatedTime\nconst messageReconnectTimeout = 30000\n\n/**\n * @param {WebsocketClient} wsclient\n */\nconst setupWS = (wsclient) => {\n if (wsclient.shouldConnect && wsclient.ws === null) {\n const websocket = new WebSocket(wsclient.url)\n const binaryType = wsclient.binaryType\n /**\n * @type {any}\n */\n let pingTimeout = null\n if (binaryType) {\n websocket.binaryType = binaryType\n }\n wsclient.ws = websocket\n wsclient.connecting = true\n wsclient.connected = false\n websocket.onmessage = event => {\n wsclient.lastMessageReceived = time.getUnixTime()\n const data = event.data\n const message = typeof data === 'string' ? JSON.parse(data) : data\n if (message && message.type === 'pong') {\n clearTimeout(pingTimeout)\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n wsclient.emit('message', [message, wsclient])\n }\n /**\n * @param {any} error\n */\n const onclose = error => {\n if (wsclient.ws !== null) {\n wsclient.ws = null\n wsclient.connecting = false\n if (wsclient.connected) {\n wsclient.connected = false\n wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient])\n } else {\n wsclient.unsuccessfulReconnects++\n }\n // Start with no reconnect timeout and increase timeout by\n // log10(wsUnsuccessfulReconnects).\n // The idea is to increase reconnect timeout slowly and have no reconnect\n // timeout at the beginning (log(1) = 0)\n setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient)\n }\n clearTimeout(pingTimeout)\n }\n const sendPing = () => {\n if (wsclient.ws === websocket) {\n wsclient.send({\n type: 'ping'\n })\n }\n }\n websocket.onclose = () => onclose(null)\n websocket.onerror = error => onclose(error)\n websocket.onopen = () => {\n wsclient.lastMessageReceived = time.getUnixTime()\n wsclient.connecting = false\n wsclient.connected = true\n wsclient.unsuccessfulReconnects = 0\n wsclient.emit('connect', [{ type: 'connect' }, wsclient])\n // set ping\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n }\n}\n\n/**\n * @deprecated\n * @extends Observable\n */\nexport class WebsocketClient extends Observable {\n /**\n * @param {string} url\n * @param {object} opts\n * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`\n */\n constructor (url, { binaryType } = {}) {\n super()\n this.url = url\n /**\n * @type {WebSocket?}\n */\n this.ws = null\n this.binaryType = binaryType || null\n this.connected = false\n this.connecting = false\n this.unsuccessfulReconnects = 0\n this.lastMessageReceived = 0\n /**\n * Whether to connect to other peers or not\n * @type {boolean}\n */\n this.shouldConnect = true\n this._checkInterval = setInterval(() => {\n if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) {\n // no message received in a long time - not even your own awareness\n // updates (which are updated every 15 seconds)\n /** @type {WebSocket} */ (this.ws).close()\n }\n }, messageReconnectTimeout / 2)\n setupWS(this)\n }\n\n /**\n * @param {any} message\n */\n send (message) {\n if (this.ws) {\n this.ws.send(JSON.stringify(message))\n }\n }\n\n destroy () {\n clearInterval(this._checkInterval)\n this.disconnect()\n super.destroy()\n }\n\n disconnect () {\n this.shouldConnect = false\n if (this.ws !== null) {\n this.ws.close()\n }\n }\n\n connect () {\n this.shouldConnect = true\n if (!this.connected && this.ws === null) {\n setupWS(this)\n }\n }\n}\n", "/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n", "/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n", "(function(e){if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();else if(\"function\"==typeof define&&define.amd)define([],e);else{var t;t=\"undefined\"==typeof window?\"undefined\"==typeof global?\"undefined\"==typeof self?this:self:global:window,t.SimplePeer=e()}})(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function(){function d(s,e,n){function t(o,i){if(!e[o]){if(!s[o]){var l=\"function\"==typeof require&&require;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error(\"Cannot find module '\"+o+\"'\");throw c.code=\"MODULE_NOT_FOUND\",c}var a=e[o]={exports:{}};s[o][0].call(a.exports,function(e){var r=s[o][1][e];return t(r||e)},a,a.exports,d,s,e,n)}return e[o].exports}for(var r=\"function\"==typeof require&&require,a=0;a>16,l[c++]=255&t>>8,l[c++]=255&t;return 2===s&&(t=u[e.charCodeAt(n)]<<2|u[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===s&&(t=u[e.charCodeAt(n)]<<10|u[e.charCodeAt(n+1)]<<4|u[e.charCodeAt(n+2)]>>2,l[c++]=255&t>>8,l[c++]=255&t),l}function d(e){return c[63&e>>18]+c[63&e>>12]+c[63&e>>6]+c[63&e]}function s(e,t,n){for(var r,a=[],o=t;ol?l:d+o));return 1===r?(t=e[n-1],a.push(c[t>>2]+c[63&t<<4]+\"==\")):2===r&&(t=(e[n-2]<<8)+e[n-1],a.push(c[t>>10]+c[63&t>>4]+c[63&t<<2]+\"=\")),a.join(\"\")}n.byteLength=function(e){var t=r(e),n=t[0],a=t[1];return 3*(n+a)/4-a},n.toByteArray=o,n.fromByteArray=l;for(var c=[],u=[],p=\"undefined\"==typeof Uint8Array?Array:Uint8Array,f=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",g=0,_=f.length;g<_;++g)c[g]=f[g],u[f.charCodeAt(g)]=g;u[45]=62,u[95]=63},{}],2:[function(){},{}],3:[function(e,t,n){(function(){(function(){/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */'use strict';var t=String.fromCharCode,o=Math.min;function d(e){if(2147483647e)throw new RangeError(\"The value \\\"\"+e+\"\\\" is invalid for option \\\"size\\\"\")}function u(e,t,n){return c(e),0>=e?d(e):void 0===t?d(e):\"string\"==typeof n?d(e).fill(t,n):d(e).fill(t)}function p(e){return c(e),d(0>e?0:0|m(e))}function f(e,t){if((\"string\"!=typeof t||\"\"===t)&&(t=\"utf8\"),!s.isEncoding(t))throw new TypeError(\"Unknown encoding: \"+t);var n=0|b(e,t),r=d(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function g(e){for(var t=0>e.length?0:0|m(e.length),n=d(t),r=0;rt||e.byteLength=2147483647)throw new RangeError(\"Attempt to allocate Buffer larger than maximum size: 0x\"+2147483647 .toString(16)+\" bytes\");return 0|e}function b(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(e,ArrayBuffer))return e.byteLength;if(\"string\"!=typeof e)throw new TypeError(\"The \\\"string\\\" argument must be one of type string, Buffer, or ArrayBuffer. Received type \"+typeof e);var n=e.length,r=2>>1;case\"base64\":return z(e).length;default:if(a)return r?-1:H(e).length;t=(\"\"+t).toLowerCase(),a=!0;}}function y(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return\"\";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return\"\";if(n>>>=0,t>>>=0,n<=t)return\"\";for(e||(e=\"utf8\");;)switch(e){case\"hex\":return P(this,t,n);case\"utf8\":case\"utf-8\":return x(this,t,n);case\"ascii\":return D(this,t,n);case\"latin1\":case\"binary\":return I(this,t,n);case\"base64\":return A(this,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return M(this,t,n);default:if(r)throw new TypeError(\"Unknown encoding: \"+e);e=(e+\"\").toLowerCase(),r=!0;}}function C(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function R(e,t,n,r,a){if(0===e.length)return-1;if(\"string\"==typeof n?(r=n,n=0):2147483647n&&(n=-2147483648),n=+n,X(n)&&(n=a?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(0>n)if(a)n=0;else return-1;if(\"string\"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:E(e,t,n,r,a);if(\"number\"==typeof t)return t&=255,\"function\"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):E(e,[t],n,r,a);throw new TypeError(\"val must be string, number or Buffer\")}function E(e,t,n,r,a){function o(e,t){return 1===d?e[t]:e.readUInt16BE(t*d)}var d=1,s=e.length,l=t.length;if(void 0!==r&&(r=(r+\"\").toLowerCase(),\"ucs2\"===r||\"ucs-2\"===r||\"utf16le\"===r||\"utf-16le\"===r)){if(2>e.length||2>t.length)return-1;d=2,s/=2,l/=2,n/=2}var c;if(a){var u=-1;for(c=n;cs&&(n=s-l),c=n;0<=c;c--){for(var p=!0,f=0;fa&&(r=a)):r=a;var o=t.length;r>o/2&&(r=o/2);for(var d,s=0;sd&&(s=d):2===l?(c=e[a+1],128==(192&c)&&(f=(31&d)<<6|63&c,127f||57343f&&(s=f))):void 0}null===s?(s=65533,l=1):65535>>10),s=56320|1023&s),r.push(s),a+=l}return N(r)}function N(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r=\"\",a=0;at)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var a=\"\",o=t;oe)throw new RangeError(\"offset is not uint\");if(e+t>n)throw new RangeError(\"Trying to access beyond buffer length\")}function F(e,t,n,r,a,o){if(!s.isBuffer(e))throw new TypeError(\"\\\"buffer\\\" argument must be a Buffer instance\");if(t>a||te.length)throw new RangeError(\"Index out of range\")}function B(e,t,n,r){if(n+r>e.length)throw new RangeError(\"Index out of range\");if(0>n)throw new RangeError(\"Index out of range\")}function U(e,t,n,r,a){return t=+t,n>>>=0,a||B(e,t,n,4,34028234663852886e22,-34028234663852886e22),J.write(e,t,n,r,23,4),n+4}function j(e,t,n,r,a){return t=+t,n>>>=0,a||B(e,t,n,8,17976931348623157e292,-17976931348623157e292),J.write(e,t,n,r,52,8),n+8}function q(e){if(e=e.split(\"=\")[0],e=e.trim().replace(Q,\"\"),2>e.length)return\"\";for(;0!=e.length%4;)e+=\"=\";return e}function W(e){return 16>e?\"0\"+e.toString(16):e.toString(16)}function H(e,t){t=t||1/0;for(var n,r=e.length,a=null,o=[],d=0;dn){if(!a){if(56319n){-1<(t-=3)&&o.push(239,191,189),a=n;continue}n=(a-55296<<10|n-56320)+65536}else a&&-1<(t-=3)&&o.push(239,191,189);if(a=null,128>n){if(0>(t-=1))break;o.push(n)}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;o.push(224|n>>12,128|63&n>>6,128|63&n)}else if(1114112>n){if(0>(t-=4))break;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}else throw new Error(\"Invalid code point\")}return o}function Y(e){for(var t=[],n=0;n(t-=2));++d)n=e.charCodeAt(d),r=n>>8,a=n%256,o.push(a),o.push(r);return o}function z(e){return $.toByteArray(q(e))}function G(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!==e}var $=e(\"base64-js\"),J=e(\"ieee754\");n.Buffer=s,n.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},n.INSPECT_MAX_BYTES=50;n.kMaxLength=2147483647,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||\"undefined\"==typeof console||\"function\"!=typeof console.error||console.error(\"This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.\"),Object.defineProperty(s.prototype,\"parent\",{enumerable:!0,get:function(){return s.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(s.prototype,\"offset\",{enumerable:!0,get:function(){return s.isBuffer(this)?this.byteOffset:void 0}}),\"undefined\"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,n){return l(e,t,n)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,n){return u(e,t,n)},s.allocUnsafe=function(e){return p(e)},s.allocUnsafeSlow=function(e){return p(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(K(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError(\"The \\\"buf1\\\", \\\"buf2\\\" arguments must be one of type Buffer or Uint8Array\");if(e===t)return 0;for(var n=e.length,r=t.length,d=0,l=o(n,r);dt&&(e+=\" ... \"),\"\"},s.prototype.compare=function(e,t,n,r,a){if(K(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError(\"The \\\"target\\\" argument must be one of type Buffer or Uint8Array. Received type \"+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),0>t||n>e.length||0>r||a>this.length)throw new RangeError(\"out of range index\");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var d=a-r,l=n-t,c=o(d,l),u=this.slice(r,a),p=e.slice(t,n),f=0;f>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r=\"utf8\")):(r=n,n=void 0);else throw new Error(\"Buffer.write(string, encoding, offset[, length]) is no longer supported\");var a=this.length-t;if((void 0===n||n>a)&&(n=a),0n||0>t)||t>this.length)throw new RangeError(\"Attempt to write outside buffer bounds\");r||(r=\"utf8\");for(var o=!1;;)switch(r){case\"hex\":return w(this,e,t,n);case\"utf8\":case\"utf-8\":return S(this,e,t,n);case\"ascii\":return T(this,e,t,n);case\"latin1\":case\"binary\":return v(this,e,t,n);case\"base64\":return k(this,e,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return L(this,e,t,n);default:if(o)throw new TypeError(\"Unknown encoding: \"+r);r=(\"\"+r).toLowerCase(),o=!0;}},s.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}};s.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,0>e?(e+=n,0>e&&(e=0)):e>n&&(e=n),0>t?(t+=n,0>t&&(t=0)):t>n&&(t=n),t>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e],a=1,o=0;++o>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e+--t],a=1;0>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var a=this[e],o=1,d=0;++d=o&&(a-=r(2,8*t)),a},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var a=t,o=1,d=this[e+--a];0=o&&(d-=r(2,8*t)),d},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),J.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),J.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),J.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),J.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,n,a){if(e=+e,t>>>=0,n>>>=0,!a){var o=r(2,8*n)-1;F(this,e,t,n,o,0)}var d=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!a){var o=r(2,8*n)-1;F(this,e,t,n,o,0)}var d=n-1,s=1;for(this[t+d]=255&e;0<=--d&&(s*=256);)this[t+d]=255&e/s;return t+n},s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);F(this,e,t,n,o-1,-o)}var d=0,s=1,l=0;for(this[t]=255&e;++de&&0===l&&0!==this[t+d-1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},s.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);F(this,e,t,n,o-1,-o)}var d=n-1,s=1,l=0;for(this[t+d]=255&e;0<=--d&&(s*=256);)0>e&&0===l&&0!==this[t+d+1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError(\"argument should be a Buffer\");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0t)throw new RangeError(\"targetStart out of bounds\");if(0>n||n>=this.length)throw new RangeError(\"Index out of range\");if(0>r)throw new RangeError(\"sourceEnd out of bounds\");r>this.length&&(r=this.length),e.length-ta||\"latin1\"===r)&&(e=a)}}else\"number\"==typeof e&&(e&=255);if(0>t||this.length>>=0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(\"number\"==typeof e)for(o=t;o{\"%%\"===e||(r++,\"%c\"===e&&(a=r))}),e.splice(a,0,n)},n.save=function(e){try{e?n.storage.setItem(\"debug\",e):n.storage.removeItem(\"debug\")}catch(e){}},n.load=r,n.useColors=function(){return!!(\"undefined\"!=typeof window&&window.process&&(\"renderer\"===window.process.type||window.process.__nwjs))||!(\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))&&(\"undefined\"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||\"undefined\"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)&&31<=parseInt(RegExp.$1,10)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"))}})(),n.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],n.log=console.debug||console.log||(()=>{}),t.exports=e(\"./common\")(n);const{formatters:o}=t.exports;o.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}).call(this)}).call(this,e(\"_process\"))},{\"./common\":5,_process:12}],5:[function(e,t){t.exports=function(t){function r(e){function t(...e){if(!t.enabled)return;const a=t,o=+new Date,i=o-(n||o);a.diff=i,a.prev=n,a.curr=o,n=o,e[0]=r.coerce(e[0]),\"string\"!=typeof e[0]&&e.unshift(\"%O\");let d=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if(\"%%\"===t)return\"%\";d++;const o=r.formatters[n];if(\"function\"==typeof o){const n=e[d];t=o.call(a,n),e.splice(d,1),d--}return t}),r.formatArgs.call(a,e);const s=a.log||r.log;s.apply(a,e)}let n,o=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=a,t.destroy=r.destroy,Object.defineProperty(t,\"enabled\",{enumerable:!0,configurable:!1,get:()=>null===o?r.enabled(e):o,set:e=>{o=e}}),\"function\"==typeof r.init&&r.init(t),t}function a(e,t){const n=r(this.namespace+(\"undefined\"==typeof t?\":\":t)+e);return n.log=this.log,n}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\\.\\*\\?$/,\"*\")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(o),...r.skips.map(o).map(e=>\"-\"+e)].join(\",\");return r.enable(\"\"),e},r.enable=function(e){r.save(e),r.names=[],r.skips=[];let t;const n=(\"string\"==typeof e?e:\"\").split(/[\\s,]+/),a=n.length;for(t=0;t{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let t=0;for(let n=0;nd&&!l.warned){l.warned=!0;var c=new Error(\"Possible EventEmitter memory leak detected. \"+l.length+\" \"+(t+\" listeners added. Use emitter.setMaxListeners() to increase limit\"));c.name=\"MaxListenersExceededWarning\",c.emitter=e,c.type=t,c.count=l.length,n(c)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function s(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},a=d.bind(r);return a.listener=n,r.wrapFn=a,a}function l(e,t,n){var r=e._events;if(r===void 0)return[];var a=r[t];return void 0===a?[]:\"function\"==typeof a?n?[a.listener||a]:[a]:n?f(a):u(a,a.length)}function c(e){var t=this._events;if(t!==void 0){var n=t[e];if(\"function\"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function u(e,t){for(var n=Array(t),r=0;re||y(e))throw new RangeError(\"The value of \\\"defaultMaxListeners\\\" is out of range. It must be a non-negative number. Received \"+e+\".\");C=e}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if(\"number\"!=typeof e||0>e||y(e))throw new RangeError(\"The value of \\\"n\\\" is out of range. It must be a non-negative number. Received \"+e+\".\");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;no)return this;0===o?n.shift():p(n,o),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit(\"removeListener\",e,s||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,void 0===n)return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var a,o=Object.keys(n);for(r=0;r */o.read=function(t,n,a,o,l){var c,u,p=8*l-o-1,f=(1<>1,_=-7,h=a?l-1:0,b=a?-1:1,d=t[n+h];for(h+=b,c=d&(1<<-_)-1,d>>=-_,_+=p;0<_;c=256*c+t[n+h],h+=b,_-=8);for(u=c&(1<<-_)-1,c>>=-_,_+=o;0<_;u=256*u+t[n+h],h+=b,_-=8);if(0===c)c=1-g;else{if(c===f)return u?NaN:(d?-1:1)*(1/0);u+=r(2,o),c-=g}return(d?-1:1)*u*r(2,c-o)},o.write=function(a,o,l,u,p,f){var h,b,y,g=Math.LN2,_=Math.log,C=8*f-p-1,R=(1<>1,w=23===p?r(2,-24)-r(2,-77):0,S=u?0:f-1,T=u?1:-1,d=0>o||0===o&&0>1/o?1:0;for(o=n(o),isNaN(o)||o===1/0?(b=isNaN(o)?1:0,h=R):(h=t(_(o)/g),1>o*(y=r(2,-h))&&(h--,y*=2),o+=1<=h+E?w/y:w*r(2,1-E),2<=o*y&&(h++,y/=2),h+E>=R?(b=0,h=R):1<=h+E?(b=(o*y-1)*r(2,p),h+=E):(b=o*r(2,E-1)*r(2,p),h=0));8<=p;a[l+S]=255&b,S+=T,b/=256,p-=8);for(h=h<=1.5*a?\"s\":\"\")}var l=24*(60*60000);t.exports=function(e,t){t=t||{};var n=typeof e;if(\"string\"==n&&0 */let n;t.exports=\"function\"==typeof queueMicrotask?queueMicrotask.bind(\"undefined\"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,\"undefined\"==typeof global?\"undefined\"==typeof self?\"undefined\"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){'use strict';var a=e(\"safe-buffer\").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError(\"requested too many random bytes\");var r=a.allocUnsafe(e);if(0n?0:+n,t.length)===t}function i(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function d(e,t,n){return\"number\"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}var s={};r(\"ERR_INVALID_OPT_VALUE\",function(e,t){return\"The value \\\"\"+t+\"\\\" is invalid for option \\\"\"+e+\"\\\"\"},TypeError),r(\"ERR_INVALID_ARG_TYPE\",function(e,t,n){var r;\"string\"==typeof t&&o(t,\"not \")?(r=\"must not be\",t=t.replace(/^not /,\"\")):r=\"must be\";var s;if(i(e,\" argument\"))s=\"The \".concat(e,\" \").concat(r,\" \").concat(a(t,\"type\"));else{var l=d(e,\".\")?\"property\":\"argument\";s=\"The \\\"\".concat(e,\"\\\" \").concat(l,\" \").concat(r,\" \").concat(a(t,\"type\"))}return s+=\". Received type \".concat(typeof n),s},TypeError),r(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\"),r(\"ERR_METHOD_NOT_IMPLEMENTED\",function(e){return\"The \"+e+\" method is not implemented\"}),r(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\"),r(\"ERR_STREAM_DESTROYED\",function(e){return\"Cannot call \"+e+\" after a stream was destroyed\"}),r(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\"),r(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\"),r(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\"),r(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),r(\"ERR_UNKNOWN_ENCODING\",function(e){return\"Unknown encoding: \"+e},TypeError),r(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\"),t.exports.codes=s},{}],16:[function(e,t){(function(n){(function(){'use strict';function r(e){return this instanceof r?void(d.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once(\"end\",a)))):new r(e)}function a(){this._writableState.ended||n.nextTick(o,this)}function o(e){e.end()}var i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var d=e(\"./_stream_readable\"),s=e(\"./_stream_writable\");e(\"inherits\")(r,d);for(var l,c=i(s.prototype),u=0;u>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=p(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function g(e,t){if(x(\"onEofChunk\"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?_(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,h(e)))}}function _(e){var t=e._readableState;x(\"emitReadable\",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(x(\"emitReadable\",t.flowing),t.emittedReadable=!0,n.nextTick(h,e))}function h(e){var t=e._readableState;x(\"emitReadable_\",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(\"readable\"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,S(e)}function m(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(b,e,t))}function b(e,t){for(;!t.reading&&!t.ended&&(t.length=t.length?(n=t.decoder?t.buffer.join(\"\"):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function v(e){var t=e._readableState;x(\"endReadable\",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(k,t,e))}function k(e,t){if(x(\"endReadableNT\",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit(\"end\"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function L(e,t){for(var n=0,r=e.length;n=t.highWaterMark)||t.ended))return x(\"read: emitReadable\",t.length,t.ended),0===t.length&&t.ended?v(this):_(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&v(this),null;var a=t.needReadable;x(\"need readable\",a),(0===t.length||t.length-e>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:\"consume\",value:function(e,t){var n;return eo.length?o.length:e;if(a+=i===o.length?o:o.slice(0,e),e-=i,0===e){i===o.length?(++r,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=o.slice(i));break}++r}return this.length-=r,a}},{key:\"_getBuffer\",value:function(e){var t=u.allocUnsafe(e),r=this.head,a=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),e-=i,0===e){i===o.length?(++a,this.head=r.next?r.next:this.tail=null):(this.head=r,r.data=o.slice(i));break}++a}return this.length-=a,t}},{key:g,value:function(e,t){return f(this,r({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){'use strict';function n(e,t){a(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(\"close\")}function a(e,t){e.emit(\"error\",t)}t.exports={destroy:function(t,o){var i=this,d=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return d||s?(o?o(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!o&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(r,i):(i._writableState.errorEmitted=!0,e.nextTick(n,i,t)):e.nextTick(n,i,t):o?(e.nextTick(r,i),o(t)):e.nextTick(r,i)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(\"error\",t)}}}).call(this)}).call(this,e(\"_process\"))},{_process:12}],24:[function(e,t){'use strict';function n(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),a=0;at.length)throw new u(\"streams\");var a,l=t.map(function(e,n){var d=nd){var s=i?o:\"highWaterMark\";throw new a(s,d)}return t(d)}return e.objectMode?16:16384}}},{\"../../../errors\":15}],28:[function(e,t){t.exports=e(\"events\").EventEmitter},{events:7}],29:[function(e,t,n){n=t.exports=e(\"./lib/_stream_readable.js\"),n.Stream=n,n.Readable=n,n.Writable=e(\"./lib/_stream_writable.js\"),n.Duplex=e(\"./lib/_stream_duplex.js\"),n.Transform=e(\"./lib/_stream_transform.js\"),n.PassThrough=e(\"./lib/_stream_passthrough.js\"),n.finished=e(\"./lib/internal/streams/end-of-stream.js\"),n.pipeline=e(\"./lib/internal/streams/pipeline.js\")},{\"./lib/_stream_duplex.js\":16,\"./lib/_stream_passthrough.js\":17,\"./lib/_stream_readable.js\":18,\"./lib/_stream_transform.js\":19,\"./lib/_stream_writable.js\":20,\"./lib/internal/streams/end-of-stream.js\":24,\"./lib/internal/streams/pipeline.js\":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return i(e,t,n)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var o=e(\"buffer\"),i=o.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=a),a.prototype=Object.create(i.prototype),r(i,a),a.from=function(e,t,n){if(\"number\"==typeof e)throw new TypeError(\"Argument must not be a number\");return i(e,t,n)},a.alloc=function(e,t,n){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");var r=i(e);return void 0===t?r.fill(0):\"string\"==typeof n?r.fill(t,n):r.fill(t),r},a.allocUnsafe=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return i(e)},a.allocUnsafeSlow=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return o.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){'use strict';function r(e){if(!e)return\"utf8\";for(var t;;)switch(e){case\"utf8\":case\"utf-8\":return\"utf8\";case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return\"utf16le\";case\"latin1\":case\"binary\":return\"latin1\";case\"base64\":case\"ascii\":case\"hex\":return e;default:if(t)return;e=(\"\"+e).toLowerCase(),t=!0;}}function a(e){var t=r(e);if(\"string\"!=typeof t&&(m.isEncoding===b||!b(e)))throw new Error(\"Unknown encoding: \"+e);return t||e}function o(e){this.encoding=a(e);var t;switch(this.encoding){case\"utf16le\":this.text=u,this.end=p,t=4;break;case\"utf8\":this.fillLast=c,t=4;break;case\"base64\":this.text=f,this.end=g,t=3;break;default:return this.write=_,void(this.end=h);}this.lastNeed=0,this.lastTotal=0,this.lastChar=m.allocUnsafe(t)}function d(e){if(127>=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e,t,n){var r=t.length-1;if(r=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(\"utf16le\",t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):\"\";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(\"utf16le\",0,n)}return t}function f(e,t){var r=(e.length-t)%3;return 0==r?e.toString(\"base64\",t):(this.lastNeed=3-r,this.lastTotal=3,1==r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(\"base64\",t,e.length-r))}function g(e){var t=e&&e.length?this.write(e):\"\";return this.lastNeed?t+this.lastChar.toString(\"base64\",0,3-this.lastNeed):t}function _(e){return e.toString(this.encoding)}function h(e){return e&&e.length?this.write(e):\"\"}var m=e(\"safe-buffer\").Buffer,b=m.isEncoding||function(e){switch(e=\"\"+e,e&&e.toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":case\"raw\":return!0;default:return!1;}};n.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return\"\";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return\"\";n=this.lastNeed,this.lastNeed=0}else n=0;return n */const a=e(\"debug\")(\"simple-peer\"),o=e(\"get-browser-rtc\"),i=e(\"randombytes\"),d=e(\"readable-stream\"),s=e(\"queue-microtask\"),l=e(\"err-code\"),{Buffer:c}=e(\"buffer\"),u=65536;class p extends d.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),this._id=i(4).toString(\"hex\").slice(0,7),this._debug(\"new peer %o\",e),this.channelName=e.initiator?e.channelName||i(20).toString(\"hex\"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||p.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},p.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&\"object\"==typeof e.wrtc?e.wrtc:o(),!this._wrtc)if(\"undefined\"==typeof window)throw l(new Error(\"No WebRTC support: Specify `opts.wrtc` option in this environment\"),\"ERR_WEBRTC_SUPPORT\");else throw l(new Error(\"No WebRTC support: Not a supported browser\"),\"ERR_WEBRTC_SUPPORT\");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(l(e,\"ERR_PC_CONSTRUCTOR\"))}this._isReactNativeWebrtc=\"number\"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},\"object\"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(l(e,\"ERR_PC_PEER_IDENTITY\"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug(\"initial negotiation\"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once(\"finish\",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&\"open\"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot signal after peer is destroyed\"),\"ERR_DESTROYED\");if(\"string\"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug(\"signal()\"),e.renegotiate&&this.initiator&&(this._debug(\"got request to renegotiate\"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug(\"got request for transceiver\"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],\"offer\"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(l(e,\"ERR_SET_REMOTE_DESCRIPTION\"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(l(new Error(\"signal() called with invalid signal data\"),\"ERR_SIGNALING\"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(\".local\")?r(\"Ignoring unsupported ICE candidate.\"):this.destroy(l(e,\"ERR_ADD_ICE_CANDIDATE\"))})}send(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot send after peer is destroyed\"),\"ERR_DESTROYED\");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot addTransceiver after peer is destroyed\"),\"ERR_DESTROYED\");if(this._debug(\"addTransceiver()\"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(l(e,\"ERR_ADD_TRANSCEIVER\"))}else this.emit(\"signal\",{type:\"transceiverRequest\",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot addStream after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"addStream()\"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot addTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"addTrack()\");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(!r)r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation();else if(r.removed)throw l(new Error(\"Track has been removed. You should enable/disable tracks that you want to re-add.\"),\"ERR_SENDER_REMOVED\");else throw l(new Error(\"Track has already been added to that stream.\"),\"ERR_SENDER_ALREADY_ADDED\")}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot replaceTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"replaceTrack()\");const r=this._senderMap.get(e),a=r?r.get(n):null;if(!a)throw l(new Error(\"Cannot replace track that was never added.\"),\"ERR_TRACK_NOT_ADDED\");t&&this._senderMap.set(t,r),null==a.replaceTrack?this.destroy(l(new Error(\"replaceTrack is not supported in this browser\"),\"ERR_UNSUPPORTED_REPLACETRACK\")):a.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot removeTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"removeSender()\");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw l(new Error(\"Cannot remove track that was never added.\"),\"ERR_TRACK_NOT_ADDED\");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){\"NS_ERROR_UNEXPECTED\"===e.name?this._sendersAwaitingStable.push(r):this.destroy(l(e,\"ERR_REMOVE_TRACK\"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot removeStream after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"removeSenders()\"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug(\"_needsNegotiation\"),this._batchedNegotiation||(this._batchedNegotiation=!0,s(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug(\"starting batched negotiation\"),this.negotiate()):this._debug(\"non-initiator initial negotiation request discarded\"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot negotiate after peer is destroyed\"),\"ERR_DESTROYED\");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"start negotiation\"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"requesting negotiation from initiator\"),this.emit(\"signal\",{type:\"renegotiate\",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug(\"destroying (error: %s)\",e&&(e.message||e)),s(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug(\"destroy (error: %s)\",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener(\"finish\",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit(\"error\",e),this.emit(\"close\"),t()}))}_setupData(e){if(!e.channel)return this.destroy(l(new Error(\"Data channel event is missing `channel` property\"),\"ERR_DATA_CHANNEL\"));this._channel=e.channel,this._channel.binaryType=\"arraybuffer\",\"number\"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=u),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(l(t,\"ERR_DATA_CHANNEL\"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&\"closing\"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5000)}_read(){}_write(e,t,n){if(this.destroyed)return n(l(new Error(\"cannot write after peer is destroyed\"),\"ERR_DATA_CHANNEL\"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(l(e,\"ERR_DATA_CHANNEL\"))}this._channel.bufferedAmount>u?(this._debug(\"start backpressure: bufferedAmount %d\",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug(\"write before connect\"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once(\"connect\",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug(\"started iceComplete timeout\"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug(\"iceComplete timeout completed\"),this.emit(\"iceTimeout\"),this.emit(\"_iceComplete\"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug(\"createOffer success\"),this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(l(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(l(e,\"ERR_CREATE_OFFER\"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(l(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(l(e,\"ERR_CREATE_ANSWER\"))})}_onConnectionStateChange(){this.destroyed||\"failed\"===this._pc.connectionState&&this.destroy(l(new Error(\"Connection failed.\"),\"ERR_CONNECTION_FAILURE\"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug(\"iceStateChange (connection: %s) (gathering: %s)\",e,t),this.emit(\"iceStateChange\",e,t),(\"connected\"===e||\"completed\"===e)&&(this._pcReady=!0,this._maybeReady()),\"failed\"===e&&this.destroy(l(new Error(\"Ice connection failed.\"),\"ERR_ICE_CONNECTION_FAILURE\")),\"closed\"===e&&this.destroy(l(new Error(\"Ice connection closed.\"),\"ERR_ICE_CONNECTION_CLOSED\"))}getStats(e){const t=e=>(\"[object Array]\"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug(\"maybeReady pc %s channel %s\",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},a={},o={};let i=!1;n.forEach(e=>{(\"remotecandidate\"===e.type||\"remote-candidate\"===e.type)&&(r[e.id]=e),(\"localcandidate\"===e.type||\"local-candidate\"===e.type)&&(a[e.id]=e),(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&(o[e.id]=e)});const d=e=>{i=!0;let t=a[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):\"string\"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(\":\"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(\":\")?\"IPv6\":\"IPv4\");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):\"string\"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(\":\"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(\":\")?\"IPv6\":\"IPv4\"),this._debug(\"connect local: %s:%s remote: %s:%s\",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{\"transport\"===e.type&&e.selectedCandidatePairId&&d(o[e.selectedCandidatePairId]),(\"googCandidatePair\"===e.type&&\"true\"===e.googActiveConnection||(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&e.selected)&&d(e)}),!i&&(!Object.keys(o).length||Object.keys(a).length))return void setTimeout(e,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(l(e,\"ERR_DATA_CHANNEL\"))}this._chunk=null,this._debug(\"sent chunk from \\\"write before connect\\\"\");const e=this._cb;this._cb=null,e(null)}\"number\"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug(\"connect\"),this.emit(\"connect\")})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>u)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(\"stable\"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug(\"flushing sender queue\",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug(\"flushing negotiation queue\"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug(\"negotiated\"),this.emit(\"negotiated\"))),this._debug(\"signalingStateChange %s\",this._pc.signalingState),this.emit(\"signalingStateChange\",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit(\"signal\",{type:\"candidate\",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit(\"_iceComplete\")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=c.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug(\"ending backpressure: bufferedAmount %d\",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug(\"on channel open\"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug(\"on channel close\"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug(\"on track\"),this.emit(\"track\",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),s(()=>{this._debug(\"on stream\"),this.emit(\"stream\",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]=\"[\"+this._id+\"] \"+e[0],a.apply(null,e)}}p.WEBRTC_SUPPORT=!!o(),p.config={iceServers:[{urls:[\"stun:stun.l.google.com:19302\",\"stun:global.stun.twilio.com:3478\"]}],sdpSemantics:\"unified-plan\"},p.channelConfig={},t.exports=p},{buffer:3,debug:4,\"err-code\":6,\"get-browser-rtc\":8,\"queue-microtask\":13,randombytes:14,\"readable-stream\":29}]},{},[])(\"/\")});", "/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * \u2022 YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * \u2022 YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.\n * Therefore it is necessary that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n", "/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n", "/* eslint-env browser */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as promise from 'lib0/promise'\nimport * as error from 'lib0/error'\nimport * as string from 'lib0/string'\n\n/**\n * @param {string} secret\n * @param {string} roomName\n * @return {PromiseLike}\n */\nexport const deriveKey = (secret, roomName) => {\n const secretBuffer = string.encodeUtf8(secret).buffer\n const salt = string.encodeUtf8(roomName).buffer\n return crypto.subtle.importKey(\n 'raw',\n secretBuffer,\n 'PBKDF2',\n false,\n ['deriveKey']\n ).then(keyMaterial =>\n crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: 100000,\n hash: 'SHA-256'\n },\n keyMaterial,\n {\n name: 'AES-GCM',\n length: 256\n },\n true,\n ['encrypt', 'decrypt']\n )\n )\n}\n\n/**\n * @param {Uint8Array} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted, base64 encoded message\n */\nexport const encrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const iv = crypto.getRandomValues(new Uint8Array(12))\n return crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n data\n ).then(cipher => {\n const encryptedDataEncoder = encoding.createEncoder()\n encoding.writeVarString(encryptedDataEncoder, 'AES-GCM')\n encoding.writeVarUint8Array(encryptedDataEncoder, iv)\n encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher))\n return encoding.toUint8Array(encryptedDataEncoder)\n })\n}\n\n/**\n * @param {Object} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted data, if key is provided\n */\nexport const encryptJson = (data, key) => {\n const dataEncoder = encoding.createEncoder()\n encoding.writeAny(dataEncoder, data)\n return encrypt(encoding.toUint8Array(dataEncoder), key)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted buffer\n */\nexport const decrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const dataDecoder = decoding.createDecoder(data)\n const algorithm = decoding.readVarString(dataDecoder)\n if (algorithm !== 'AES-GCM') {\n promise.reject(error.create('Unknown encryption algorithm'))\n }\n const iv = decoding.readVarUint8Array(dataDecoder)\n const cipher = decoding.readVarUint8Array(dataDecoder)\n return crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n cipher\n ).then(data => new Uint8Array(data))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted object\n */\nexport const decryptJson = (data, key) =>\n decrypt(data, key).then(decryptedValue =>\n decoding.readAny(decoding.createDecoder(new Uint8Array(decryptedValue)))\n )\n", "import * as ws from 'lib0/websocket'\nimport * as map from 'lib0/map'\nimport * as error from 'lib0/error'\nimport * as random from 'lib0/random'\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport { ObservableV2 } from 'lib0/observable'\nimport * as logging from 'lib0/logging'\nimport * as promise from 'lib0/promise'\nimport * as bc from 'lib0/broadcastchannel'\nimport * as buffer from 'lib0/buffer'\nimport * as math from 'lib0/math'\nimport { createMutex } from 'lib0/mutex'\n\nimport * as Y from 'yjs' // eslint-disable-line\nimport Peer from 'simple-peer/simplepeer.min.js'\n\nimport * as syncProtocol from 'y-protocols/sync'\nimport * as awarenessProtocol from 'y-protocols/awareness'\n\nimport * as cryptoutils from './crypto.js'\n\nconst log = logging.createModuleLogger('y-webrtc')\n\nconst messageSync = 0\nconst messageQueryAwareness = 3\nconst messageAwareness = 1\nconst messageBcPeerId = 4\n\n/**\n * @type {Map}\n */\nconst signalingConns = new Map()\n\n/**\n * @type {Map}\n */\nconst rooms = new Map()\n\n/**\n * @param {Room} room\n */\nconst checkIsSynced = room => {\n let synced = true\n room.webrtcConns.forEach(peer => {\n if (!peer.synced) {\n synced = false\n }\n })\n if ((!synced && room.synced) || (synced && !room.synced)) {\n room.synced = synced\n room.provider.emit('synced', [{ synced }])\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with all peers')\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} buf\n * @param {function} syncedCallback\n * @return {encoding.Encoder?}\n */\nconst readMessage = (room, buf, syncedCallback) => {\n const decoder = decoding.createDecoder(buf)\n const encoder = encoding.createEncoder()\n const messageType = decoding.readVarUint(decoder)\n if (room === undefined) {\n return null\n }\n const awareness = room.awareness\n const doc = room.doc\n let sendReply = false\n switch (messageType) {\n case messageSync: {\n encoding.writeVarUint(encoder, messageSync)\n const syncMessageType = syncProtocol.readSyncMessage(decoder, encoder, doc, room)\n if (syncMessageType === syncProtocol.messageYjsSyncStep2 && !room.synced) {\n syncedCallback()\n }\n if (syncMessageType === syncProtocol.messageYjsSyncStep1) {\n sendReply = true\n }\n break\n }\n case messageQueryAwareness:\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())))\n sendReply = true\n break\n case messageAwareness:\n awarenessProtocol.applyAwarenessUpdate(awareness, decoding.readVarUint8Array(decoder), room)\n break\n case messageBcPeerId: {\n const add = decoding.readUint8(decoder) === 1\n const peerName = decoding.readVarString(decoder)\n if (peerName !== room.peerId && ((room.bcConns.has(peerName) && !add) || (!room.bcConns.has(peerName) && add))) {\n const removed = []\n const added = []\n if (add) {\n room.bcConns.add(peerName)\n added.push(peerName)\n } else {\n room.bcConns.delete(peerName)\n removed.push(peerName)\n }\n room.provider.emit('peers', [{\n added,\n removed,\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n broadcastBcPeerId(room)\n }\n break\n }\n default:\n console.error('Unable to compute message')\n return encoder\n }\n if (!sendReply) {\n // nothing has been written, no answer created\n return null\n }\n return encoder\n}\n\n/**\n * @param {WebrtcConn} peerConn\n * @param {Uint8Array} buf\n * @return {encoding.Encoder?}\n */\nconst readPeerMessage = (peerConn, buf) => {\n const room = peerConn.room\n log('received message from ', logging.BOLD, peerConn.remotePeerId, logging.GREY, ' (', room.name, ')', logging.UNBOLD, logging.UNCOLOR)\n return readMessage(room, buf, () => {\n peerConn.synced = true\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with ', logging.BOLD, peerConn.remotePeerId)\n checkIsSynced(room)\n })\n}\n\n/**\n * @param {WebrtcConn} webrtcConn\n * @param {encoding.Encoder} encoder\n */\nconst sendWebrtcConn = (webrtcConn, encoder) => {\n log('send message to ', logging.BOLD, webrtcConn.remotePeerId, logging.UNBOLD, logging.GREY, ' (', webrtcConn.room.name, ')', logging.UNCOLOR)\n try {\n webrtcConn.peer.send(encoding.toUint8Array(encoder))\n } catch (e) {}\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastWebrtcConn = (room, m) => {\n log('broadcast message in ', logging.BOLD, room.name, logging.UNBOLD)\n room.webrtcConns.forEach(conn => {\n try {\n conn.peer.send(m)\n } catch (e) {}\n })\n}\n\nexport class WebrtcConn {\n /**\n * @param {SignalingConn} signalingConn\n * @param {boolean} initiator\n * @param {string} remotePeerId\n * @param {Room} room\n */\n constructor (signalingConn, initiator, remotePeerId, room) {\n log('establishing connection to ', logging.BOLD, remotePeerId)\n this.room = room\n this.remotePeerId = remotePeerId\n this.glareToken = undefined\n this.closed = false\n this.connected = false\n this.synced = false\n /**\n * @type {any}\n */\n this.peer = new Peer({ initiator, ...room.provider.peerOpts })\n this.peer.on('signal', signal => {\n if (this.glareToken === undefined) {\n // add some randomness to the timestamp of the offer\n this.glareToken = Date.now() + Math.random()\n }\n publishSignalingMessage(signalingConn, room, { to: remotePeerId, from: room.peerId, type: 'signal', token: this.glareToken, signal })\n })\n this.peer.on('connect', () => {\n log('connected to ', logging.BOLD, remotePeerId)\n this.connected = true\n // send sync step 1\n const provider = room.provider\n const doc = provider.doc\n const awareness = room.awareness\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeSyncStep1(encoder, doc)\n sendWebrtcConn(this, encoder)\n const awarenessStates = awareness.getStates()\n if (awarenessStates.size > 0) {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awarenessStates.keys())))\n sendWebrtcConn(this, encoder)\n }\n })\n this.peer.on('close', () => {\n this.connected = false\n this.closed = true\n if (room.webrtcConns.has(this.remotePeerId)) {\n room.webrtcConns.delete(this.remotePeerId)\n room.provider.emit('peers', [{\n removed: [this.remotePeerId],\n added: [],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n }\n checkIsSynced(room)\n this.peer.destroy()\n log('closed connection to ', logging.BOLD, remotePeerId)\n announceSignalingInfo(room)\n })\n this.peer.on('error', err => {\n log('Error in connection to ', logging.BOLD, remotePeerId, ': ', err)\n announceSignalingInfo(room)\n })\n this.peer.on('data', data => {\n const answer = readPeerMessage(this, data)\n if (answer !== null) {\n sendWebrtcConn(this, answer)\n }\n })\n }\n\n destroy () {\n this.peer.destroy()\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastBcMessage = (room, m) => cryptoutils.encrypt(m, room.key).then(data =>\n room.mux(() =>\n bc.publish(room.name, data)\n )\n)\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastRoomMessage = (room, m) => {\n if (room.bcconnected) {\n broadcastBcMessage(room, m)\n }\n broadcastWebrtcConn(room, m)\n}\n\n/**\n * @param {Room} room\n */\nconst announceSignalingInfo = room => {\n signalingConns.forEach(conn => {\n // only subscribe if connection is established, otherwise the conn automatically subscribes to all rooms\n if (conn.connected) {\n conn.send({ type: 'subscribe', topics: [room.name] })\n if (room.webrtcConns.size < room.provider.maxConns) {\n publishSignalingMessage(conn, room, { type: 'announce', from: room.peerId })\n }\n }\n })\n}\n\n/**\n * @param {Room} room\n */\nconst broadcastBcPeerId = room => {\n if (room.provider.filterBcConns) {\n // broadcast peerId via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 1)\n encoding.writeVarString(encoderPeerIdBc, room.peerId)\n broadcastBcMessage(room, encoding.toUint8Array(encoderPeerIdBc))\n }\n}\n\nexport class Room {\n /**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n */\n constructor (doc, provider, name, key) {\n /**\n * Do not assume that peerId is unique. This is only meant for sending signaling messages.\n *\n * @type {string}\n */\n this.peerId = random.uuidv4()\n this.doc = doc\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = provider.awareness\n this.provider = provider\n this.synced = false\n this.name = name\n // @todo make key secret by scoping\n this.key = key\n /**\n * @type {Map}\n */\n this.webrtcConns = new Map()\n /**\n * @type {Set}\n */\n this.bcConns = new Set()\n this.mux = createMutex()\n this.bcconnected = false\n /**\n * @param {ArrayBuffer} data\n */\n this._bcSubscriber = data =>\n cryptoutils.decrypt(new Uint8Array(data), key).then(m =>\n this.mux(() => {\n const reply = readMessage(this, m, () => {})\n if (reply) {\n broadcastBcMessage(this, encoding.toUint8Array(reply))\n }\n })\n )\n /**\n * Listens to Yjs updates and sends them to remote peers\n *\n * @param {Uint8Array} update\n * @param {any} _origin\n */\n this._docUpdateHandler = (update, _origin) => {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeUpdate(encoder, update)\n broadcastRoomMessage(this, encoding.toUint8Array(encoder))\n }\n /**\n * Listens to Awareness updates and sends them to remote peers\n *\n * @param {any} changed\n * @param {any} _origin\n */\n this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {\n const changedClients = added.concat(updated).concat(removed)\n const encoderAwareness = encoding.createEncoder()\n encoding.writeVarUint(encoderAwareness, messageAwareness)\n encoding.writeVarUint8Array(encoderAwareness, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients))\n broadcastRoomMessage(this, encoding.toUint8Array(encoderAwareness))\n }\n\n this._beforeUnloadHandler = () => {\n awarenessProtocol.removeAwarenessStates(this.awareness, [doc.clientID], 'window unload')\n rooms.forEach(room => {\n room.disconnect()\n })\n }\n\n if (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', this._beforeUnloadHandler)\n } else if (typeof process !== 'undefined') {\n process.on('exit', this._beforeUnloadHandler)\n }\n }\n\n connect () {\n this.doc.on('update', this._docUpdateHandler)\n this.awareness.on('update', this._awarenessUpdateHandler)\n // signal through all available signaling connections\n announceSignalingInfo(this)\n const roomName = this.name\n bc.subscribe(roomName, this._bcSubscriber)\n this.bcconnected = true\n // broadcast peerId via broadcastchannel\n broadcastBcPeerId(this)\n // write sync step 1\n const encoderSync = encoding.createEncoder()\n encoding.writeVarUint(encoderSync, messageSync)\n syncProtocol.writeSyncStep1(encoderSync, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderSync))\n // broadcast local state\n const encoderState = encoding.createEncoder()\n encoding.writeVarUint(encoderState, messageSync)\n syncProtocol.writeSyncStep2(encoderState, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderState))\n // write queryAwareness\n const encoderAwarenessQuery = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness)\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessQuery))\n // broadcast local awareness state\n const encoderAwarenessState = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessState, messageAwareness)\n encoding.writeVarUint8Array(encoderAwarenessState, awarenessProtocol.encodeAwarenessUpdate(this.awareness, [this.doc.clientID]))\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessState))\n }\n\n disconnect () {\n // signal through all available signaling connections\n signalingConns.forEach(conn => {\n if (conn.connected) {\n conn.send({ type: 'unsubscribe', topics: [this.name] })\n }\n })\n awarenessProtocol.removeAwarenessStates(this.awareness, [this.doc.clientID], 'disconnect')\n // broadcast peerId removal via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 0) // remove peerId from other bc peers\n encoding.writeVarString(encoderPeerIdBc, this.peerId)\n broadcastBcMessage(this, encoding.toUint8Array(encoderPeerIdBc))\n\n bc.unsubscribe(this.name, this._bcSubscriber)\n this.bcconnected = false\n this.doc.off('update', this._docUpdateHandler)\n this.awareness.off('update', this._awarenessUpdateHandler)\n this.webrtcConns.forEach(conn => conn.destroy())\n }\n\n destroy () {\n this.disconnect()\n if (typeof window !== 'undefined') {\n window.removeEventListener('beforeunload', this._beforeUnloadHandler)\n } else if (typeof process !== 'undefined') {\n process.off('exit', this._beforeUnloadHandler)\n }\n }\n}\n\n/**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n * @return {Room}\n */\nconst openRoom = (doc, provider, name, key) => {\n // there must only be one room\n if (rooms.has(name)) {\n throw error.create(`A Yjs Doc connected to room \"${name}\" already exists!`)\n }\n const room = new Room(doc, provider, name, key)\n rooms.set(name, /** @type {Room} */ (room))\n return room\n}\n\n/**\n * @param {SignalingConn} conn\n * @param {Room} room\n * @param {any} data\n */\nconst publishSignalingMessage = (conn, room, data) => {\n if (room.key) {\n cryptoutils.encryptJson(data, room.key).then(data => {\n conn.send({ type: 'publish', topic: room.name, data: buffer.toBase64(data) })\n })\n } else {\n conn.send({ type: 'publish', topic: room.name, data })\n }\n}\n\nexport class SignalingConn extends ws.WebsocketClient {\n constructor (url) {\n super(url)\n /**\n * @type {Set}\n */\n this.providers = new Set()\n this.on('connect', () => {\n log(`connected (${url})`)\n const topics = Array.from(rooms.keys())\n this.send({ type: 'subscribe', topics })\n rooms.forEach(room =>\n publishSignalingMessage(this, room, { type: 'announce', from: room.peerId })\n )\n })\n this.on('message', m => {\n switch (m.type) {\n case 'publish': {\n const roomName = m.topic\n const room = rooms.get(roomName)\n if (room == null || typeof roomName !== 'string') {\n return\n }\n const execMessage = data => {\n const webrtcConns = room.webrtcConns\n const peerId = room.peerId\n if (data == null || data.from === peerId || (data.to !== undefined && data.to !== peerId) || room.bcConns.has(data.from)) {\n // ignore messages that are not addressed to this conn, or from clients that are connected via broadcastchannel\n return\n }\n const emitPeerChange = webrtcConns.has(data.from)\n ? () => {}\n : () =>\n room.provider.emit('peers', [{\n removed: [],\n added: [data.from],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n switch (data.type) {\n case 'announce':\n if (webrtcConns.size < room.provider.maxConns) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, true, data.from, room))\n emitPeerChange()\n }\n break\n case 'signal':\n if (data.signal.type === 'offer') {\n const existingConn = webrtcConns.get(data.from)\n if (existingConn) {\n const remoteToken = data.token\n const localToken = existingConn.glareToken\n if (localToken && localToken > remoteToken) {\n log('offer rejected: ', data.from)\n return\n }\n // if we don't reject the offer, we will be accepting it and answering it\n existingConn.glareToken = undefined\n }\n }\n if (data.signal.type === 'answer') {\n log('offer answered by: ', data.from)\n const existingConn = webrtcConns.get(data.from)\n existingConn.glareToken = undefined\n }\n if (data.to === peerId) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, false, data.from, room)).peer.signal(data.signal)\n emitPeerChange()\n }\n break\n }\n }\n if (room.key) {\n if (typeof m.data === 'string') {\n cryptoutils.decryptJson(buffer.fromBase64(m.data), room.key).then(execMessage)\n }\n } else {\n execMessage(m.data)\n }\n }\n }\n })\n this.on('disconnect', () => log(`disconnect (${url})`))\n }\n}\n\n/**\n * @typedef {Object} ProviderOptions\n * @property {Array} [signaling]\n * @property {string} [password]\n * @property {awarenessProtocol.Awareness} [awareness]\n * @property {number} [maxConns]\n * @property {boolean} [filterBcConns]\n * @property {any} [peerOpts]\n */\n\n/**\n * @param {WebrtcProvider} provider\n */\nconst emitStatus = provider => {\n provider.emit('status', [{\n connected: provider.connected\n }])\n}\n\n/**\n * @typedef {Object} WebrtcProviderEvents\n * @property {function({connected:boolean}):void} WebrtcProviderEvent.status\n * @property {function({synced:boolean}):void} WebrtcProviderEvent.synced\n * @property {function({added:Array,removed:Array,webrtcPeers:Array,bcPeers:Array}):void} WebrtcProviderEvent.peers\n */\n\n/**\n * @extends ObservableV2\n */\nexport class WebrtcProvider extends ObservableV2 {\n /**\n * @param {string} roomName\n * @param {Y.Doc} doc\n * @param {ProviderOptions?} opts\n */\n constructor (\n roomName,\n doc,\n {\n signaling = ['wss://y-webrtc-eu.fly.dev'],\n password = null,\n awareness = new awarenessProtocol.Awareness(doc),\n maxConns = 20 + math.floor(random.rand() * 15), // the random factor reduces the chance that n clients form a cluster\n filterBcConns = true,\n peerOpts = {} // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts\n } = {}\n ) {\n super()\n this.roomName = roomName\n this.doc = doc\n this.filterBcConns = filterBcConns\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = awareness\n this.shouldConnect = false\n this.signalingUrls = signaling\n this.signalingConns = []\n this.maxConns = maxConns\n this.peerOpts = peerOpts\n /**\n * @type {PromiseLike}\n */\n this.key = password ? cryptoutils.deriveKey(password, roomName) : /** @type {PromiseLike} */ (promise.resolve(null))\n /**\n * @type {Room|null}\n */\n this.room = null\n this.key.then(key => {\n this.room = openRoom(doc, this, roomName, key)\n if (this.shouldConnect) {\n this.room.connect()\n } else {\n this.room.disconnect()\n }\n emitStatus(this)\n })\n this.connect()\n this.destroy = this.destroy.bind(this)\n doc.on('destroy', this.destroy)\n }\n\n /**\n * Indicates whether the provider is looking for other peers.\n *\n * Other peers can be found via signaling servers or via broadcastchannel (cross browser-tab\n * communication). You never know when you are connected to all peers. You also don't know if\n * there are other peers. connected doesn't mean that you are connected to any physical peers\n * working on the same resource as you. It does not change unless you call provider.disconnect()\n *\n * `this.on('status', (event) => { console.log(event.connected) })`\n *\n * @type {boolean}\n */\n get connected () {\n return this.room !== null && this.shouldConnect\n }\n\n connect () {\n this.shouldConnect = true\n this.signalingUrls.forEach(url => {\n const signalingConn = map.setIfUndefined(signalingConns, url, () => new SignalingConn(url))\n this.signalingConns.push(signalingConn)\n signalingConn.providers.add(this)\n })\n if (this.room) {\n this.room.connect()\n emitStatus(this)\n }\n }\n\n disconnect () {\n this.shouldConnect = false\n this.signalingConns.forEach(conn => {\n conn.providers.delete(this)\n if (conn.providers.size === 0) {\n conn.destroy()\n signalingConns.delete(conn.url)\n }\n })\n if (this.room) {\n this.room.disconnect()\n emitStatus(this)\n }\n }\n\n destroy () {\n this.doc.off('destroy', this.destroy)\n // need to wait for key before deleting room\n this.key.then(() => {\n /** @type {Room} */ (this.room).destroy()\n rooms.delete(this.roomName)\n })\n super.destroy()\n }\n}\n", "/* eslint-env browser */\n\n/**\n * Helpers to work with IndexedDB.\n *\n * @module indexeddb\n */\n\nimport * as promise from './promise.js'\nimport * as error from './error.js'\n\n/* c8 ignore start */\n\n/**\n * IDB Request to Promise transformer\n *\n * @param {IDBRequest} request\n * @return {Promise}\n */\nexport const rtop = request => promise.create((resolve, reject) => {\n // @ts-ignore\n request.onerror = event => reject(new Error(event.target.error))\n // @ts-ignore\n request.onsuccess = event => resolve(event.target.result)\n})\n\n/**\n * @param {string} name\n * @param {function(IDBDatabase):any} initDB Called when the database is first created\n * @return {Promise}\n */\nexport const openDB = (name, initDB) => promise.create((resolve, reject) => {\n const request = indexedDB.open(name)\n /**\n * @param {any} event\n */\n request.onupgradeneeded = event => initDB(event.target.result)\n /**\n * @param {any} event\n */\n request.onerror = event => reject(error.create(event.target.error))\n /**\n * @param {any} event\n */\n request.onsuccess = event => {\n /**\n * @type {IDBDatabase}\n */\n const db = event.target.result\n db.onversionchange = () => { db.close() }\n resolve(db)\n }\n})\n\n/**\n * @param {string} name\n */\nexport const deleteDB = name => rtop(indexedDB.deleteDatabase(name))\n\n/**\n * @param {IDBDatabase} db\n * @param {Array|Array>} definitions\n */\nexport const createStores = (db, definitions) => definitions.forEach(d =>\n // @ts-ignore\n db.createObjectStore.apply(db, d)\n)\n\n/**\n * @param {IDBDatabase} db\n * @param {Array} stores\n * @param {\"readwrite\"|\"readonly\"} [access]\n * @return {Array}\n */\nexport const transact = (db, stores, access = 'readwrite') => {\n const transaction = db.transaction(stores, access)\n return stores.map(store => getStore(transaction, store))\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @return {Promise}\n */\nexport const count = (store, range) =>\n rtop(store.count(range))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | Array } key\n * @return {Promise>}\n */\nexport const get = (store, key) =>\n rtop(store.get(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key\n */\nexport const del = (store, key) =>\n rtop(store.delete(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} [key]\n */\nexport const put = (store, item, key) =>\n rtop(store.put(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} key\n * @return {Promise}\n */\nexport const add = (store, item, key) =>\n rtop(store.add(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date} item\n * @return {Promise} Returns the generated key\n */\nexport const addAutoKey = (store, item) =>\n rtop(store.add(item))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAll = (store, range, limit) =>\n rtop(store.getAll(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeys = (store, range, limit) =>\n rtop(store.getAllKeys(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} query\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n * @return {Promise}\n */\nexport const queryFirst = (store, query, direction) => {\n /**\n * @type {any}\n */\n let first = null\n return iterateKeys(store, query, key => {\n first = key\n return false\n }, direction).then(() => first)\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getLastKey = (store, range = null) => queryFirst(store, range, 'prev')\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getFirstKey = (store, range = null) => queryFirst(store, range, 'next')\n\n/**\n * @typedef KeyValuePair\n * @type {Object}\n * @property {any} k key\n * @property {any} v Value\n */\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeysValues = (store, range, limit) =>\n // @ts-ignore\n promise.all([getAllKeys(store, range, limit), getAll(store, range, limit)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] })))\n\n/**\n * @param {any} request\n * @param {function(IDBCursorWithValue):void|boolean|Promise} f\n * @return {Promise}\n */\nconst iterateOnRequest = (request, f) => promise.create((resolve, reject) => {\n request.onerror = reject\n /**\n * @param {any} event\n */\n request.onsuccess = async event => {\n const cursor = event.target.result\n if (cursor === null || (await f(cursor)) === false) {\n return resolve()\n }\n cursor.continue()\n }\n})\n\n/**\n * Iterate on keys and values\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any,any):void|boolean|Promise} f Callback that receives (value, key)\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterate = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openCursor(keyrange, direction), cursor => f(cursor.value, cursor.key))\n\n/**\n * Iterate on the keys (no values)\n *\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any):void|boolean|Promise} f callback that receives the key\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterateKeys = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openKeyCursor(keyrange, direction), cursor => f(cursor.key))\n\n/**\n * Open store from transaction\n * @param {IDBTransaction} t\n * @param {String} store\n * @returns {IDBObjectStore}\n */\nexport const getStore = (t, store) => t.objectStore(store)\n\n/**\n * @param {any} lower\n * @param {any} upper\n * @param {boolean} lowerOpen\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen)\n\n/**\n * @param {any} upper\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen)\n\n/**\n * @param {any} lower\n * @param {boolean} lowerOpen\n */\nexport const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen)\n\n/* c8 ignore stop */\n", "import * as Y from 'yjs'\nimport * as idb from 'lib0/indexeddb'\nimport * as promise from 'lib0/promise'\nimport { Observable } from 'lib0/observable'\n\nconst customStoreName = 'custom'\nconst updatesStoreName = 'updates'\n\nexport const PREFERRED_TRIM_SIZE = 500\n\n/**\n * @param {IndexeddbPersistence} idbPersistence\n * @param {function(IDBObjectStore):void} [beforeApplyUpdatesCallback]\n * @param {function(IDBObjectStore):void} [afterApplyUpdatesCallback]\n */\nexport const fetchUpdates = (idbPersistence, beforeApplyUpdatesCallback = () => {}, afterApplyUpdatesCallback = () => {}) => {\n const [updatesStore] = idb.transact(/** @type {IDBDatabase} */ (idbPersistence.db), [updatesStoreName]) // , 'readonly')\n return idb.getAll(updatesStore, idb.createIDBKeyRangeLowerBound(idbPersistence._dbref, false)).then(updates => {\n if (!idbPersistence._destroyed) {\n beforeApplyUpdatesCallback(updatesStore)\n Y.transact(idbPersistence.doc, () => {\n updates.forEach(val => Y.applyUpdate(idbPersistence.doc, val))\n }, idbPersistence, false)\n afterApplyUpdatesCallback(updatesStore)\n }\n })\n .then(() => idb.getLastKey(updatesStore).then(lastKey => { idbPersistence._dbref = lastKey + 1 }))\n .then(() => idb.count(updatesStore).then(cnt => { idbPersistence._dbsize = cnt }))\n .then(() => updatesStore)\n}\n\n/**\n * @param {IndexeddbPersistence} idbPersistence\n * @param {boolean} forceStore\n */\nexport const storeState = (idbPersistence, forceStore = true) =>\n fetchUpdates(idbPersistence)\n .then(updatesStore => {\n if (forceStore || idbPersistence._dbsize >= PREFERRED_TRIM_SIZE) {\n idb.addAutoKey(updatesStore, Y.encodeStateAsUpdate(idbPersistence.doc))\n .then(() => idb.del(updatesStore, idb.createIDBKeyRangeUpperBound(idbPersistence._dbref, true)))\n .then(() => idb.count(updatesStore).then(cnt => { idbPersistence._dbsize = cnt }))\n }\n })\n\n/**\n * @param {string} name\n */\nexport const clearDocument = name => idb.deleteDB(name)\n\n/**\n * @extends Observable\n */\nexport class IndexeddbPersistence extends Observable {\n /**\n * @param {string} name\n * @param {Y.Doc} doc\n */\n constructor (name, doc) {\n super()\n this.doc = doc\n this.name = name\n this._dbref = 0\n this._dbsize = 0\n this._destroyed = false\n /**\n * @type {IDBDatabase|null}\n */\n this.db = null\n this.synced = false\n this._db = idb.openDB(name, db =>\n idb.createStores(db, [\n ['updates', { autoIncrement: true }],\n ['custom']\n ])\n )\n /**\n * @type {Promise}\n */\n this.whenSynced = promise.create(resolve => this.on('synced', () => resolve(this)))\n\n this._db.then(db => {\n this.db = db\n /**\n * @param {IDBObjectStore} updatesStore\n */\n const beforeApplyUpdatesCallback = (updatesStore) => idb.addAutoKey(updatesStore, Y.encodeStateAsUpdate(doc))\n const afterApplyUpdatesCallback = () => {\n if (this._destroyed) return this\n this.synced = true\n this.emit('synced', [this])\n }\n fetchUpdates(this, beforeApplyUpdatesCallback, afterApplyUpdatesCallback)\n })\n /**\n * Timeout in ms untill data is merged and persisted in idb.\n */\n this._storeTimeout = 1000\n /**\n * @type {any}\n */\n this._storeTimeoutId = null\n /**\n * @param {Uint8Array} update\n * @param {any} origin\n */\n this._storeUpdate = (update, origin) => {\n if (this.db && origin !== this) {\n const [updatesStore] = idb.transact(/** @type {IDBDatabase} */ (this.db), [updatesStoreName])\n idb.addAutoKey(updatesStore, update)\n if (++this._dbsize >= PREFERRED_TRIM_SIZE) {\n // debounce store call\n if (this._storeTimeoutId !== null) {\n clearTimeout(this._storeTimeoutId)\n }\n this._storeTimeoutId = setTimeout(() => {\n storeState(this, false)\n this._storeTimeoutId = null\n }, this._storeTimeout)\n }\n }\n }\n doc.on('update', this._storeUpdate)\n this.destroy = this.destroy.bind(this)\n doc.on('destroy', this.destroy)\n }\n\n destroy () {\n if (this._storeTimeoutId) {\n clearTimeout(this._storeTimeoutId)\n }\n this.doc.off('update', this._storeUpdate)\n this.doc.off('destroy', this.destroy)\n this._destroyed = true\n return this._db.then(db => {\n db.close()\n })\n }\n\n /**\n * Destroys this instance and removes all data from indexeddb.\n *\n * @return {Promise}\n */\n clearData () {\n return this.destroy().then(() => {\n idb.deleteDB(this.name)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @return {Promise}\n */\n get (key) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName], 'readonly')\n return idb.get(custom, key)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @param {String | number | ArrayBuffer | Date} value\n * @return {Promise}\n */\n set (key, value) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName])\n return idb.put(custom, value, key)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @return {Promise}\n */\n del (key) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName])\n return idb.del(custom, key)\n })\n }\n}\n", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}\n\n/*# sourceMappingURL=quill.core.css.map*/", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}.ql-bubble.ql-toolbar:after,.ql-bubble .ql-toolbar:after{clear:both;content:'';display:table}.ql-bubble.ql-toolbar button,.ql-bubble .ql-toolbar button{background:none;border:none;cursor:pointer;display:inline-block;float:left;height:24px;padding:3px 5px;width:28px}.ql-bubble.ql-toolbar button svg,.ql-bubble .ql-toolbar button svg{float:left;height:100%}.ql-bubble.ql-toolbar button:active:hover,.ql-bubble .ql-toolbar button:active:hover{outline:none}.ql-bubble.ql-toolbar input.ql-image[type=file],.ql-bubble .ql-toolbar input.ql-image[type=file]{display:none}.ql-bubble.ql-toolbar button:hover,.ql-bubble .ql-toolbar button:hover,.ql-bubble.ql-toolbar button:focus,.ql-bubble .ql-toolbar button:focus,.ql-bubble.ql-toolbar button.ql-active,.ql-bubble .ql-toolbar button.ql-active,.ql-bubble.ql-toolbar .ql-picker-label:hover,.ql-bubble .ql-toolbar .ql-picker-label:hover,.ql-bubble.ql-toolbar .ql-picker-label.ql-active,.ql-bubble .ql-toolbar .ql-picker-label.ql-active,.ql-bubble.ql-toolbar .ql-picker-item:hover,.ql-bubble .ql-toolbar .ql-picker-item:hover,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected{color:#fff}.ql-bubble.ql-toolbar button:hover .ql-fill,.ql-bubble .ql-toolbar button:hover .ql-fill,.ql-bubble.ql-toolbar button:focus .ql-fill,.ql-bubble .ql-toolbar button:focus .ql-fill,.ql-bubble.ql-toolbar button.ql-active .ql-fill,.ql-bubble .ql-toolbar button.ql-active .ql-fill,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-fill,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-fill,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-fill,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-fill,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-bubble.ql-toolbar button:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar button:focus .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:focus .ql-stroke.ql-fill,.ql-bubble.ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill{fill:#fff}.ql-bubble.ql-toolbar button:hover .ql-stroke,.ql-bubble .ql-toolbar button:hover .ql-stroke,.ql-bubble.ql-toolbar button:focus .ql-stroke,.ql-bubble .ql-toolbar button:focus .ql-stroke,.ql-bubble.ql-toolbar button.ql-active .ql-stroke,.ql-bubble .ql-toolbar button.ql-active .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-bubble.ql-toolbar button:hover .ql-stroke-miter,.ql-bubble .ql-toolbar button:hover .ql-stroke-miter,.ql-bubble.ql-toolbar button:focus .ql-stroke-miter,.ql-bubble .ql-toolbar button:focus .ql-stroke-miter,.ql-bubble.ql-toolbar button.ql-active .ql-stroke-miter,.ql-bubble .ql-toolbar button.ql-active .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter{stroke:#fff}@media (pointer:coarse){.ql-bubble.ql-toolbar button:hover:not(.ql-active),.ql-bubble .ql-toolbar button:hover:not(.ql-active){color:#ccc}.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill{fill:#ccc}.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter{stroke:#ccc}}.ql-bubble{box-sizing:border-box}.ql-bubble *{box-sizing:border-box}.ql-bubble .ql-hidden{display:none}.ql-bubble .ql-out-bottom,.ql-bubble .ql-out-top{visibility:hidden}.ql-bubble .ql-tooltip{position:absolute;transform:translateY(10px)}.ql-bubble .ql-tooltip a{cursor:pointer;text-decoration:none}.ql-bubble .ql-tooltip.ql-flip{transform:translateY(-10px)}.ql-bubble .ql-formats{display:inline-block;vertical-align:middle}.ql-bubble .ql-formats:after{clear:both;content:'';display:table}.ql-bubble .ql-stroke{fill:none;stroke:#ccc;stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.ql-bubble .ql-stroke-miter{fill:none;stroke:#ccc;stroke-miterlimit:10;stroke-width:2}.ql-bubble .ql-fill,.ql-bubble .ql-stroke.ql-fill{fill:#ccc}.ql-bubble .ql-empty{fill:none}.ql-bubble .ql-even{fill-rule:evenodd}.ql-bubble .ql-thin,.ql-bubble .ql-stroke.ql-thin{stroke-width:1}.ql-bubble .ql-transparent{opacity:.4}.ql-bubble .ql-direction svg:last-child{display:none}.ql-bubble .ql-direction.ql-active svg:last-child{display:inline}.ql-bubble .ql-direction.ql-active svg:first-child{display:none}.ql-bubble .ql-editor h1{font-size:2em}.ql-bubble .ql-editor h2{font-size:1.5em}.ql-bubble .ql-editor h3{font-size:1.17em}.ql-bubble .ql-editor h4{font-size:1em}.ql-bubble .ql-editor h5{font-size:.83em}.ql-bubble .ql-editor h6{font-size:.67em}.ql-bubble .ql-editor a{text-decoration:underline}.ql-bubble .ql-editor blockquote{border-left:4px solid #ccc;margin-bottom:5px;margin-top:5px;padding-left:16px}.ql-bubble .ql-editor code,.ql-bubble .ql-editor .ql-code-block-container{background-color:#f0f0f0;border-radius:3px}.ql-bubble .ql-editor .ql-code-block-container{margin-bottom:5px;margin-top:5px;padding:5px 10px}.ql-bubble .ql-editor code{font-size:85%;padding:2px 4px}.ql-bubble .ql-editor .ql-code-block-container{background-color:#23241f;color:#f8f8f2;overflow:visible}.ql-bubble .ql-editor img{max-width:100%}.ql-bubble .ql-picker{color:#ccc;display:inline-block;float:left;font-size:14px;font-weight:500;height:24px;position:relative;vertical-align:middle}.ql-bubble .ql-picker-label{cursor:pointer;display:inline-block;height:100%;padding-left:8px;padding-right:2px;position:relative;width:100%}.ql-bubble .ql-picker-label::before{display:inline-block;line-height:22px}.ql-bubble .ql-picker-options{background-color:#444;display:none;min-width:100%;padding:4px 8px;position:absolute;white-space:nowrap}.ql-bubble .ql-picker-options .ql-picker-item{cursor:pointer;display:block;padding-bottom:5px;padding-top:5px}.ql-bubble .ql-picker.ql-expanded .ql-picker-label{color:#777;z-index:2}.ql-bubble .ql-picker.ql-expanded .ql-picker-label .ql-fill{fill:#777}.ql-bubble .ql-picker.ql-expanded .ql-picker-label .ql-stroke{stroke:#777}.ql-bubble .ql-picker.ql-expanded .ql-picker-options{display:block;margin-top:-1px;top:100%;z-index:1}.ql-bubble .ql-color-picker,.ql-bubble .ql-icon-picker{width:28px}.ql-bubble .ql-color-picker .ql-picker-label,.ql-bubble .ql-icon-picker .ql-picker-label{padding:2px 4px}.ql-bubble .ql-color-picker .ql-picker-label svg,.ql-bubble .ql-icon-picker .ql-picker-label svg{right:4px}.ql-bubble .ql-icon-picker .ql-picker-options{padding:4px 0}.ql-bubble .ql-icon-picker .ql-picker-item{height:24px;width:24px;padding:2px 4px}.ql-bubble .ql-color-picker .ql-picker-options{padding:3px 5px;width:152px}.ql-bubble .ql-color-picker .ql-picker-item{border:1px solid transparent;float:left;height:16px;margin:2px;padding:0;width:16px}.ql-bubble .ql-picker:not(.ql-color-picker):not(.ql-icon-picker) svg{position:absolute;margin-top:-9px;right:0;top:50%;width:18px}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-font .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-size .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-label]:not([data-label=''])::before{content:attr(data-label)}.ql-bubble .ql-picker.ql-header{width:98px}.ql-bubble .ql-picker.ql-header .ql-picker-label::before,.ql-bubble .ql-picker.ql-header .ql-picker-item::before{content:'Normal'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"1\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{content:'Heading 1'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"2\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{content:'Heading 2'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"3\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{content:'Heading 3'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"4\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{content:'Heading 4'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"5\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{content:'Heading 5'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"6\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{content:'Heading 6'}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{font-size:2em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{font-size:1.5em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{font-size:1.17em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{font-size:1em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{font-size:.83em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{font-size:.67em}.ql-bubble .ql-picker.ql-font{width:108px}.ql-bubble .ql-picker.ql-font .ql-picker-label::before,.ql-bubble .ql-picker.ql-font .ql-picker-item::before{content:'Sans Serif'}.ql-bubble .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{content:'Serif'}.ql-bubble .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{content:'Monospace'}.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{font-family:Georgia,Times New Roman,serif}.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{font-family:Monaco,Courier New,monospace}.ql-bubble .ql-picker.ql-size{width:98px}.ql-bubble .ql-picker.ql-size .ql-picker-label::before,.ql-bubble .ql-picker.ql-size .ql-picker-item::before{content:'Normal'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=small]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=small]::before{content:'Small'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=large]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=large]::before{content:'Large'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{content:'Huge'}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=small]::before{font-size:10px}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=large]::before{font-size:18px}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{font-size:32px}.ql-bubble .ql-color-picker.ql-background .ql-picker-item{background-color:#fff}.ql-bubble .ql-color-picker.ql-color .ql-picker-item{background-color:#000}.ql-code-block-container{position:relative}.ql-code-block-container .ql-ui{right:5px;top:5px}.ql-bubble .ql-toolbar .ql-formats{margin:8px 12px 8px 0}.ql-bubble .ql-toolbar .ql-formats:first-child{margin-left:12px}.ql-bubble .ql-color-picker svg{margin:1px}.ql-bubble .ql-color-picker .ql-picker-item.ql-selected,.ql-bubble .ql-color-picker .ql-picker-item:hover{border-color:#fff}.ql-bubble .ql-tooltip{background-color:#444;border-radius:25px;color:#fff}.ql-bubble .ql-tooltip-arrow{border-left:6px solid transparent;border-right:6px solid transparent;content:\" \";display:block;left:50%;margin-left:-6px;position:absolute}.ql-bubble .ql-tooltip:not(.ql-flip) .ql-tooltip-arrow{border-bottom:6px solid #444;top:-6px}.ql-bubble .ql-tooltip.ql-flip .ql-tooltip-arrow{border-top:6px solid #444;bottom:-6px}.ql-bubble .ql-tooltip.ql-editing .ql-tooltip-editor{display:block}.ql-bubble .ql-tooltip.ql-editing .ql-formats{visibility:hidden}.ql-bubble .ql-tooltip-editor{display:none}.ql-bubble .ql-tooltip-editor input[type=text]{background:transparent;border:none;color:#fff;font-size:13px;height:100%;outline:none;padding:10px 20px;position:absolute;width:100%}.ql-bubble .ql-tooltip-editor a{top:10px;position:absolute;right:20px}.ql-bubble .ql-tooltip-editor a:before{color:#ccc;content:\"\\00D7\";font-size:16px;font-weight:bold}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close){position:relative;white-space:nowrap}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::before{background-color:#444;border-radius:15px;top:-5px;font-size:12px;color:#fff;content:attr(href);font-weight:normal;overflow:hidden;padding:5px 15px;text-decoration:none;z-index:1}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::after{border-top:6px solid #444;border-left:6px solid transparent;border-right:6px solid transparent;top:0;content:\" \";height:0;width:0}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::before,.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::after{left:0;margin-left:50%;position:absolute;transform:translate(-50%,-100%);transition:visibility 0s ease 200ms;visibility:hidden}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close):hover::before,.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close):hover::after{visibility:visible}\n\n/*# sourceMappingURL=quill.bubble.css.map*/", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}.ql-snow.ql-toolbar:after,.ql-snow .ql-toolbar:after{clear:both;content:'';display:table}.ql-snow.ql-toolbar button,.ql-snow .ql-toolbar button{background:none;border:none;cursor:pointer;display:inline-block;float:left;height:24px;padding:3px 5px;width:28px}.ql-snow.ql-toolbar button svg,.ql-snow .ql-toolbar button svg{float:left;height:100%}.ql-snow.ql-toolbar button:active:hover,.ql-snow .ql-toolbar button:active:hover{outline:none}.ql-snow.ql-toolbar input.ql-image[type=file],.ql-snow .ql-toolbar input.ql-image[type=file]{display:none}.ql-snow.ql-toolbar button:hover,.ql-snow .ql-toolbar button:hover,.ql-snow.ql-toolbar button:focus,.ql-snow .ql-toolbar button:focus,.ql-snow.ql-toolbar button.ql-active,.ql-snow .ql-toolbar button.ql-active,.ql-snow.ql-toolbar .ql-picker-label:hover,.ql-snow .ql-toolbar .ql-picker-label:hover,.ql-snow.ql-toolbar .ql-picker-label.ql-active,.ql-snow .ql-toolbar .ql-picker-label.ql-active,.ql-snow.ql-toolbar .ql-picker-item:hover,.ql-snow .ql-toolbar .ql-picker-item:hover,.ql-snow.ql-toolbar .ql-picker-item.ql-selected,.ql-snow .ql-toolbar .ql-picker-item.ql-selected{color:#06c}.ql-snow.ql-toolbar button:hover .ql-fill,.ql-snow .ql-toolbar button:hover .ql-fill,.ql-snow.ql-toolbar button:focus .ql-fill,.ql-snow .ql-toolbar button:focus .ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow.ql-toolbar button:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill{fill:#06c}.ql-snow.ql-toolbar button:hover .ql-stroke,.ql-snow .ql-toolbar button:hover .ql-stroke,.ql-snow.ql-toolbar button:focus .ql-stroke,.ql-snow .ql-toolbar button:focus .ql-stroke,.ql-snow.ql-toolbar button.ql-active .ql-stroke,.ql-snow .ql-toolbar button.ql-active .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow.ql-toolbar button:hover .ql-stroke-miter,.ql-snow .ql-toolbar button:hover .ql-stroke-miter,.ql-snow.ql-toolbar button:focus .ql-stroke-miter,.ql-snow .ql-toolbar button:focus .ql-stroke-miter,.ql-snow.ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter{stroke:#06c}@media (pointer:coarse){.ql-snow.ql-toolbar button:hover:not(.ql-active),.ql-snow .ql-toolbar button:hover:not(.ql-active){color:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill{fill:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter{stroke:#444}}.ql-snow{box-sizing:border-box}.ql-snow *{box-sizing:border-box}.ql-snow .ql-hidden{display:none}.ql-snow .ql-out-bottom,.ql-snow .ql-out-top{visibility:hidden}.ql-snow .ql-tooltip{position:absolute;transform:translateY(10px)}.ql-snow .ql-tooltip a{cursor:pointer;text-decoration:none}.ql-snow .ql-tooltip.ql-flip{transform:translateY(-10px)}.ql-snow .ql-formats{display:inline-block;vertical-align:middle}.ql-snow .ql-formats:after{clear:both;content:'';display:table}.ql-snow .ql-stroke{fill:none;stroke:#444;stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.ql-snow .ql-stroke-miter{fill:none;stroke:#444;stroke-miterlimit:10;stroke-width:2}.ql-snow .ql-fill,.ql-snow .ql-stroke.ql-fill{fill:#444}.ql-snow .ql-empty{fill:none}.ql-snow .ql-even{fill-rule:evenodd}.ql-snow .ql-thin,.ql-snow .ql-stroke.ql-thin{stroke-width:1}.ql-snow .ql-transparent{opacity:.4}.ql-snow .ql-direction svg:last-child{display:none}.ql-snow .ql-direction.ql-active svg:last-child{display:inline}.ql-snow .ql-direction.ql-active svg:first-child{display:none}.ql-snow .ql-editor h1{font-size:2em}.ql-snow .ql-editor h2{font-size:1.5em}.ql-snow .ql-editor h3{font-size:1.17em}.ql-snow .ql-editor h4{font-size:1em}.ql-snow .ql-editor h5{font-size:.83em}.ql-snow .ql-editor h6{font-size:.67em}.ql-snow .ql-editor a{text-decoration:underline}.ql-snow .ql-editor blockquote{border-left:4px solid #ccc;margin-bottom:5px;margin-top:5px;padding-left:16px}.ql-snow .ql-editor code,.ql-snow .ql-editor .ql-code-block-container{background-color:#f0f0f0;border-radius:3px}.ql-snow .ql-editor .ql-code-block-container{margin-bottom:5px;margin-top:5px;padding:5px 10px}.ql-snow .ql-editor code{font-size:85%;padding:2px 4px}.ql-snow .ql-editor .ql-code-block-container{background-color:#23241f;color:#f8f8f2;overflow:visible}.ql-snow .ql-editor img{max-width:100%}.ql-snow .ql-picker{color:#444;display:inline-block;float:left;font-size:14px;font-weight:500;height:24px;position:relative;vertical-align:middle}.ql-snow .ql-picker-label{cursor:pointer;display:inline-block;height:100%;padding-left:8px;padding-right:2px;position:relative;width:100%}.ql-snow .ql-picker-label::before{display:inline-block;line-height:22px}.ql-snow .ql-picker-options{background-color:#fff;display:none;min-width:100%;padding:4px 8px;position:absolute;white-space:nowrap}.ql-snow .ql-picker-options .ql-picker-item{cursor:pointer;display:block;padding-bottom:5px;padding-top:5px}.ql-snow .ql-picker.ql-expanded .ql-picker-label{color:#ccc;z-index:2}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-fill{fill:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-stroke{stroke:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-options{display:block;margin-top:-1px;top:100%;z-index:1}.ql-snow .ql-color-picker,.ql-snow .ql-icon-picker{width:28px}.ql-snow .ql-color-picker .ql-picker-label,.ql-snow .ql-icon-picker .ql-picker-label{padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-label svg,.ql-snow .ql-icon-picker .ql-picker-label svg{right:4px}.ql-snow .ql-icon-picker .ql-picker-options{padding:4px 0}.ql-snow .ql-icon-picker .ql-picker-item{height:24px;width:24px;padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-options{padding:3px 5px;width:152px}.ql-snow .ql-color-picker .ql-picker-item{border:1px solid transparent;float:left;height:16px;margin:2px;padding:0;width:16px}.ql-snow .ql-picker:not(.ql-color-picker):not(.ql-icon-picker) svg{position:absolute;margin-top:-9px;right:0;top:50%;width:18px}.ql-snow .ql-picker.ql-header .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-font .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-label]:not([data-label=''])::before{content:attr(data-label)}.ql-snow .ql-picker.ql-header{width:98px}.ql-snow .ql-picker.ql-header .ql-picker-label::before,.ql-snow .ql-picker.ql-header .ql-picker-item::before{content:'Normal'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"1\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{content:'Heading 1'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"2\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{content:'Heading 2'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"3\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{content:'Heading 3'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"4\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{content:'Heading 4'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"5\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{content:'Heading 5'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"6\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{content:'Heading 6'}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{font-size:2em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{font-size:1.5em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{font-size:1.17em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{font-size:1em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{font-size:.83em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{font-size:.67em}.ql-snow .ql-picker.ql-font{width:108px}.ql-snow .ql-picker.ql-font .ql-picker-label::before,.ql-snow .ql-picker.ql-font .ql-picker-item::before{content:'Sans Serif'}.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{content:'Serif'}.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{content:'Monospace'}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{font-family:Georgia,Times New Roman,serif}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{font-family:Monaco,Courier New,monospace}.ql-snow .ql-picker.ql-size{width:98px}.ql-snow .ql-picker.ql-size .ql-picker-label::before,.ql-snow .ql-picker.ql-size .ql-picker-item::before{content:'Normal'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before{content:'Small'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before{content:'Large'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{content:'Huge'}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before{font-size:10px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before{font-size:18px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{font-size:32px}.ql-snow .ql-color-picker.ql-background .ql-picker-item{background-color:#fff}.ql-snow .ql-color-picker.ql-color .ql-picker-item{background-color:#000}.ql-code-block-container{position:relative}.ql-code-block-container .ql-ui{right:5px;top:5px}.ql-toolbar.ql-snow{border:1px solid #ccc;box-sizing:border-box;font-family:'Helvetica Neue','Helvetica','Arial',sans-serif;padding:8px}.ql-toolbar.ql-snow .ql-formats{margin-right:15px}.ql-toolbar.ql-snow .ql-picker-label{border:1px solid transparent}.ql-toolbar.ql-snow .ql-picker-options{border:1px solid transparent;box-shadow:rgba(0,0,0,0.2) 0 2px 8px}.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-label{border-color:#ccc}.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options{border-color:#ccc}.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item.ql-selected,.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item:hover{border-color:#000}.ql-toolbar.ql-snow + .ql-container.ql-snow{border-top:0}.ql-snow .ql-tooltip{background-color:#fff;border:1px solid #ccc;box-shadow:0 0 5px #ddd;color:#444;padding:5px 12px;white-space:nowrap}.ql-snow .ql-tooltip::before{content:\"Visit URL:\";line-height:26px;margin-right:8px}.ql-snow .ql-tooltip input[type=text]{display:none;border:1px solid #ccc;font-size:13px;height:26px;margin:0;padding:3px 5px;width:170px}.ql-snow .ql-tooltip a.ql-preview{display:inline-block;max-width:200px;overflow-x:hidden;text-overflow:ellipsis;vertical-align:top}.ql-snow .ql-tooltip a.ql-action::after{border-right:1px solid #ccc;content:'Edit';margin-left:16px;padding-right:8px}.ql-snow .ql-tooltip a.ql-remove::before{content:'Remove';margin-left:8px}.ql-snow .ql-tooltip a{line-height:26px}.ql-snow .ql-tooltip.ql-editing a.ql-preview,.ql-snow .ql-tooltip.ql-editing a.ql-remove{display:none}.ql-snow .ql-tooltip.ql-editing input[type=text]{display:inline-block}.ql-snow .ql-tooltip.ql-editing a.ql-action::after{border-right:0;content:'Save';padding-right:0}.ql-snow .ql-tooltip[data-mode=link]::before{content:\"Enter link:\"}.ql-snow .ql-tooltip[data-mode=formula]::before{content:\"Enter formula:\"}.ql-snow .ql-tooltip[data-mode=video]::before{content:\"Enter video:\"}.ql-snow a{color:#06c}.ql-container.ql-snow{border:1px solid #ccc}\n\n/*# sourceMappingURL=quill.snow.css.map*/", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n", "/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n", "/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n", "/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n", "/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n", "import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n", "import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n", "import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n", "/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n", "import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n", "import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n", "import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n", "import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n", "import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n", "import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n", "import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n", "import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n", "import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n", "/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n", "import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n", "import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n", "import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n", "import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n", "import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n", "import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignMergeValue;\n", "import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n", "/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n", "import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nexport default baseMergeDeep;\n", "import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nexport default baseMerge;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nexport default merge;\n", "/**\n * @license\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"es\" -o ./`\n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\nexport { default as add } from './add.js';\nexport { default as after } from './after.js';\nexport { default as ary } from './ary.js';\nexport { default as assign } from './assign.js';\nexport { default as assignIn } from './assignIn.js';\nexport { default as assignInWith } from './assignInWith.js';\nexport { default as assignWith } from './assignWith.js';\nexport { default as at } from './at.js';\nexport { default as attempt } from './attempt.js';\nexport { default as before } from './before.js';\nexport { default as bind } from './bind.js';\nexport { default as bindAll } from './bindAll.js';\nexport { default as bindKey } from './bindKey.js';\nexport { default as camelCase } from './camelCase.js';\nexport { default as capitalize } from './capitalize.js';\nexport { default as castArray } from './castArray.js';\nexport { default as ceil } from './ceil.js';\nexport { default as chain } from './chain.js';\nexport { default as chunk } from './chunk.js';\nexport { default as clamp } from './clamp.js';\nexport { default as clone } from './clone.js';\nexport { default as cloneDeep } from './cloneDeep.js';\nexport { default as cloneDeepWith } from './cloneDeepWith.js';\nexport { default as cloneWith } from './cloneWith.js';\nexport { default as commit } from './commit.js';\nexport { default as compact } from './compact.js';\nexport { default as concat } from './concat.js';\nexport { default as cond } from './cond.js';\nexport { default as conforms } from './conforms.js';\nexport { default as conformsTo } from './conformsTo.js';\nexport { default as constant } from './constant.js';\nexport { default as countBy } from './countBy.js';\nexport { default as create } from './create.js';\nexport { default as curry } from './curry.js';\nexport { default as curryRight } from './curryRight.js';\nexport { default as debounce } from './debounce.js';\nexport { default as deburr } from './deburr.js';\nexport { default as defaultTo } from './defaultTo.js';\nexport { default as defaults } from './defaults.js';\nexport { default as defaultsDeep } from './defaultsDeep.js';\nexport { default as defer } from './defer.js';\nexport { default as delay } from './delay.js';\nexport { default as difference } from './difference.js';\nexport { default as differenceBy } from './differenceBy.js';\nexport { default as differenceWith } from './differenceWith.js';\nexport { default as divide } from './divide.js';\nexport { default as drop } from './drop.js';\nexport { default as dropRight } from './dropRight.js';\nexport { default as dropRightWhile } from './dropRightWhile.js';\nexport { default as dropWhile } from './dropWhile.js';\nexport { default as each } from './each.js';\nexport { default as eachRight } from './eachRight.js';\nexport { default as endsWith } from './endsWith.js';\nexport { default as entries } from './entries.js';\nexport { default as entriesIn } from './entriesIn.js';\nexport { default as eq } from './eq.js';\nexport { default as escape } from './escape.js';\nexport { default as escapeRegExp } from './escapeRegExp.js';\nexport { default as every } from './every.js';\nexport { default as extend } from './extend.js';\nexport { default as extendWith } from './extendWith.js';\nexport { default as fill } from './fill.js';\nexport { default as filter } from './filter.js';\nexport { default as find } from './find.js';\nexport { default as findIndex } from './findIndex.js';\nexport { default as findKey } from './findKey.js';\nexport { default as findLast } from './findLast.js';\nexport { default as findLastIndex } from './findLastIndex.js';\nexport { default as findLastKey } from './findLastKey.js';\nexport { default as first } from './first.js';\nexport { default as flatMap } from './flatMap.js';\nexport { default as flatMapDeep } from './flatMapDeep.js';\nexport { default as flatMapDepth } from './flatMapDepth.js';\nexport { default as flatten } from './flatten.js';\nexport { default as flattenDeep } from './flattenDeep.js';\nexport { default as flattenDepth } from './flattenDepth.js';\nexport { default as flip } from './flip.js';\nexport { default as floor } from './floor.js';\nexport { default as flow } from './flow.js';\nexport { default as flowRight } from './flowRight.js';\nexport { default as forEach } from './forEach.js';\nexport { default as forEachRight } from './forEachRight.js';\nexport { default as forIn } from './forIn.js';\nexport { default as forInRight } from './forInRight.js';\nexport { default as forOwn } from './forOwn.js';\nexport { default as forOwnRight } from './forOwnRight.js';\nexport { default as fromPairs } from './fromPairs.js';\nexport { default as functions } from './functions.js';\nexport { default as functionsIn } from './functionsIn.js';\nexport { default as get } from './get.js';\nexport { default as groupBy } from './groupBy.js';\nexport { default as gt } from './gt.js';\nexport { default as gte } from './gte.js';\nexport { default as has } from './has.js';\nexport { default as hasIn } from './hasIn.js';\nexport { default as head } from './head.js';\nexport { default as identity } from './identity.js';\nexport { default as inRange } from './inRange.js';\nexport { default as includes } from './includes.js';\nexport { default as indexOf } from './indexOf.js';\nexport { default as initial } from './initial.js';\nexport { default as intersection } from './intersection.js';\nexport { default as intersectionBy } from './intersectionBy.js';\nexport { default as intersectionWith } from './intersectionWith.js';\nexport { default as invert } from './invert.js';\nexport { default as invertBy } from './invertBy.js';\nexport { default as invoke } from './invoke.js';\nexport { default as invokeMap } from './invokeMap.js';\nexport { default as isArguments } from './isArguments.js';\nexport { default as isArray } from './isArray.js';\nexport { default as isArrayBuffer } from './isArrayBuffer.js';\nexport { default as isArrayLike } from './isArrayLike.js';\nexport { default as isArrayLikeObject } from './isArrayLikeObject.js';\nexport { default as isBoolean } from './isBoolean.js';\nexport { default as isBuffer } from './isBuffer.js';\nexport { default as isDate } from './isDate.js';\nexport { default as isElement } from './isElement.js';\nexport { default as isEmpty } from './isEmpty.js';\nexport { default as isEqual } from './isEqual.js';\nexport { default as isEqualWith } from './isEqualWith.js';\nexport { default as isError } from './isError.js';\nexport { default as isFinite } from './isFinite.js';\nexport { default as isFunction } from './isFunction.js';\nexport { default as isInteger } from './isInteger.js';\nexport { default as isLength } from './isLength.js';\nexport { default as isMap } from './isMap.js';\nexport { default as isMatch } from './isMatch.js';\nexport { default as isMatchWith } from './isMatchWith.js';\nexport { default as isNaN } from './isNaN.js';\nexport { default as isNative } from './isNative.js';\nexport { default as isNil } from './isNil.js';\nexport { default as isNull } from './isNull.js';\nexport { default as isNumber } from './isNumber.js';\nexport { default as isObject } from './isObject.js';\nexport { default as isObjectLike } from './isObjectLike.js';\nexport { default as isPlainObject } from './isPlainObject.js';\nexport { default as isRegExp } from './isRegExp.js';\nexport { default as isSafeInteger } from './isSafeInteger.js';\nexport { default as isSet } from './isSet.js';\nexport { default as isString } from './isString.js';\nexport { default as isSymbol } from './isSymbol.js';\nexport { default as isTypedArray } from './isTypedArray.js';\nexport { default as isUndefined } from './isUndefined.js';\nexport { default as isWeakMap } from './isWeakMap.js';\nexport { default as isWeakSet } from './isWeakSet.js';\nexport { default as iteratee } from './iteratee.js';\nexport { default as join } from './join.js';\nexport { default as kebabCase } from './kebabCase.js';\nexport { default as keyBy } from './keyBy.js';\nexport { default as keys } from './keys.js';\nexport { default as keysIn } from './keysIn.js';\nexport { default as last } from './last.js';\nexport { default as lastIndexOf } from './lastIndexOf.js';\nexport { default as lodash } from './wrapperLodash.js';\nexport { default as lowerCase } from './lowerCase.js';\nexport { default as lowerFirst } from './lowerFirst.js';\nexport { default as lt } from './lt.js';\nexport { default as lte } from './lte.js';\nexport { default as map } from './map.js';\nexport { default as mapKeys } from './mapKeys.js';\nexport { default as mapValues } from './mapValues.js';\nexport { default as matches } from './matches.js';\nexport { default as matchesProperty } from './matchesProperty.js';\nexport { default as max } from './max.js';\nexport { default as maxBy } from './maxBy.js';\nexport { default as mean } from './mean.js';\nexport { default as meanBy } from './meanBy.js';\nexport { default as memoize } from './memoize.js';\nexport { default as merge } from './merge.js';\nexport { default as mergeWith } from './mergeWith.js';\nexport { default as method } from './method.js';\nexport { default as methodOf } from './methodOf.js';\nexport { default as min } from './min.js';\nexport { default as minBy } from './minBy.js';\nexport { default as mixin } from './mixin.js';\nexport { default as multiply } from './multiply.js';\nexport { default as negate } from './negate.js';\nexport { default as next } from './next.js';\nexport { default as noop } from './noop.js';\nexport { default as now } from './now.js';\nexport { default as nth } from './nth.js';\nexport { default as nthArg } from './nthArg.js';\nexport { default as omit } from './omit.js';\nexport { default as omitBy } from './omitBy.js';\nexport { default as once } from './once.js';\nexport { default as orderBy } from './orderBy.js';\nexport { default as over } from './over.js';\nexport { default as overArgs } from './overArgs.js';\nexport { default as overEvery } from './overEvery.js';\nexport { default as overSome } from './overSome.js';\nexport { default as pad } from './pad.js';\nexport { default as padEnd } from './padEnd.js';\nexport { default as padStart } from './padStart.js';\nexport { default as parseInt } from './parseInt.js';\nexport { default as partial } from './partial.js';\nexport { default as partialRight } from './partialRight.js';\nexport { default as partition } from './partition.js';\nexport { default as pick } from './pick.js';\nexport { default as pickBy } from './pickBy.js';\nexport { default as plant } from './plant.js';\nexport { default as property } from './property.js';\nexport { default as propertyOf } from './propertyOf.js';\nexport { default as pull } from './pull.js';\nexport { default as pullAll } from './pullAll.js';\nexport { default as pullAllBy } from './pullAllBy.js';\nexport { default as pullAllWith } from './pullAllWith.js';\nexport { default as pullAt } from './pullAt.js';\nexport { default as random } from './random.js';\nexport { default as range } from './range.js';\nexport { default as rangeRight } from './rangeRight.js';\nexport { default as rearg } from './rearg.js';\nexport { default as reduce } from './reduce.js';\nexport { default as reduceRight } from './reduceRight.js';\nexport { default as reject } from './reject.js';\nexport { default as remove } from './remove.js';\nexport { default as repeat } from './repeat.js';\nexport { default as replace } from './replace.js';\nexport { default as rest } from './rest.js';\nexport { default as result } from './result.js';\nexport { default as reverse } from './reverse.js';\nexport { default as round } from './round.js';\nexport { default as sample } from './sample.js';\nexport { default as sampleSize } from './sampleSize.js';\nexport { default as set } from './set.js';\nexport { default as setWith } from './setWith.js';\nexport { default as shuffle } from './shuffle.js';\nexport { default as size } from './size.js';\nexport { default as slice } from './slice.js';\nexport { default as snakeCase } from './snakeCase.js';\nexport { default as some } from './some.js';\nexport { default as sortBy } from './sortBy.js';\nexport { default as sortedIndex } from './sortedIndex.js';\nexport { default as sortedIndexBy } from './sortedIndexBy.js';\nexport { default as sortedIndexOf } from './sortedIndexOf.js';\nexport { default as sortedLastIndex } from './sortedLastIndex.js';\nexport { default as sortedLastIndexBy } from './sortedLastIndexBy.js';\nexport { default as sortedLastIndexOf } from './sortedLastIndexOf.js';\nexport { default as sortedUniq } from './sortedUniq.js';\nexport { default as sortedUniqBy } from './sortedUniqBy.js';\nexport { default as split } from './split.js';\nexport { default as spread } from './spread.js';\nexport { default as startCase } from './startCase.js';\nexport { default as startsWith } from './startsWith.js';\nexport { default as stubArray } from './stubArray.js';\nexport { default as stubFalse } from './stubFalse.js';\nexport { default as stubObject } from './stubObject.js';\nexport { default as stubString } from './stubString.js';\nexport { default as stubTrue } from './stubTrue.js';\nexport { default as subtract } from './subtract.js';\nexport { default as sum } from './sum.js';\nexport { default as sumBy } from './sumBy.js';\nexport { default as tail } from './tail.js';\nexport { default as take } from './take.js';\nexport { default as takeRight } from './takeRight.js';\nexport { default as takeRightWhile } from './takeRightWhile.js';\nexport { default as takeWhile } from './takeWhile.js';\nexport { default as tap } from './tap.js';\nexport { default as template } from './template.js';\nexport { default as templateSettings } from './templateSettings.js';\nexport { default as throttle } from './throttle.js';\nexport { default as thru } from './thru.js';\nexport { default as times } from './times.js';\nexport { default as toArray } from './toArray.js';\nexport { default as toFinite } from './toFinite.js';\nexport { default as toInteger } from './toInteger.js';\nexport { default as toIterator } from './toIterator.js';\nexport { default as toJSON } from './toJSON.js';\nexport { default as toLength } from './toLength.js';\nexport { default as toLower } from './toLower.js';\nexport { default as toNumber } from './toNumber.js';\nexport { default as toPairs } from './toPairs.js';\nexport { default as toPairsIn } from './toPairsIn.js';\nexport { default as toPath } from './toPath.js';\nexport { default as toPlainObject } from './toPlainObject.js';\nexport { default as toSafeInteger } from './toSafeInteger.js';\nexport { default as toString } from './toString.js';\nexport { default as toUpper } from './toUpper.js';\nexport { default as transform } from './transform.js';\nexport { default as trim } from './trim.js';\nexport { default as trimEnd } from './trimEnd.js';\nexport { default as trimStart } from './trimStart.js';\nexport { default as truncate } from './truncate.js';\nexport { default as unary } from './unary.js';\nexport { default as unescape } from './unescape.js';\nexport { default as union } from './union.js';\nexport { default as unionBy } from './unionBy.js';\nexport { default as unionWith } from './unionWith.js';\nexport { default as uniq } from './uniq.js';\nexport { default as uniqBy } from './uniqBy.js';\nexport { default as uniqWith } from './uniqWith.js';\nexport { default as uniqueId } from './uniqueId.js';\nexport { default as unset } from './unset.js';\nexport { default as unzip } from './unzip.js';\nexport { default as unzipWith } from './unzipWith.js';\nexport { default as update } from './update.js';\nexport { default as updateWith } from './updateWith.js';\nexport { default as upperCase } from './upperCase.js';\nexport { default as upperFirst } from './upperFirst.js';\nexport { default as value } from './value.js';\nexport { default as valueOf } from './valueOf.js';\nexport { default as values } from './values.js';\nexport { default as valuesIn } from './valuesIn.js';\nexport { default as without } from './without.js';\nexport { default as words } from './words.js';\nexport { default as wrap } from './wrap.js';\nexport { default as wrapperAt } from './wrapperAt.js';\nexport { default as wrapperChain } from './wrapperChain.js';\nexport { default as wrapperCommit } from './commit.js';\nexport { default as wrapperLodash } from './wrapperLodash.js';\nexport { default as wrapperNext } from './next.js';\nexport { default as wrapperPlant } from './plant.js';\nexport { default as wrapperReverse } from './wrapperReverse.js';\nexport { default as wrapperToIterator } from './toIterator.js';\nexport { default as wrapperValue } from './wrapperValue.js';\nexport { default as xor } from './xor.js';\nexport { default as xorBy } from './xorBy.js';\nexport { default as xorWith } from './xorWith.js';\nexport { default as zip } from './zip.js';\nexport { default as zipObject } from './zipObject.js';\nexport { default as zipObjectDeep } from './zipObjectDeep.js';\nexport { default as zipWith } from './zipWith.js';\nexport { default } from './lodash.default.js';\n", "enum Scope {\n TYPE = (1 << 2) - 1, // 0011 Lower two bits\n LEVEL = ((1 << 2) - 1) << 2, // 1100 Higher two bits\n\n ATTRIBUTE = (1 << 0) | LEVEL, // 1101\n BLOT = (1 << 1) | LEVEL, // 1110\n INLINE = (1 << 2) | TYPE, // 0111\n BLOCK = (1 << 3) | TYPE, // 1011\n\n BLOCK_BLOT = BLOCK & BLOT, // 1010\n INLINE_BLOT = INLINE & BLOT, // 0110\n BLOCK_ATTRIBUTE = BLOCK & ATTRIBUTE, // 1001\n INLINE_ATTRIBUTE = INLINE & ATTRIBUTE, // 0101\n\n ANY = TYPE | LEVEL,\n}\n\nexport default Scope;\n", "import Scope from '../scope.js';\n\nexport interface AttributorOptions {\n scope?: Scope;\n whitelist?: string[];\n}\n\nexport default class Attributor {\n public static keys(node: HTMLElement): string[] {\n return Array.from(node.attributes).map((item: Attr) => item.name);\n }\n\n public scope: Scope;\n public whitelist: string[] | undefined;\n\n constructor(\n public readonly attrName: string,\n public readonly keyName: string,\n options: AttributorOptions = {},\n ) {\n const attributeBit = Scope.TYPE & Scope.ATTRIBUTE;\n this.scope =\n options.scope != null\n ? // Ignore type bits, force attribute bit\n (options.scope & Scope.LEVEL) | attributeBit\n : Scope.ATTRIBUTE;\n if (options.whitelist != null) {\n this.whitelist = options.whitelist;\n }\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n node.setAttribute(this.keyName, value);\n return true;\n }\n\n public canAdd(_node: HTMLElement, value: any): boolean {\n if (this.whitelist == null) {\n return true;\n }\n if (typeof value === 'string') {\n return this.whitelist.indexOf(value.replace(/[\"']/g, '')) > -1;\n } else {\n return this.whitelist.indexOf(value) > -1;\n }\n }\n\n public remove(node: HTMLElement): void {\n node.removeAttribute(this.keyName);\n }\n\n public value(node: HTMLElement): any {\n const value = node.getAttribute(this.keyName);\n if (this.canAdd(node, value) && value) {\n return value;\n }\n return '';\n }\n}\n", "export default class ParchmentError extends Error {\n public message: string;\n public name: string;\n public stack!: string;\n\n constructor(message: string) {\n message = '[Parchment] ' + message;\n super(message);\n this.message = message;\n this.name = this.constructor.name;\n }\n}\n", "import Attributor from './attributor/attributor.js';\nimport {\n type Blot,\n type BlotConstructor,\n type Root,\n} from './blot/abstract/blot.js';\nimport ParchmentError from './error.js';\nimport Scope from './scope.js';\n\nexport type RegistryDefinition = Attributor | BlotConstructor;\n\nexport interface RegistryInterface {\n create(scroll: Root, input: Node | string | Scope, value?: any): Blot;\n query(query: string | Node | Scope, scope: Scope): RegistryDefinition | null;\n register(...definitions: any[]): any;\n}\n\nexport default class Registry implements RegistryInterface {\n public static blots = new WeakMap();\n\n public static find(node?: Node | null, bubble = false): Blot | null {\n if (node == null) {\n return null;\n }\n if (this.blots.has(node)) {\n return this.blots.get(node) || null;\n }\n if (bubble) {\n let parentNode: Node | null = null;\n try {\n parentNode = node.parentNode;\n } catch (err) {\n // Probably hit a permission denied error.\n // A known case is in Firefox, event targets can be anonymous DIVs\n // inside an input element.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=208427\n return null;\n }\n return this.find(parentNode, bubble);\n }\n return null;\n }\n\n private attributes: { [key: string]: Attributor } = {};\n private classes: { [key: string]: BlotConstructor } = {};\n private tags: { [key: string]: BlotConstructor } = {};\n private types: { [key: string]: RegistryDefinition } = {};\n\n public create(scroll: Root, input: Node | string | Scope, value?: any): Blot {\n const match = this.query(input);\n if (match == null) {\n throw new ParchmentError(`Unable to create ${input} blot`);\n }\n const blotClass = match as BlotConstructor;\n const node =\n // @ts-expect-error Fix me later\n input instanceof Node || input.nodeType === Node.TEXT_NODE\n ? input\n : blotClass.create(value);\n\n const blot = new blotClass(scroll, node as Node, value);\n Registry.blots.set(blot.domNode, blot);\n return blot;\n }\n\n public find(node: Node | null, bubble = false): Blot | null {\n return Registry.find(node, bubble);\n }\n\n public query(\n query: string | Node | Scope,\n scope: Scope = Scope.ANY,\n ): RegistryDefinition | null {\n let match;\n if (typeof query === 'string') {\n match = this.types[query] || this.attributes[query];\n // @ts-expect-error Fix me later\n } else if (query instanceof Text || query.nodeType === Node.TEXT_NODE) {\n match = this.types.text;\n } else if (typeof query === 'number') {\n if (query & Scope.LEVEL & Scope.BLOCK) {\n match = this.types.block;\n } else if (query & Scope.LEVEL & Scope.INLINE) {\n match = this.types.inline;\n }\n } else if (query instanceof Element) {\n const names = (query.getAttribute('class') || '').split(/\\s+/);\n names.some((name) => {\n match = this.classes[name];\n if (match) {\n return true;\n }\n return false;\n });\n match = match || this.tags[query.tagName];\n }\n if (match == null) {\n return null;\n }\n if (\n 'scope' in match &&\n scope & Scope.LEVEL & match.scope &&\n scope & Scope.TYPE & match.scope\n ) {\n return match;\n }\n return null;\n }\n\n public register(...definitions: RegistryDefinition[]): RegistryDefinition[] {\n return definitions.map((definition) => {\n const isBlot = 'blotName' in definition;\n const isAttr = 'attrName' in definition;\n if (!isBlot && !isAttr) {\n throw new ParchmentError('Invalid definition');\n } else if (isBlot && definition.blotName === 'abstract') {\n throw new ParchmentError('Cannot register abstract class');\n }\n const key = isBlot\n ? definition.blotName\n : isAttr\n ? definition.attrName\n : (undefined as never); // already handled by above checks\n this.types[key] = definition;\n\n if (isAttr) {\n if (typeof definition.keyName === 'string') {\n this.attributes[definition.keyName] = definition;\n }\n } else if (isBlot) {\n if (definition.className) {\n this.classes[definition.className] = definition;\n }\n if (definition.tagName) {\n if (Array.isArray(definition.tagName)) {\n definition.tagName = definition.tagName.map((tagName: string) => {\n return tagName.toUpperCase();\n });\n } else {\n definition.tagName = definition.tagName.toUpperCase();\n }\n const tagNames = Array.isArray(definition.tagName)\n ? definition.tagName\n : [definition.tagName];\n tagNames.forEach((tag: string) => {\n if (this.tags[tag] == null || definition.className == null) {\n this.tags[tag] = definition;\n }\n });\n }\n }\n return definition;\n });\n }\n}\n", "import Attributor from './attributor.js';\n\nfunction match(node: HTMLElement, prefix: string): string[] {\n const className = node.getAttribute('class') || '';\n return className\n .split(/\\s+/)\n .filter((name) => name.indexOf(`${prefix}-`) === 0);\n}\n\nclass ClassAttributor extends Attributor {\n public static keys(node: HTMLElement): string[] {\n return (node.getAttribute('class') || '')\n .split(/\\s+/)\n .map((name) => name.split('-').slice(0, -1).join('-'));\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n this.remove(node);\n node.classList.add(`${this.keyName}-${value}`);\n return true;\n }\n\n public remove(node: HTMLElement): void {\n const matches = match(node, this.keyName);\n matches.forEach((name) => {\n node.classList.remove(name);\n });\n if (node.classList.length === 0) {\n node.removeAttribute('class');\n }\n }\n\n public value(node: HTMLElement): any {\n const result = match(node, this.keyName)[0] || '';\n const value = result.slice(this.keyName.length + 1); // +1 for hyphen\n return this.canAdd(node, value) ? value : '';\n }\n}\n\nexport default ClassAttributor;\n", "import Attributor from './attributor.js';\n\nfunction camelize(name: string): string {\n const parts = name.split('-');\n const rest = parts\n .slice(1)\n .map((part: string) => part[0].toUpperCase() + part.slice(1))\n .join('');\n return parts[0] + rest;\n}\n\nclass StyleAttributor extends Attributor {\n public static keys(node: HTMLElement): string[] {\n return (node.getAttribute('style') || '').split(';').map((value) => {\n const arr = value.split(':');\n return arr[0].trim();\n });\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n // @ts-expect-error Fix me later\n node.style[camelize(this.keyName)] = value;\n return true;\n }\n\n public remove(node: HTMLElement): void {\n // @ts-expect-error Fix me later\n node.style[camelize(this.keyName)] = '';\n if (!node.getAttribute('style')) {\n node.removeAttribute('style');\n }\n }\n\n public value(node: HTMLElement): any {\n // @ts-expect-error Fix me later\n const value = node.style[camelize(this.keyName)];\n return this.canAdd(node, value) ? value : '';\n }\n}\n\nexport default StyleAttributor;\n", "import type { Formattable } from '../blot/abstract/blot.js';\nimport Registry from '../registry.js';\nimport Scope from '../scope.js';\nimport Attributor from './attributor.js';\nimport ClassAttributor from './class.js';\nimport StyleAttributor from './style.js';\n\nclass AttributorStore {\n private attributes: { [key: string]: Attributor } = {};\n private domNode: HTMLElement;\n\n constructor(domNode: HTMLElement) {\n this.domNode = domNode;\n this.build();\n }\n\n public attribute(attribute: Attributor, value: any): void {\n // verb\n if (value) {\n if (attribute.add(this.domNode, value)) {\n if (attribute.value(this.domNode) != null) {\n this.attributes[attribute.attrName] = attribute;\n } else {\n delete this.attributes[attribute.attrName];\n }\n }\n } else {\n attribute.remove(this.domNode);\n delete this.attributes[attribute.attrName];\n }\n }\n\n public build(): void {\n this.attributes = {};\n const blot = Registry.find(this.domNode);\n if (blot == null) {\n return;\n }\n const attributes = Attributor.keys(this.domNode);\n const classes = ClassAttributor.keys(this.domNode);\n const styles = StyleAttributor.keys(this.domNode);\n attributes\n .concat(classes)\n .concat(styles)\n .forEach((name) => {\n const attr = blot.scroll.query(name, Scope.ATTRIBUTE);\n if (attr instanceof Attributor) {\n this.attributes[attr.attrName] = attr;\n }\n });\n }\n\n public copy(target: Formattable): void {\n Object.keys(this.attributes).forEach((key) => {\n const value = this.attributes[key].value(this.domNode);\n target.format(key, value);\n });\n }\n\n public move(target: Formattable): void {\n this.copy(target);\n Object.keys(this.attributes).forEach((key) => {\n this.attributes[key].remove(this.domNode);\n });\n this.attributes = {};\n }\n\n public values(): { [key: string]: any } {\n return Object.keys(this.attributes).reduce(\n (attributes: { [key: string]: any }, name: string) => {\n attributes[name] = this.attributes[name].value(this.domNode);\n return attributes;\n },\n {},\n );\n }\n}\n\nexport default AttributorStore;\n", "import ParchmentError from '../../error.js';\nimport Registry from '../../registry.js';\nimport Scope from '../../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Parent,\n Root,\n} from './blot.js';\n\nclass ShadowBlot implements Blot {\n public static blotName = 'abstract';\n public static className: string;\n public static requiredContainer: BlotConstructor;\n public static scope: Scope;\n public static tagName: string | string[];\n\n public static create(rawValue?: unknown): Node {\n if (this.tagName == null) {\n throw new ParchmentError('Blot definition missing tagName');\n }\n let node: HTMLElement;\n let value: string | number | undefined;\n if (Array.isArray(this.tagName)) {\n if (typeof rawValue === 'string') {\n value = rawValue.toUpperCase();\n if (parseInt(value, 10).toString() === value) {\n value = parseInt(value, 10);\n }\n } else if (typeof rawValue === 'number') {\n value = rawValue;\n }\n if (typeof value === 'number') {\n node = document.createElement(this.tagName[value - 1]);\n } else if (value && this.tagName.indexOf(value) > -1) {\n node = document.createElement(value);\n } else {\n node = document.createElement(this.tagName[0]);\n }\n } else {\n node = document.createElement(this.tagName);\n }\n if (this.className) {\n node.classList.add(this.className);\n }\n return node;\n }\n\n public prev: Blot | null;\n public next: Blot | null;\n // @ts-expect-error Fix me later\n public parent: Parent;\n\n // Hack for accessing inherited static methods\n get statics(): any {\n return this.constructor;\n }\n constructor(\n public scroll: Root,\n public domNode: Node,\n ) {\n Registry.blots.set(domNode, this);\n this.prev = null;\n this.next = null;\n }\n\n public attach(): void {\n // Nothing to do\n }\n\n public clone(): Blot {\n const domNode = this.domNode.cloneNode(false);\n return this.scroll.create(domNode);\n }\n\n public detach(): void {\n if (this.parent != null) {\n this.parent.removeChild(this);\n }\n Registry.blots.delete(this.domNode);\n }\n\n public deleteAt(index: number, length: number): void {\n const blot = this.isolate(index, length);\n blot.remove();\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n const blot = this.isolate(index, length);\n if (this.scroll.query(name, Scope.BLOT) != null && value) {\n blot.wrap(name, value);\n } else if (this.scroll.query(name, Scope.ATTRIBUTE) != null) {\n const parent = this.scroll.create(this.statics.scope) as Parent &\n Formattable;\n blot.wrap(parent);\n parent.format(name, value);\n }\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n const blot =\n def == null\n ? this.scroll.create('text', value)\n : this.scroll.create(value, def);\n const ref = this.split(index);\n this.parent.insertBefore(blot, ref || undefined);\n }\n\n public isolate(index: number, length: number): Blot {\n const target = this.split(index);\n if (target == null) {\n throw new Error('Attempt to isolate at end');\n }\n target.split(length);\n return target;\n }\n\n public length(): number {\n return 1;\n }\n\n public offset(root: Blot = this.parent): number {\n if (this.parent == null || this === root) {\n return 0;\n }\n return this.parent.children.offset(this) + this.parent.offset(root);\n }\n\n public optimize(_context?: { [key: string]: any }): void {\n if (\n this.statics.requiredContainer &&\n !(this.parent instanceof this.statics.requiredContainer)\n ) {\n this.wrap(this.statics.requiredContainer.blotName);\n }\n }\n\n public remove(): void {\n if (this.domNode.parentNode != null) {\n this.domNode.parentNode.removeChild(this.domNode);\n }\n this.detach();\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement =\n typeof name === 'string' ? this.scroll.create(name, value) : name;\n if (this.parent != null) {\n this.parent.insertBefore(replacement, this.next || undefined);\n this.remove();\n }\n return replacement;\n }\n\n public split(index: number, _force?: boolean): Blot | null {\n return index === 0 ? this : this.next;\n }\n\n public update(\n _mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n // Nothing to do by default\n }\n\n public wrap(name: string | Parent, value?: any): Parent {\n const wrapper =\n typeof name === 'string'\n ? (this.scroll.create(name, value) as Parent)\n : name;\n if (this.parent != null) {\n this.parent.insertBefore(wrapper, this.next || undefined);\n }\n if (typeof wrapper.appendChild !== 'function') {\n throw new ParchmentError(`Cannot wrap ${name}`);\n }\n wrapper.appendChild(this);\n return wrapper;\n }\n}\n\nexport default ShadowBlot;\n", "import Scope from '../../scope.js';\nimport type { Leaf } from './blot.js';\nimport ShadowBlot from './shadow.js';\n\nclass LeafBlot extends ShadowBlot implements Leaf {\n public static scope = Scope.INLINE_BLOT;\n\n /**\n * Returns the value represented by domNode if it is this Blot's type\n * No checking that domNode can represent this Blot type is required so\n * applications needing it should check externally before calling.\n */\n public static value(_domNode: Node): any {\n return true;\n }\n\n /**\n * Given location represented by node and offset from DOM Selection Range,\n * return index to that location.\n */\n public index(node: Node, offset: number): number {\n if (\n this.domNode === node ||\n this.domNode.compareDocumentPosition(node) &\n Node.DOCUMENT_POSITION_CONTAINED_BY\n ) {\n return Math.min(offset, 1);\n }\n return -1;\n }\n\n /**\n * Given index to location within blot, return node and offset representing\n * that location, consumable by DOM Selection Range\n */\n public position(index: number, _inclusive?: boolean): [Node, number] {\n const childNodes: Node[] = Array.from(this.parent.domNode.childNodes);\n let offset = childNodes.indexOf(this.domNode);\n if (index > 0) {\n offset += 1;\n }\n return [this.parent.domNode, offset];\n }\n\n /**\n * Return value represented by this blot\n * Should not change without interaction from API or\n * user change detectable by update()\n */\n public value(): any {\n return {\n [this.statics.blotName]: this.statics.value(this.domNode) || true,\n };\n }\n}\n\nexport default LeafBlot;\n", "import type LinkedNode from './linked-node.js';\n\nclass LinkedList {\n public head: T | null;\n public tail: T | null;\n public length: number;\n\n constructor() {\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n public append(...nodes: T[]): void {\n this.insertBefore(nodes[0], null);\n if (nodes.length > 1) {\n const rest = nodes.slice(1);\n this.append(...rest);\n }\n }\n\n public at(index: number): T | null {\n const next = this.iterator();\n let cur = next();\n while (cur && index > 0) {\n index -= 1;\n cur = next();\n }\n return cur;\n }\n\n public contains(node: T): boolean {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n if (cur === node) {\n return true;\n }\n cur = next();\n }\n return false;\n }\n\n public indexOf(node: T): number {\n const next = this.iterator();\n let cur = next();\n let index = 0;\n while (cur) {\n if (cur === node) {\n return index;\n }\n index += 1;\n cur = next();\n }\n return -1;\n }\n\n public insertBefore(node: T | null, refNode: T | null): void {\n if (node == null) {\n return;\n }\n this.remove(node);\n node.next = refNode;\n if (refNode != null) {\n node.prev = refNode.prev;\n if (refNode.prev != null) {\n refNode.prev.next = node;\n }\n refNode.prev = node;\n if (refNode === this.head) {\n this.head = node;\n }\n } else if (this.tail != null) {\n this.tail.next = node;\n node.prev = this.tail;\n this.tail = node;\n } else {\n node.prev = null;\n this.head = this.tail = node;\n }\n this.length += 1;\n }\n\n public offset(target: T): number {\n let index = 0;\n let cur = this.head;\n while (cur != null) {\n if (cur === target) {\n return index;\n }\n index += cur.length();\n cur = cur.next as T;\n }\n return -1;\n }\n\n public remove(node: T): void {\n if (!this.contains(node)) {\n return;\n }\n if (node.prev != null) {\n node.prev.next = node.next;\n }\n if (node.next != null) {\n node.next.prev = node.prev;\n }\n if (node === this.head) {\n this.head = node.next as T;\n }\n if (node === this.tail) {\n this.tail = node.prev as T;\n }\n this.length -= 1;\n }\n\n public iterator(curNode: T | null = this.head): () => T | null {\n // TODO use yield when we can\n return (): T | null => {\n const ret = curNode;\n if (curNode != null) {\n curNode = curNode.next as T;\n }\n return ret;\n };\n }\n\n public find(index: number, inclusive = false): [T | null, number] {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n const length = cur.length();\n if (\n index < length ||\n (inclusive &&\n index === length &&\n (cur.next == null || cur.next.length() !== 0))\n ) {\n return [cur, index];\n }\n index -= length;\n cur = next();\n }\n return [null, 0];\n }\n\n public forEach(callback: (cur: T) => void): void {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n callback(cur);\n cur = next();\n }\n }\n\n public forEachAt(\n index: number,\n length: number,\n callback: (cur: T, offset: number, length: number) => void,\n ): void {\n if (length <= 0) {\n return;\n }\n const [startNode, offset] = this.find(index);\n let curIndex = index - offset;\n const next = this.iterator(startNode);\n let cur = next();\n while (cur && curIndex < index + length) {\n const curLength = cur.length();\n if (index > curIndex) {\n callback(\n cur,\n index - curIndex,\n Math.min(length, curIndex + curLength - index),\n );\n } else {\n callback(cur, 0, Math.min(curLength, index + length - curIndex));\n }\n curIndex += curLength;\n cur = next();\n }\n }\n\n public map(callback: (cur: T) => any): any[] {\n return this.reduce((memo: T[], cur: T) => {\n memo.push(callback(cur));\n return memo;\n }, []);\n }\n\n public reduce(callback: (memo: M, cur: T) => M, memo: M): M {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n memo = callback(memo, cur);\n cur = next();\n }\n return memo;\n }\n}\n\nexport default LinkedList;\n", "import LinkedList from '../../collection/linked-list.js';\nimport ParchmentError from '../../error.js';\nimport Scope from '../../scope.js';\nimport type { Blot, BlotConstructor, Parent, Root } from './blot.js';\nimport ShadowBlot from './shadow.js';\n\nfunction makeAttachedBlot(node: Node, scroll: Root): Blot {\n const found = scroll.find(node);\n if (found) return found;\n try {\n return scroll.create(node);\n } catch (e) {\n const blot = scroll.create(Scope.INLINE);\n Array.from(node.childNodes).forEach((child: Node) => {\n blot.domNode.appendChild(child);\n });\n if (node.parentNode) {\n node.parentNode.replaceChild(blot.domNode, node);\n }\n blot.attach();\n return blot;\n }\n}\n\nclass ParentBlot extends ShadowBlot implements Parent {\n /**\n * Whitelist array of Blots that can be direct children.\n */\n public static allowedChildren?: BlotConstructor[];\n\n /**\n * Default child blot to be inserted if this blot becomes empty.\n */\n public static defaultChild?: BlotConstructor;\n public static uiClass = '';\n\n public children!: LinkedList;\n public domNode!: HTMLElement;\n public uiNode: HTMLElement | null = null;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.build();\n }\n\n public appendChild(other: Blot): void {\n this.insertBefore(other);\n }\n\n public attach(): void {\n super.attach();\n this.children.forEach((child) => {\n child.attach();\n });\n }\n\n public attachUI(node: HTMLElement): void {\n if (this.uiNode != null) {\n this.uiNode.remove();\n }\n this.uiNode = node;\n if (ParentBlot.uiClass) {\n this.uiNode.classList.add(ParentBlot.uiClass);\n }\n this.uiNode.setAttribute('contenteditable', 'false');\n this.domNode.insertBefore(this.uiNode, this.domNode.firstChild);\n }\n\n /**\n * Called during construction, should fill its own children LinkedList.\n */\n public build(): void {\n this.children = new LinkedList();\n // Need to be reversed for if DOM nodes already in order\n Array.from(this.domNode.childNodes)\n .filter((node: Node) => node !== this.uiNode)\n .reverse()\n .forEach((node: Node) => {\n try {\n const child = makeAttachedBlot(node, this.scroll);\n this.insertBefore(child, this.children.head || undefined);\n } catch (err) {\n if (err instanceof ParchmentError) {\n return;\n } else {\n throw err;\n }\n }\n });\n }\n\n public deleteAt(index: number, length: number): void {\n if (index === 0 && length === this.length()) {\n return this.remove();\n }\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.deleteAt(offset, childLength);\n });\n }\n\n public descendant(\n criteria: new (...args: any[]) => T,\n index: number,\n ): [T | null, number];\n public descendant(\n criteria: (blot: Blot) => boolean,\n index: number,\n ): [Blot | null, number];\n public descendant(criteria: any, index = 0): [Blot | null, number] {\n const [child, offset] = this.children.find(index);\n if (\n (criteria.blotName == null && criteria(child)) ||\n (criteria.blotName != null && child instanceof criteria)\n ) {\n return [child as any, offset];\n } else if (child instanceof ParentBlot) {\n return child.descendant(criteria, offset);\n } else {\n return [null, -1];\n }\n }\n\n public descendants(\n criteria: new (...args: any[]) => T,\n index?: number,\n length?: number,\n ): T[];\n public descendants(\n criteria: (blot: Blot) => boolean,\n index?: number,\n length?: number,\n ): Blot[];\n public descendants(\n criteria: any,\n index = 0,\n length: number = Number.MAX_VALUE,\n ): Blot[] {\n let descendants: Blot[] = [];\n let lengthLeft = length;\n this.children.forEachAt(\n index,\n length,\n (child: Blot, childIndex: number, childLength: number) => {\n if (\n (criteria.blotName == null && criteria(child)) ||\n (criteria.blotName != null && child instanceof criteria)\n ) {\n descendants.push(child);\n }\n if (child instanceof ParentBlot) {\n descendants = descendants.concat(\n child.descendants(criteria, childIndex, lengthLeft),\n );\n }\n lengthLeft -= childLength;\n },\n );\n return descendants;\n }\n\n public detach(): void {\n this.children.forEach((child) => {\n child.detach();\n });\n super.detach();\n }\n\n public enforceAllowedChildren(): void {\n let done = false;\n this.children.forEach((child: Blot) => {\n if (done) {\n return;\n }\n const allowed = this.statics.allowedChildren.some(\n (def: BlotConstructor) => child instanceof def,\n );\n if (allowed) {\n return;\n }\n if (child.statics.scope === Scope.BLOCK_BLOT) {\n if (child.next != null) {\n this.splitAfter(child);\n }\n if (child.prev != null) {\n this.splitAfter(child.prev);\n }\n child.parent.unwrap();\n done = true;\n } else if (child instanceof ParentBlot) {\n child.unwrap();\n } else {\n child.remove();\n }\n });\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.formatAt(offset, childLength, name, value);\n });\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n const [child, offset] = this.children.find(index);\n if (child) {\n child.insertAt(offset, value, def);\n } else {\n const blot =\n def == null\n ? this.scroll.create('text', value)\n : this.scroll.create(value, def);\n this.appendChild(blot);\n }\n }\n\n public insertBefore(childBlot: Blot, refBlot?: Blot | null): void {\n if (childBlot.parent != null) {\n childBlot.parent.children.remove(childBlot);\n }\n let refDomNode: Node | null = null;\n this.children.insertBefore(childBlot, refBlot || null);\n childBlot.parent = this;\n if (refBlot != null) {\n refDomNode = refBlot.domNode;\n }\n if (\n this.domNode.parentNode !== childBlot.domNode ||\n this.domNode.nextSibling !== refDomNode\n ) {\n this.domNode.insertBefore(childBlot.domNode, refDomNode);\n }\n childBlot.attach();\n }\n\n public length(): number {\n return this.children.reduce((memo, child) => {\n return memo + child.length();\n }, 0);\n }\n\n public moveChildren(targetParent: Parent, refNode?: Blot | null): void {\n this.children.forEach((child) => {\n targetParent.insertBefore(child, refNode);\n });\n }\n\n public optimize(context?: { [key: string]: any }): void {\n super.optimize(context);\n this.enforceAllowedChildren();\n if (this.uiNode != null && this.uiNode !== this.domNode.firstChild) {\n this.domNode.insertBefore(this.uiNode, this.domNode.firstChild);\n }\n if (this.children.length === 0) {\n if (this.statics.defaultChild != null) {\n const child = this.scroll.create(this.statics.defaultChild.blotName);\n this.appendChild(child);\n // TODO double check if necessary\n // child.optimize(context);\n } else {\n this.remove();\n }\n }\n }\n\n public path(index: number, inclusive = false): [Blot, number][] {\n const [child, offset] = this.children.find(index, inclusive);\n const position: [Blot, number][] = [[this, index]];\n if (child instanceof ParentBlot) {\n return position.concat(child.path(offset, inclusive));\n } else if (child != null) {\n position.push([child, offset]);\n }\n return position;\n }\n\n public removeChild(child: Blot): void {\n this.children.remove(child);\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement =\n typeof name === 'string' ? this.scroll.create(name, value) : name;\n if (replacement instanceof ParentBlot) {\n this.moveChildren(replacement);\n }\n return super.replaceWith(replacement);\n }\n\n public split(index: number, force = false): Blot | null {\n if (!force) {\n if (index === 0) {\n return this;\n }\n if (index === this.length()) {\n return this.next;\n }\n }\n const after = this.clone() as ParentBlot;\n if (this.parent) {\n this.parent.insertBefore(after, this.next || undefined);\n }\n this.children.forEachAt(index, this.length(), (child, offset, _length) => {\n const split = child.split(offset, force);\n if (split != null) {\n after.appendChild(split);\n }\n });\n return after;\n }\n\n public splitAfter(child: Blot): Parent {\n const after = this.clone() as ParentBlot;\n while (child.next != null) {\n after.appendChild(child.next);\n }\n if (this.parent) {\n this.parent.insertBefore(after, this.next || undefined);\n }\n return after;\n }\n\n public unwrap(): void {\n if (this.parent) {\n this.moveChildren(this.parent, this.next || undefined);\n }\n this.remove();\n }\n\n public update(\n mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n const addedNodes: Node[] = [];\n const removedNodes: Node[] = [];\n mutations.forEach((mutation) => {\n if (mutation.target === this.domNode && mutation.type === 'childList') {\n addedNodes.push(...mutation.addedNodes);\n removedNodes.push(...mutation.removedNodes);\n }\n });\n removedNodes.forEach((node: Node) => {\n // Check node has actually been removed\n // One exception is Chrome does not immediately remove IFRAMEs\n // from DOM but MutationRecord is correct in its reported removal\n if (\n node.parentNode != null &&\n // @ts-expect-error Fix me later\n node.tagName !== 'IFRAME' &&\n document.body.compareDocumentPosition(node) &\n Node.DOCUMENT_POSITION_CONTAINED_BY\n ) {\n return;\n }\n const blot = this.scroll.find(node);\n if (blot == null) {\n return;\n }\n if (\n blot.domNode.parentNode == null ||\n blot.domNode.parentNode === this.domNode\n ) {\n blot.detach();\n }\n });\n addedNodes\n .filter((node) => {\n return node.parentNode === this.domNode && node !== this.uiNode;\n })\n .sort((a, b) => {\n if (a === b) {\n return 0;\n }\n if (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) {\n return 1;\n }\n return -1;\n })\n .forEach((node) => {\n let refBlot: Blot | null = null;\n if (node.nextSibling != null) {\n refBlot = this.scroll.find(node.nextSibling);\n }\n const blot = makeAttachedBlot(node, this.scroll);\n if (blot.next !== refBlot || blot.next == null) {\n if (blot.parent != null) {\n blot.parent.removeChild(this);\n }\n this.insertBefore(blot, refBlot || undefined);\n }\n });\n this.enforceAllowedChildren();\n }\n}\n\nexport default ParentBlot;\n", "import Attributor from '../attributor/attributor.js';\nimport AttributorStore from '../attributor/store.js';\nimport Scope from '../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Parent,\n Root,\n} from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\nimport ParentBlot from './abstract/parent.js';\n\n// Shallow object comparison\nfunction isEqual(\n obj1: Record,\n obj2: Record,\n): boolean {\n if (Object.keys(obj1).length !== Object.keys(obj2).length) {\n return false;\n }\n for (const prop in obj1) {\n if (obj1[prop] !== obj2[prop]) {\n return false;\n }\n }\n return true;\n}\n\nclass InlineBlot extends ParentBlot implements Formattable {\n public static allowedChildren: BlotConstructor[] = [InlineBlot, LeafBlot];\n public static blotName = 'inline';\n public static scope = Scope.INLINE_BLOT;\n public static tagName: string | string[] = 'SPAN';\n\n static create(value?: unknown) {\n return super.create(value) as HTMLElement;\n }\n\n public static formats(domNode: HTMLElement, scroll: Root): any {\n const match = scroll.query(InlineBlot.blotName);\n if (\n match != null &&\n domNode.tagName === (match as BlotConstructor).tagName\n ) {\n return undefined;\n } else if (typeof this.tagName === 'string') {\n return true;\n } else if (Array.isArray(this.tagName)) {\n return domNode.tagName.toLowerCase();\n }\n return undefined;\n }\n\n protected attributes: AttributorStore;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.attributes = new AttributorStore(this.domNode);\n }\n\n public format(name: string, value: any): void {\n if (name === this.statics.blotName && !value) {\n this.children.forEach((child) => {\n if (!(child instanceof InlineBlot)) {\n child = child.wrap(InlineBlot.blotName, true);\n }\n this.attributes.copy(child as InlineBlot);\n });\n this.unwrap();\n } else {\n const format = this.scroll.query(name, Scope.INLINE);\n if (format == null) {\n return;\n }\n if (format instanceof Attributor) {\n this.attributes.attribute(format, value);\n } else if (\n value &&\n (name !== this.statics.blotName || this.formats()[name] !== value)\n ) {\n this.replaceWith(name, value);\n }\n }\n }\n\n public formats(): { [index: string]: any } {\n const formats = this.attributes.values();\n const format = this.statics.formats(this.domNode, this.scroll);\n if (format != null) {\n formats[this.statics.blotName] = format;\n }\n return formats;\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (\n this.formats()[name] != null ||\n this.scroll.query(name, Scope.ATTRIBUTE)\n ) {\n const blot = this.isolate(index, length) as InlineBlot;\n blot.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n const formats = this.formats();\n if (Object.keys(formats).length === 0) {\n return this.unwrap(); // unformatted span\n }\n const next = this.next;\n if (\n next instanceof InlineBlot &&\n next.prev === this &&\n isEqual(formats, next.formats())\n ) {\n next.moveChildren(this);\n next.remove();\n }\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement = super.replaceWith(name, value) as InlineBlot;\n this.attributes.copy(replacement);\n return replacement;\n }\n\n public update(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void {\n super.update(mutations, context);\n const attributeChanged = mutations.some(\n (mutation) =>\n mutation.target === this.domNode && mutation.type === 'attributes',\n );\n if (attributeChanged) {\n this.attributes.build();\n }\n }\n\n public wrap(name: string | Parent, value?: any): Parent {\n const wrapper = super.wrap(name, value);\n if (wrapper instanceof InlineBlot) {\n this.attributes.move(wrapper);\n }\n return wrapper;\n }\n}\n\nexport default InlineBlot;\n", "import Attributor from '../attributor/attributor.js';\nimport AttributorStore from '../attributor/store.js';\nimport Scope from '../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Root,\n} from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\nimport ParentBlot from './abstract/parent.js';\nimport InlineBlot from './inline.js';\n\nclass BlockBlot extends ParentBlot implements Formattable {\n public static blotName = 'block';\n public static scope = Scope.BLOCK_BLOT;\n public static tagName: string | string[] = 'P';\n public static allowedChildren: BlotConstructor[] = [\n InlineBlot,\n BlockBlot,\n LeafBlot,\n ];\n\n static create(value?: unknown) {\n return super.create(value) as HTMLElement;\n }\n\n public static formats(domNode: HTMLElement, scroll: Root): any {\n const match = scroll.query(BlockBlot.blotName);\n if (\n match != null &&\n domNode.tagName === (match as BlotConstructor).tagName\n ) {\n return undefined;\n } else if (typeof this.tagName === 'string') {\n return true;\n } else if (Array.isArray(this.tagName)) {\n return domNode.tagName.toLowerCase();\n }\n }\n\n protected attributes: AttributorStore;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.attributes = new AttributorStore(this.domNode);\n }\n\n public format(name: string, value: any): void {\n const format = this.scroll.query(name, Scope.BLOCK);\n if (format == null) {\n return;\n } else if (format instanceof Attributor) {\n this.attributes.attribute(format, value);\n } else if (name === this.statics.blotName && !value) {\n this.replaceWith(BlockBlot.blotName);\n } else if (\n value &&\n (name !== this.statics.blotName || this.formats()[name] !== value)\n ) {\n this.replaceWith(name, value);\n }\n }\n\n public formats(): { [index: string]: any } {\n const formats = this.attributes.values();\n const format = this.statics.formats(this.domNode, this.scroll);\n if (format != null) {\n formats[this.statics.blotName] = format;\n }\n return formats;\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (this.scroll.query(name, Scope.BLOCK) != null) {\n this.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n if (def == null || this.scroll.query(value, Scope.INLINE) != null) {\n // Insert text or inline\n super.insertAt(index, value, def);\n } else {\n const after = this.split(index);\n if (after != null) {\n const blot = this.scroll.create(value, def);\n after.parent.insertBefore(blot, after);\n } else {\n throw new Error('Attempt to insertAt after block boundaries');\n }\n }\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement = super.replaceWith(name, value) as BlockBlot;\n this.attributes.copy(replacement);\n return replacement;\n }\n\n public update(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void {\n super.update(mutations, context);\n const attributeChanged = mutations.some(\n (mutation) =>\n mutation.target === this.domNode && mutation.type === 'attributes',\n );\n if (attributeChanged) {\n this.attributes.build();\n }\n }\n}\n\nexport default BlockBlot;\n", "import Scope from '../../scope.js';\nimport BlockBlot from '../block.js';\nimport ParentBlot from './parent.js';\n\nclass ContainerBlot extends ParentBlot {\n public static blotName = 'container';\n public static scope = Scope.BLOCK_BLOT;\n public static tagName: string | string[];\n\n public prev!: BlockBlot | ContainerBlot | null;\n public next!: BlockBlot | ContainerBlot | null;\n\n public checkMerge(): boolean {\n return (\n this.next !== null && this.next.statics.blotName === this.statics.blotName\n );\n }\n\n public deleteAt(index: number, length: number): void {\n super.deleteAt(index, length);\n this.enforceAllowedChildren();\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n super.formatAt(index, length, name, value);\n this.enforceAllowedChildren();\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n super.insertAt(index, value, def);\n this.enforceAllowedChildren();\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n if (this.children.length > 0 && this.next != null && this.checkMerge()) {\n this.next.moveChildren(this);\n this.next.remove();\n }\n }\n}\n\nexport default ContainerBlot;\n", "import type { Formattable, Root } from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\n\nclass EmbedBlot extends LeafBlot implements Formattable {\n public static formats(_domNode: HTMLElement, _scroll: Root): any {\n return undefined;\n }\n\n public format(name: string, value: any): void {\n // super.formatAt wraps, which is what we want in general,\n // but this allows subclasses to overwrite for formats\n // that just apply to particular embeds\n super.formatAt(0, this.length(), name, value);\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (index === 0 && length === this.length()) {\n this.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public formats(): { [index: string]: any } {\n return this.statics.formats(this.domNode, this.scroll);\n }\n}\n\nexport default EmbedBlot;\n", "import Registry, { type RegistryDefinition } from '../registry.js';\nimport Scope from '../scope.js';\nimport type { Blot, BlotConstructor, Root } from './abstract/blot.js';\nimport ContainerBlot from './abstract/container.js';\nimport ParentBlot from './abstract/parent.js';\nimport BlockBlot from './block.js';\n\nconst OBSERVER_CONFIG = {\n attributes: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n};\n\nconst MAX_OPTIMIZE_ITERATIONS = 100;\n\nclass ScrollBlot extends ParentBlot implements Root {\n public static blotName = 'scroll';\n public static defaultChild = BlockBlot;\n public static allowedChildren: BlotConstructor[] = [BlockBlot, ContainerBlot];\n public static scope = Scope.BLOCK_BLOT;\n public static tagName = 'DIV';\n\n public observer: MutationObserver;\n\n constructor(\n public registry: Registry,\n node: HTMLDivElement,\n ) {\n // @ts-expect-error scroll is the root with no parent\n super(null, node);\n this.scroll = this;\n this.build();\n this.observer = new MutationObserver((mutations: MutationRecord[]) => {\n this.update(mutations);\n });\n this.observer.observe(this.domNode, OBSERVER_CONFIG);\n this.attach();\n }\n\n public create(input: Node | string | Scope, value?: any): Blot {\n return this.registry.create(this, input, value);\n }\n\n public find(node: Node | null, bubble = false): Blot | null {\n const blot = this.registry.find(node, bubble);\n if (!blot) {\n return null;\n }\n if (blot.scroll === this) {\n return blot;\n }\n return bubble ? this.find(blot.scroll.domNode.parentNode, true) : null;\n }\n\n public query(\n query: string | Node | Scope,\n scope: Scope = Scope.ANY,\n ): RegistryDefinition | null {\n return this.registry.query(query, scope);\n }\n\n public register(...definitions: RegistryDefinition[]) {\n return this.registry.register(...definitions);\n }\n\n public build(): void {\n if (this.scroll == null) {\n return;\n }\n super.build();\n }\n\n public detach(): void {\n super.detach();\n this.observer.disconnect();\n }\n\n public deleteAt(index: number, length: number): void {\n this.update();\n if (index === 0 && length === this.length()) {\n this.children.forEach((child) => {\n child.remove();\n });\n } else {\n super.deleteAt(index, length);\n }\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n this.update();\n super.formatAt(index, length, name, value);\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n this.update();\n super.insertAt(index, value, def);\n }\n\n public optimize(context?: { [key: string]: any }): void;\n public optimize(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void;\n public optimize(mutations: any = [], context: any = {}): void {\n super.optimize(context);\n const mutationsMap = context.mutationsMap || new WeakMap();\n // We must modify mutations directly, cannot make copy and then modify\n let records = Array.from(this.observer.takeRecords());\n // Array.push currently seems to be implemented by a non-tail recursive function\n // so we cannot just mutations.push.apply(mutations, this.observer.takeRecords());\n while (records.length > 0) {\n mutations.push(records.pop());\n }\n const mark = (blot: Blot | null, markParent = true): void => {\n if (blot == null || blot === this) {\n return;\n }\n if (blot.domNode.parentNode == null) {\n return;\n }\n if (!mutationsMap.has(blot.domNode)) {\n mutationsMap.set(blot.domNode, []);\n }\n if (markParent) {\n mark(blot.parent);\n }\n };\n const optimize = (blot: Blot): void => {\n // Post-order traversal\n if (!mutationsMap.has(blot.domNode)) {\n return;\n }\n if (blot instanceof ParentBlot) {\n blot.children.forEach(optimize);\n }\n mutationsMap.delete(blot.domNode);\n blot.optimize(context);\n };\n let remaining = mutations;\n for (let i = 0; remaining.length > 0; i += 1) {\n if (i >= MAX_OPTIMIZE_ITERATIONS) {\n throw new Error('[Parchment] Maximum optimize iterations reached');\n }\n remaining.forEach((mutation: MutationRecord) => {\n const blot = this.find(mutation.target, true);\n if (blot == null) {\n return;\n }\n if (blot.domNode === mutation.target) {\n if (mutation.type === 'childList') {\n mark(this.find(mutation.previousSibling, false));\n Array.from(mutation.addedNodes).forEach((node: Node) => {\n const child = this.find(node, false);\n mark(child, false);\n if (child instanceof ParentBlot) {\n child.children.forEach((grandChild: Blot) => {\n mark(grandChild, false);\n });\n }\n });\n } else if (mutation.type === 'attributes') {\n mark(blot.prev);\n }\n }\n mark(blot);\n });\n this.children.forEach(optimize);\n remaining = Array.from(this.observer.takeRecords());\n records = remaining.slice();\n while (records.length > 0) {\n mutations.push(records.pop());\n }\n }\n }\n\n public update(\n mutations?: MutationRecord[],\n context: { [key: string]: any } = {},\n ): void {\n mutations = mutations || this.observer.takeRecords();\n const mutationsMap = new WeakMap();\n mutations\n .map((mutation: MutationRecord) => {\n const blot = this.find(mutation.target, true);\n if (blot == null) {\n return null;\n }\n if (mutationsMap.has(blot.domNode)) {\n mutationsMap.get(blot.domNode).push(mutation);\n return null;\n } else {\n mutationsMap.set(blot.domNode, [mutation]);\n return blot;\n }\n })\n .forEach((blot: Blot | null) => {\n if (blot != null && blot !== this && mutationsMap.has(blot.domNode)) {\n blot.update(mutationsMap.get(blot.domNode) || [], context);\n }\n });\n context.mutationsMap = mutationsMap;\n if (mutationsMap.has(this.domNode)) {\n super.update(mutationsMap.get(this.domNode), context);\n }\n this.optimize(mutations, context);\n }\n}\n\nexport default ScrollBlot;\n", "import Scope from '../scope.js';\nimport type { Blot, Leaf, Root } from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\n\nclass TextBlot extends LeafBlot implements Leaf {\n public static readonly blotName = 'text';\n public static scope = Scope.INLINE_BLOT;\n\n public static create(value: string): Text {\n return document.createTextNode(value);\n }\n\n public static value(domNode: Text): string {\n return domNode.data;\n }\n\n public domNode!: Text;\n protected text: string;\n\n constructor(scroll: Root, node: Node) {\n super(scroll, node);\n this.text = this.statics.value(this.domNode);\n }\n\n public deleteAt(index: number, length: number): void {\n this.domNode.data = this.text =\n this.text.slice(0, index) + this.text.slice(index + length);\n }\n\n public index(node: Node, offset: number): number {\n if (this.domNode === node) {\n return offset;\n }\n return -1;\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n if (def == null) {\n this.text = this.text.slice(0, index) + value + this.text.slice(index);\n this.domNode.data = this.text;\n } else {\n super.insertAt(index, value, def);\n }\n }\n\n public length(): number {\n return this.text.length;\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n this.text = this.statics.value(this.domNode);\n if (this.text.length === 0) {\n this.remove();\n } else if (this.next instanceof TextBlot && this.next.prev === this) {\n this.insertAt(this.length(), (this.next as TextBlot).value());\n this.next.remove();\n }\n }\n\n public position(index: number, _inclusive = false): [Node, number] {\n return [this.domNode, index];\n }\n\n public split(index: number, force = false): Blot | null {\n if (!force) {\n if (index === 0) {\n return this;\n }\n if (index === this.length()) {\n return this.next;\n }\n }\n const after = this.scroll.create(this.domNode.splitText(index));\n this.parent.insertBefore(after, this.next || undefined);\n this.text = this.statics.value(this.domNode);\n return after;\n }\n\n public update(\n mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n if (\n mutations.some((mutation) => {\n return (\n mutation.type === 'characterData' && mutation.target === this.domNode\n );\n })\n ) {\n this.text = this.statics.value(this.domNode);\n }\n }\n\n public value(): string {\n return this.text;\n }\n}\n\nexport default TextBlot;\n", "/**\n * This library modifies the diff-patch-match library by Neil Fraser\n * by removing the patch and match functionality and certain advanced\n * options in the diff function. The original license is as follows:\n *\n * ===\n *\n * Diff Match and Patch\n *\n * Copyright 2006 Google Inc.\n * http://code.google.com/p/google-diff-match-patch/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The data structure representing a diff is an array of tuples:\n * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]\n * which means: delete 'Hello', add 'Goodbye' and keep ' world.'\n */\nvar DIFF_DELETE = -1;\nvar DIFF_INSERT = 1;\nvar DIFF_EQUAL = 0;\n\n/**\n * Find the differences between two texts. Simplifies the problem by stripping\n * any common prefix or suffix off the texts before diffing.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {Int|Object} [cursor_pos] Edit position in text1 or object with more info\n * @param {boolean} [cleanup] Apply semantic cleanup before returning.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_main(text1, text2, cursor_pos, cleanup, _fix_unicode) {\n // Check for equality\n if (text1 === text2) {\n if (text1) {\n return [[DIFF_EQUAL, text1]];\n }\n return [];\n }\n\n if (cursor_pos != null) {\n var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos);\n if (editdiff) {\n return editdiff;\n }\n }\n\n // Trim off common prefix (speedup).\n var commonlength = diff_commonPrefix(text1, text2);\n var commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n\n // Trim off common suffix (speedup).\n commonlength = diff_commonSuffix(text1, text2);\n var commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n\n // Compute the diff on the middle block.\n var diffs = diff_compute_(text1, text2);\n\n // Restore the prefix and suffix.\n if (commonprefix) {\n diffs.unshift([DIFF_EQUAL, commonprefix]);\n }\n if (commonsuffix) {\n diffs.push([DIFF_EQUAL, commonsuffix]);\n }\n diff_cleanupMerge(diffs, _fix_unicode);\n if (cleanup) {\n diff_cleanupSemantic(diffs);\n }\n return diffs;\n}\n\n/**\n * Find the differences between two texts. Assumes that the texts do not\n * have any common prefix or suffix.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_compute_(text1, text2) {\n var diffs;\n\n if (!text1) {\n // Just add some text (speedup).\n return [[DIFF_INSERT, text2]];\n }\n\n if (!text2) {\n // Just delete some text (speedup).\n return [[DIFF_DELETE, text1]];\n }\n\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n var i = longtext.indexOf(shorttext);\n if (i !== -1) {\n // Shorter text is inside the longer text (speedup).\n diffs = [\n [DIFF_INSERT, longtext.substring(0, i)],\n [DIFF_EQUAL, shorttext],\n [DIFF_INSERT, longtext.substring(i + shorttext.length)],\n ];\n // Swap insertions for deletions if diff is reversed.\n if (text1.length > text2.length) {\n diffs[0][0] = diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n\n if (shorttext.length === 1) {\n // Single character string.\n // After the previous speedup, the character can't be an equality.\n return [\n [DIFF_DELETE, text1],\n [DIFF_INSERT, text2],\n ];\n }\n\n // Check to see if the problem can be split in two.\n var hm = diff_halfMatch_(text1, text2);\n if (hm) {\n // A half-match was found, sort out the return data.\n var text1_a = hm[0];\n var text1_b = hm[1];\n var text2_a = hm[2];\n var text2_b = hm[3];\n var mid_common = hm[4];\n // Send both pairs off for separate processing.\n var diffs_a = diff_main(text1_a, text2_a);\n var diffs_b = diff_main(text1_b, text2_b);\n // Merge the results.\n return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);\n }\n\n return diff_bisect_(text1, text2);\n}\n\n/**\n * Find the 'middle snake' of a diff, split the problem in two\n * and return the recursively constructed diff.\n * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @return {Array} Array of diff tuples.\n * @private\n */\nfunction diff_bisect_(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n var max_d = Math.ceil((text1_length + text2_length) / 2);\n var v_offset = max_d;\n var v_length = 2 * max_d;\n var v1 = new Array(v_length);\n var v2 = new Array(v_length);\n // Setting all elements to -1 is faster in Chrome & Firefox than mixing\n // integers and undefined.\n for (var x = 0; x < v_length; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[v_offset + 1] = 0;\n v2[v_offset + 1] = 0;\n var delta = text1_length - text2_length;\n // If the total number of characters is odd, then the front path will collide\n // with the reverse path.\n var front = delta % 2 !== 0;\n // Offsets for start and end of k loop.\n // Prevents mapping of space beyond the grid.\n var k1start = 0;\n var k1end = 0;\n var k2start = 0;\n var k2end = 0;\n for (var d = 0; d < max_d; d++) {\n // Walk the front path one step.\n for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n var k1_offset = v_offset + k1;\n var x1;\n if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) {\n x1 = v1[k1_offset + 1];\n } else {\n x1 = v1[k1_offset - 1] + 1;\n }\n var y1 = x1 - k1;\n while (\n x1 < text1_length &&\n y1 < text2_length &&\n text1.charAt(x1) === text2.charAt(y1)\n ) {\n x1++;\n y1++;\n }\n v1[k1_offset] = x1;\n if (x1 > text1_length) {\n // Ran off the right of the graph.\n k1end += 2;\n } else if (y1 > text2_length) {\n // Ran off the bottom of the graph.\n k1start += 2;\n } else if (front) {\n var k2_offset = v_offset + delta - k1;\n if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) {\n // Mirror x2 onto top-left coordinate system.\n var x2 = text1_length - v2[k2_offset];\n if (x1 >= x2) {\n // Overlap detected.\n return diff_bisectSplit_(text1, text2, x1, y1);\n }\n }\n }\n }\n\n // Walk the reverse path one step.\n for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n var k2_offset = v_offset + k2;\n var x2;\n if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) {\n x2 = v2[k2_offset + 1];\n } else {\n x2 = v2[k2_offset - 1] + 1;\n }\n var y2 = x2 - k2;\n while (\n x2 < text1_length &&\n y2 < text2_length &&\n text1.charAt(text1_length - x2 - 1) ===\n text2.charAt(text2_length - y2 - 1)\n ) {\n x2++;\n y2++;\n }\n v2[k2_offset] = x2;\n if (x2 > text1_length) {\n // Ran off the left of the graph.\n k2end += 2;\n } else if (y2 > text2_length) {\n // Ran off the top of the graph.\n k2start += 2;\n } else if (!front) {\n var k1_offset = v_offset + delta - k2;\n if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) {\n var x1 = v1[k1_offset];\n var y1 = v_offset + x1 - k1_offset;\n // Mirror x2 onto top-left coordinate system.\n x2 = text1_length - x2;\n if (x1 >= x2) {\n // Overlap detected.\n return diff_bisectSplit_(text1, text2, x1, y1);\n }\n }\n }\n }\n }\n // Diff took too long and hit the deadline or\n // number of diffs equals number of characters, no commonality at all.\n return [\n [DIFF_DELETE, text1],\n [DIFF_INSERT, text2],\n ];\n}\n\n/**\n * Given the location of the 'middle snake', split the diff in two parts\n * and recurse.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} x Index of split point in text1.\n * @param {number} y Index of split point in text2.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_bisectSplit_(text1, text2, x, y) {\n var text1a = text1.substring(0, x);\n var text2a = text2.substring(0, y);\n var text1b = text1.substring(x);\n var text2b = text2.substring(y);\n\n // Compute both diffs serially.\n var diffs = diff_main(text1a, text2a);\n var diffsb = diff_main(text1b, text2b);\n\n return diffs.concat(diffsb);\n}\n\n/**\n * Determine the common prefix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the start of each\n * string.\n */\nfunction diff_commonPrefix(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: http://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerstart = 0;\n while (pointermin < pointermid) {\n if (\n text1.substring(pointerstart, pointermid) ==\n text2.substring(pointerstart, pointermid)\n ) {\n pointermin = pointermid;\n pointerstart = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n\n if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) {\n pointermid--;\n }\n\n return pointermid;\n}\n\n/**\n * Determine if the suffix of one string is the prefix of another.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of the first\n * string and the start of the second string.\n * @private\n */\nfunction diff_commonOverlap_(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n // Eliminate the null case.\n if (text1_length == 0 || text2_length == 0) {\n return 0;\n }\n // Truncate the longer string.\n if (text1_length > text2_length) {\n text1 = text1.substring(text1_length - text2_length);\n } else if (text1_length < text2_length) {\n text2 = text2.substring(0, text1_length);\n }\n var text_length = Math.min(text1_length, text2_length);\n // Quick check for the worst case.\n if (text1 == text2) {\n return text_length;\n }\n\n // Start by looking for a single character match\n // and increase length until no match is found.\n // Performance analysis: http://neil.fraser.name/news/2010/11/04/\n var best = 0;\n var length = 1;\n while (true) {\n var pattern = text1.substring(text_length - length);\n var found = text2.indexOf(pattern);\n if (found == -1) {\n return best;\n }\n length += found;\n if (\n found == 0 ||\n text1.substring(text_length - length) == text2.substring(0, length)\n ) {\n best = length;\n length++;\n }\n }\n}\n\n/**\n * Determine the common suffix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of each string.\n */\nfunction diff_commonSuffix(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: http://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerend = 0;\n while (pointermin < pointermid) {\n if (\n text1.substring(text1.length - pointermid, text1.length - pointerend) ==\n text2.substring(text2.length - pointermid, text2.length - pointerend)\n ) {\n pointermin = pointermid;\n pointerend = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n\n if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) {\n pointermid--;\n }\n\n return pointermid;\n}\n\n/**\n * Do the two texts share a substring which is at least half the length of the\n * longer text?\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {Array.} Five element Array, containing the prefix of\n * text1, the suffix of text1, the prefix of text2, the suffix of\n * text2 and the common middle. Or null if there was no match.\n */\nfunction diff_halfMatch_(text1, text2) {\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {\n return null; // Pointless.\n }\n\n /**\n * Does a substring of shorttext exist within longtext such that the substring\n * is at least half the length of longtext?\n * Closure, but does not reference any external variables.\n * @param {string} longtext Longer string.\n * @param {string} shorttext Shorter string.\n * @param {number} i Start index of quarter length substring within longtext.\n * @return {Array.} Five element Array, containing the prefix of\n * longtext, the suffix of longtext, the prefix of shorttext, the suffix\n * of shorttext and the common middle. Or null if there was no match.\n * @private\n */\n function diff_halfMatchI_(longtext, shorttext, i) {\n // Start with a 1/4 length substring at position i as a seed.\n var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));\n var j = -1;\n var best_common = \"\";\n var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;\n while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {\n var prefixLength = diff_commonPrefix(\n longtext.substring(i),\n shorttext.substring(j)\n );\n var suffixLength = diff_commonSuffix(\n longtext.substring(0, i),\n shorttext.substring(0, j)\n );\n if (best_common.length < suffixLength + prefixLength) {\n best_common =\n shorttext.substring(j - suffixLength, j) +\n shorttext.substring(j, j + prefixLength);\n best_longtext_a = longtext.substring(0, i - suffixLength);\n best_longtext_b = longtext.substring(i + prefixLength);\n best_shorttext_a = shorttext.substring(0, j - suffixLength);\n best_shorttext_b = shorttext.substring(j + prefixLength);\n }\n }\n if (best_common.length * 2 >= longtext.length) {\n return [\n best_longtext_a,\n best_longtext_b,\n best_shorttext_a,\n best_shorttext_b,\n best_common,\n ];\n } else {\n return null;\n }\n }\n\n // First check if the second quarter is the seed for a half-match.\n var hm1 = diff_halfMatchI_(\n longtext,\n shorttext,\n Math.ceil(longtext.length / 4)\n );\n // Check again based on the third quarter.\n var hm2 = diff_halfMatchI_(\n longtext,\n shorttext,\n Math.ceil(longtext.length / 2)\n );\n var hm;\n if (!hm1 && !hm2) {\n return null;\n } else if (!hm2) {\n hm = hm1;\n } else if (!hm1) {\n hm = hm2;\n } else {\n // Both matched. Select the longest.\n hm = hm1[4].length > hm2[4].length ? hm1 : hm2;\n }\n\n // A half-match was found, sort out the return data.\n var text1_a, text1_b, text2_a, text2_b;\n if (text1.length > text2.length) {\n text1_a = hm[0];\n text1_b = hm[1];\n text2_a = hm[2];\n text2_b = hm[3];\n } else {\n text2_a = hm[0];\n text2_b = hm[1];\n text1_a = hm[2];\n text1_b = hm[3];\n }\n var mid_common = hm[4];\n return [text1_a, text1_b, text2_a, text2_b, mid_common];\n}\n\n/**\n * Reduce the number of edits by eliminating semantically trivial equalities.\n * @param {!Array.} diffs Array of diff tuples.\n */\nfunction diff_cleanupSemantic(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastequality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Number of characters that changed prior to the equality.\n var length_insertions1 = 0;\n var length_deletions1 = 0;\n // Number of characters that changed after the equality.\n var length_insertions2 = 0;\n var length_deletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) {\n // Equality found.\n equalities[equalitiesLength++] = pointer;\n length_insertions1 = length_insertions2;\n length_deletions1 = length_deletions2;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastequality = diffs[pointer][1];\n } else {\n // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_INSERT) {\n length_insertions2 += diffs[pointer][1].length;\n } else {\n length_deletions2 += diffs[pointer][1].length;\n }\n // Eliminate an equality that is smaller or equal to the edits on both\n // sides of it.\n if (\n lastequality &&\n lastequality.length <=\n Math.max(length_insertions1, length_deletions1) &&\n lastequality.length <= Math.max(length_insertions2, length_deletions2)\n ) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0, [\n DIFF_DELETE,\n lastequality,\n ]);\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n // Throw away the equality we just deleted.\n equalitiesLength--;\n // Throw away the previous equality (it needs to be reevaluated).\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n length_insertions1 = 0; // Reset the counters.\n length_deletions1 = 0;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastequality = null;\n changes = true;\n }\n }\n pointer++;\n }\n\n // Normalize the diff.\n if (changes) {\n diff_cleanupMerge(diffs);\n }\n diff_cleanupSemanticLossless(diffs);\n\n // Find any overlaps between deletions and insertions.\n // e.g: abcxxxxxxdef\n // -> abcxxxdef\n // e.g: xxxabcdefxxx\n // -> defxxxabc\n // Only extract an overlap if it is as big as the edit ahead or behind it.\n pointer = 1;\n while (pointer < diffs.length) {\n if (\n diffs[pointer - 1][0] == DIFF_DELETE &&\n diffs[pointer][0] == DIFF_INSERT\n ) {\n var deletion = diffs[pointer - 1][1];\n var insertion = diffs[pointer][1];\n var overlap_length1 = diff_commonOverlap_(deletion, insertion);\n var overlap_length2 = diff_commonOverlap_(insertion, deletion);\n if (overlap_length1 >= overlap_length2) {\n if (\n overlap_length1 >= deletion.length / 2 ||\n overlap_length1 >= insertion.length / 2\n ) {\n // Overlap found. Insert an equality and trim the surrounding edits.\n diffs.splice(pointer, 0, [\n DIFF_EQUAL,\n insertion.substring(0, overlap_length1),\n ]);\n diffs[pointer - 1][1] = deletion.substring(\n 0,\n deletion.length - overlap_length1\n );\n diffs[pointer + 1][1] = insertion.substring(overlap_length1);\n pointer++;\n }\n } else {\n if (\n overlap_length2 >= deletion.length / 2 ||\n overlap_length2 >= insertion.length / 2\n ) {\n // Reverse overlap found.\n // Insert an equality and swap and trim the surrounding edits.\n diffs.splice(pointer, 0, [\n DIFF_EQUAL,\n deletion.substring(0, overlap_length2),\n ]);\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] = insertion.substring(\n 0,\n insertion.length - overlap_length2\n );\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] = deletion.substring(overlap_length2);\n pointer++;\n }\n }\n pointer++;\n }\n pointer++;\n }\n}\n\nvar nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;\nvar whitespaceRegex_ = /\\s/;\nvar linebreakRegex_ = /[\\r\\n]/;\nvar blanklineEndRegex_ = /\\n\\r?\\n$/;\nvar blanklineStartRegex_ = /^\\r?\\n\\r?\\n/;\n\n/**\n * Look for single edits surrounded on both sides by equalities\n * which can be shifted sideways to align the edit to a word boundary.\n * e.g: The cat came. -> The cat came.\n * @param {!Array.} diffs Array of diff tuples.\n */\nfunction diff_cleanupSemanticLossless(diffs) {\n /**\n * Given two strings, compute a score representing whether the internal\n * boundary falls on logical boundaries.\n * Scores range from 6 (best) to 0 (worst).\n * Closure, but does not reference any external variables.\n * @param {string} one First string.\n * @param {string} two Second string.\n * @return {number} The score.\n * @private\n */\n function diff_cleanupSemanticScore_(one, two) {\n if (!one || !two) {\n // Edges are the best.\n return 6;\n }\n\n // Each port of this function behaves slightly differently due to\n // subtle differences in each language's definition of things like\n // 'whitespace'. Since this function's purpose is largely cosmetic,\n // the choice has been made to use each language's native features\n // rather than force total conformity.\n var char1 = one.charAt(one.length - 1);\n var char2 = two.charAt(0);\n var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_);\n var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_);\n var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_);\n var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_);\n var lineBreak1 = whitespace1 && char1.match(linebreakRegex_);\n var lineBreak2 = whitespace2 && char2.match(linebreakRegex_);\n var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_);\n var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_);\n\n if (blankLine1 || blankLine2) {\n // Five points for blank lines.\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n // Four points for line breaks.\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n // Three points for end of sentences.\n return 3;\n } else if (whitespace1 || whitespace2) {\n // Two points for whitespace.\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n // One point for non-alphanumeric.\n return 1;\n }\n return 0;\n }\n\n var pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (\n diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL\n ) {\n // This is a single edit surrounded by equalities.\n var equality1 = diffs[pointer - 1][1];\n var edit = diffs[pointer][1];\n var equality2 = diffs[pointer + 1][1];\n\n // First, shift the edit as far left as possible.\n var commonOffset = diff_commonSuffix(equality1, edit);\n if (commonOffset) {\n var commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n\n // Second, step character by character right, looking for the best fit.\n var bestEquality1 = equality1;\n var bestEdit = edit;\n var bestEquality2 = equality2;\n var bestScore =\n diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n var score =\n diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n // The >= encourages trailing rather than leading whitespace on edits.\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n\n if (diffs[pointer - 1][1] != bestEquality1) {\n // We have an improvement, save it back to the diff.\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n}\n\n/**\n * Reorder and merge like edit sections. Merge equalities.\n * Any edit section can move as long as it doesn't cross an equality.\n * @param {Array} diffs Array of diff tuples.\n * @param {boolean} fix_unicode Whether to normalize to a unicode-correct diff\n */\nfunction diff_cleanupMerge(diffs, fix_unicode) {\n diffs.push([DIFF_EQUAL, \"\"]); // Add a dummy entry at the end.\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = \"\";\n var text_insert = \"\";\n var commonlength;\n while (pointer < diffs.length) {\n if (pointer < diffs.length - 1 && !diffs[pointer][1]) {\n diffs.splice(pointer, 1);\n continue;\n }\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n var previous_equality = pointer - count_insert - count_delete - 1;\n if (fix_unicode) {\n // prevent splitting of unicode surrogate pairs. when fix_unicode is true,\n // we assume that the old and new text in the diff are complete and correct\n // unicode-encoded JS strings, but the tuple boundaries may fall between\n // surrogate pairs. we fix this by shaving off stray surrogates from the end\n // of the previous equality and the beginning of this equality. this may create\n // empty equalities or a common prefix or suffix. for example, if AB and AC are\n // emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and\n // inserting 'AC', and then the common suffix 'AC' will be eliminated. in this\n // particular case, both equalities go away, we absorb any previous inequalities,\n // and we keep scanning for the next equality before rewriting the tuples.\n if (\n previous_equality >= 0 &&\n ends_with_pair_start(diffs[previous_equality][1])\n ) {\n var stray = diffs[previous_equality][1].slice(-1);\n diffs[previous_equality][1] = diffs[previous_equality][1].slice(\n 0,\n -1\n );\n text_delete = stray + text_delete;\n text_insert = stray + text_insert;\n if (!diffs[previous_equality][1]) {\n // emptied out previous equality, so delete it and include previous delete/insert\n diffs.splice(previous_equality, 1);\n pointer--;\n var k = previous_equality - 1;\n if (diffs[k] && diffs[k][0] === DIFF_INSERT) {\n count_insert++;\n text_insert = diffs[k][1] + text_insert;\n k--;\n }\n if (diffs[k] && diffs[k][0] === DIFF_DELETE) {\n count_delete++;\n text_delete = diffs[k][1] + text_delete;\n k--;\n }\n previous_equality = k;\n }\n }\n if (starts_with_pair_end(diffs[pointer][1])) {\n var stray = diffs[pointer][1].charAt(0);\n diffs[pointer][1] = diffs[pointer][1].slice(1);\n text_delete += stray;\n text_insert += stray;\n }\n }\n if (pointer < diffs.length - 1 && !diffs[pointer][1]) {\n // for empty equality not at end, wait for next equality\n diffs.splice(pointer, 1);\n break;\n }\n if (text_delete.length > 0 || text_insert.length > 0) {\n // note that diff_commonPrefix and diff_commonSuffix are unicode-aware\n if (text_delete.length > 0 && text_insert.length > 0) {\n // Factor out any common prefixes.\n commonlength = diff_commonPrefix(text_insert, text_delete);\n if (commonlength !== 0) {\n if (previous_equality >= 0) {\n diffs[previous_equality][1] += text_insert.substring(\n 0,\n commonlength\n );\n } else {\n diffs.splice(0, 0, [\n DIFF_EQUAL,\n text_insert.substring(0, commonlength),\n ]);\n pointer++;\n }\n text_insert = text_insert.substring(commonlength);\n text_delete = text_delete.substring(commonlength);\n }\n // Factor out any common suffixes.\n commonlength = diff_commonSuffix(text_insert, text_delete);\n if (commonlength !== 0) {\n diffs[pointer][1] =\n text_insert.substring(text_insert.length - commonlength) +\n diffs[pointer][1];\n text_insert = text_insert.substring(\n 0,\n text_insert.length - commonlength\n );\n text_delete = text_delete.substring(\n 0,\n text_delete.length - commonlength\n );\n }\n }\n // Delete the offending records and add the merged ones.\n var n = count_insert + count_delete;\n if (text_delete.length === 0 && text_insert.length === 0) {\n diffs.splice(pointer - n, n);\n pointer = pointer - n;\n } else if (text_delete.length === 0) {\n diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]);\n pointer = pointer - n + 1;\n } else if (text_insert.length === 0) {\n diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]);\n pointer = pointer - n + 1;\n } else {\n diffs.splice(\n pointer - n,\n n,\n [DIFF_DELETE, text_delete],\n [DIFF_INSERT, text_insert]\n );\n pointer = pointer - n + 2;\n }\n }\n if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {\n // Merge this equality with the previous one.\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = \"\";\n text_insert = \"\";\n break;\n }\n }\n if (diffs[diffs.length - 1][1] === \"\") {\n diffs.pop(); // Remove the dummy entry at the end.\n }\n\n // Second pass: look for single edits surrounded on both sides by equalities\n // which can be shifted sideways to eliminate an equality.\n // e.g: ABAC -> ABAC\n var changes = false;\n pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (\n diffs[pointer - 1][0] === DIFF_EQUAL &&\n diffs[pointer + 1][0] === DIFF_EQUAL\n ) {\n // This is a single edit surrounded by equalities.\n if (\n diffs[pointer][1].substring(\n diffs[pointer][1].length - diffs[pointer - 1][1].length\n ) === diffs[pointer - 1][1]\n ) {\n // Shift the edit over the previous equality.\n diffs[pointer][1] =\n diffs[pointer - 1][1] +\n diffs[pointer][1].substring(\n 0,\n diffs[pointer][1].length - diffs[pointer - 1][1].length\n );\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n changes = true;\n } else if (\n diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==\n diffs[pointer + 1][1]\n ) {\n // Shift the edit over the next equality.\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] =\n diffs[pointer][1].substring(diffs[pointer + 1][1].length) +\n diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n changes = true;\n }\n }\n pointer++;\n }\n // If shifts were made, the diff needs reordering and another shift sweep.\n if (changes) {\n diff_cleanupMerge(diffs, fix_unicode);\n }\n}\n\nfunction is_surrogate_pair_start(charCode) {\n return charCode >= 0xd800 && charCode <= 0xdbff;\n}\n\nfunction is_surrogate_pair_end(charCode) {\n return charCode >= 0xdc00 && charCode <= 0xdfff;\n}\n\nfunction starts_with_pair_end(str) {\n return is_surrogate_pair_end(str.charCodeAt(0));\n}\n\nfunction ends_with_pair_start(str) {\n return is_surrogate_pair_start(str.charCodeAt(str.length - 1));\n}\n\nfunction remove_empty_tuples(tuples) {\n var ret = [];\n for (var i = 0; i < tuples.length; i++) {\n if (tuples[i][1].length > 0) {\n ret.push(tuples[i]);\n }\n }\n return ret;\n}\n\nfunction make_edit_splice(before, oldMiddle, newMiddle, after) {\n if (ends_with_pair_start(before) || starts_with_pair_end(after)) {\n return null;\n }\n return remove_empty_tuples([\n [DIFF_EQUAL, before],\n [DIFF_DELETE, oldMiddle],\n [DIFF_INSERT, newMiddle],\n [DIFF_EQUAL, after],\n ]);\n}\n\nfunction find_cursor_edit_diff(oldText, newText, cursor_pos) {\n // note: this runs after equality check has ruled out exact equality\n var oldRange =\n typeof cursor_pos === \"number\"\n ? { index: cursor_pos, length: 0 }\n : cursor_pos.oldRange;\n var newRange = typeof cursor_pos === \"number\" ? null : cursor_pos.newRange;\n // take into account the old and new selection to generate the best diff\n // possible for a text edit. for example, a text change from \"xxx\" to \"xx\"\n // could be a delete or forwards-delete of any one of the x's, or the\n // result of selecting two of the x's and typing \"x\".\n var oldLength = oldText.length;\n var newLength = newText.length;\n if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) {\n // see if we have an insert or delete before or after cursor\n var oldCursor = oldRange.index;\n var oldBefore = oldText.slice(0, oldCursor);\n var oldAfter = oldText.slice(oldCursor);\n var maybeNewCursor = newRange ? newRange.index : null;\n editBefore: {\n // is this an insert or delete right before oldCursor?\n var newCursor = oldCursor + newLength - oldLength;\n if (maybeNewCursor !== null && maybeNewCursor !== newCursor) {\n break editBefore;\n }\n if (newCursor < 0 || newCursor > newLength) {\n break editBefore;\n }\n var newBefore = newText.slice(0, newCursor);\n var newAfter = newText.slice(newCursor);\n if (newAfter !== oldAfter) {\n break editBefore;\n }\n var prefixLength = Math.min(oldCursor, newCursor);\n var oldPrefix = oldBefore.slice(0, prefixLength);\n var newPrefix = newBefore.slice(0, prefixLength);\n if (oldPrefix !== newPrefix) {\n break editBefore;\n }\n var oldMiddle = oldBefore.slice(prefixLength);\n var newMiddle = newBefore.slice(prefixLength);\n return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter);\n }\n editAfter: {\n // is this an insert or delete right after oldCursor?\n if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) {\n break editAfter;\n }\n var cursor = oldCursor;\n var newBefore = newText.slice(0, cursor);\n var newAfter = newText.slice(cursor);\n if (newBefore !== oldBefore) {\n break editAfter;\n }\n var suffixLength = Math.min(oldLength - cursor, newLength - cursor);\n var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength);\n var newSuffix = newAfter.slice(newAfter.length - suffixLength);\n if (oldSuffix !== newSuffix) {\n break editAfter;\n }\n var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength);\n var newMiddle = newAfter.slice(0, newAfter.length - suffixLength);\n return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix);\n }\n }\n if (oldRange.length > 0 && newRange && newRange.length === 0) {\n replaceRange: {\n // see if diff could be a splice of the old selection range\n var oldPrefix = oldText.slice(0, oldRange.index);\n var oldSuffix = oldText.slice(oldRange.index + oldRange.length);\n var prefixLength = oldPrefix.length;\n var suffixLength = oldSuffix.length;\n if (newLength < prefixLength + suffixLength) {\n break replaceRange;\n }\n var newPrefix = newText.slice(0, prefixLength);\n var newSuffix = newText.slice(newLength - suffixLength);\n if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) {\n break replaceRange;\n }\n var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength);\n var newMiddle = newText.slice(prefixLength, newLength - suffixLength);\n return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix);\n }\n }\n\n return null;\n}\n\nfunction diff(text1, text2, cursor_pos, cleanup) {\n // only pass fix_unicode=true at the top level, not when diff_main is\n // recursively invoked\n return diff_main(text1, text2, cursor_pos, cleanup, true);\n}\n\ndiff.INSERT = DIFF_INSERT;\ndiff.DELETE = DIFF_DELETE;\ndiff.EQUAL = DIFF_EQUAL;\n\nmodule.exports = diff;\n", "/**\n * lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/**\n * Adds the key-value `pair` to `map`.\n *\n * @private\n * @param {Object} map The map to modify.\n * @param {Array} pair The key-value pair to add.\n * @returns {Object} Returns `map`.\n */\nfunction addMapEntry(map, pair) {\n // Don't return `map.set` because it's not chainable in IE 11.\n map.set(pair[0], pair[1]);\n return map;\n}\n\n/**\n * Adds `value` to `set`.\n *\n * @private\n * @param {Object} set The set to modify.\n * @param {*} value The value to add.\n * @returns {Object} Returns `set`.\n */\nfunction addSetEntry(set, value) {\n // Don't return `set.add` because it's not chainable in IE 11.\n set.add(value);\n return set;\n}\n\n/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array ? array.length : 0;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n return this.has(key) && delete this.__data__[key];\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n return getMapData(this, key)['delete'](key);\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n getMapData(this, key).set(key, value);\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n this.__data__ = new ListCache(entries);\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n return this.__data__['delete'](key);\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var cache = this.__data__;\n if (cache instanceof ListCache) {\n var pairs = cache.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n return this;\n }\n cache = this.__data__ = new MapCache(pairs);\n }\n cache.set(key, value);\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n // Safari 9 makes `arguments.length` enumerable in strict mode.\n var result = (isArray(value) || isArguments(value))\n ? baseTimes(value.length, String)\n : [];\n\n var length = result.length,\n skipIndexes = !!length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (key == 'length' || isIndex(key, length)))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n object[key] = value;\n }\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @param {boolean} [isFull] Specify a clone including symbols.\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, isDeep, isFull, customizer, key, object, stack) {\n var result;\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n if (isHostObject(value)) {\n return object ? value : {};\n }\n result = initCloneObject(isFunc ? {} : value);\n if (!isDeep) {\n return copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, baseClone, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (!isArr) {\n var props = isFull ? getAllKeys(value) : keys(value);\n }\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));\n });\n return result;\n}\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} prototype The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nfunction baseCreate(proto) {\n return isObject(proto) ? objectCreate(proto) : {};\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n return objectToString.call(value);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var result = new buffer.constructor(buffer.length);\n buffer.copy(result);\n return result;\n}\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\n/**\n * Creates a clone of `map`.\n *\n * @private\n * @param {Object} map The map to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned map.\n */\nfunction cloneMap(map, isDeep, cloneFunc) {\n var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);\n return arrayReduce(array, addMapEntry, new map.constructor);\n}\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\n/**\n * Creates a clone of `set`.\n *\n * @private\n * @param {Object} set The set to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned set.\n */\nfunction cloneSet(set, isDeep, cloneFunc) {\n var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);\n return arrayReduce(array, addSetEntry, new set.constructor);\n}\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\n/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n assignValue(object, key, newValue === undefined ? source[key] : newValue);\n }\n return object;\n}\n\n/**\n * Copies own symbol properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * Creates an array of the own enumerable symbol properties of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11,\n// for data views in Edge < 14, and promises in Node.js.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = objectToString.call(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : undefined;\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, cloneFunc, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return cloneMap(object, isDeep, cloneFunc);\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return cloneSet(object, isDeep, cloneFunc);\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to process.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, true, true);\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nfunction isArguments(value) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&\n (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);\n}\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = cloneDeep;\n", "/**\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright JS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\n/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = isEqual;\n", "import cloneDeep = require('lodash.clonedeep');\nimport isEqual = require('lodash.isequal');\n\ninterface AttributeMap {\n [key: string]: unknown;\n}\n\nnamespace AttributeMap {\n export function compose(\n a: AttributeMap = {},\n b: AttributeMap = {},\n keepNull = false,\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n a = {};\n }\n if (typeof b !== 'object') {\n b = {};\n }\n let attributes = cloneDeep(b);\n if (!keepNull) {\n attributes = Object.keys(attributes).reduce((copy, key) => {\n if (attributes[key] != null) {\n copy[key] = attributes[key];\n }\n return copy;\n }, {});\n }\n for (const key in a) {\n if (a[key] !== undefined && b[key] === undefined) {\n attributes[key] = a[key];\n }\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n\n export function diff(\n a: AttributeMap = {},\n b: AttributeMap = {},\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n a = {};\n }\n if (typeof b !== 'object') {\n b = {};\n }\n const attributes = Object.keys(a)\n .concat(Object.keys(b))\n .reduce((attrs, key) => {\n if (!isEqual(a[key], b[key])) {\n attrs[key] = b[key] === undefined ? null : b[key];\n }\n return attrs;\n }, {});\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n\n export function invert(\n attr: AttributeMap = {},\n base: AttributeMap = {},\n ): AttributeMap {\n attr = attr || {};\n const baseInverted = Object.keys(base).reduce((memo, key) => {\n if (base[key] !== attr[key] && attr[key] !== undefined) {\n memo[key] = base[key];\n }\n return memo;\n }, {});\n return Object.keys(attr).reduce((memo, key) => {\n if (attr[key] !== base[key] && base[key] === undefined) {\n memo[key] = null;\n }\n return memo;\n }, baseInverted);\n }\n\n export function transform(\n a: AttributeMap | undefined,\n b: AttributeMap | undefined,\n priority = false,\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n return b;\n }\n if (typeof b !== 'object') {\n return undefined;\n }\n if (!priority) {\n return b; // b simply overwrites us without priority\n }\n const attributes = Object.keys(b).reduce((attrs, key) => {\n if (a[key] === undefined) {\n attrs[key] = b[key]; // null is a valid value\n }\n return attrs;\n }, {});\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n}\n\nexport default AttributeMap;\n", "import AttributeMap from './AttributeMap';\n\ninterface Op {\n // only one property out of {insert, delete, retain} will be present\n insert?: string | Record;\n delete?: number;\n retain?: number | Record;\n\n attributes?: AttributeMap;\n}\n\nnamespace Op {\n export function length(op: Op): number {\n if (typeof op.delete === 'number') {\n return op.delete;\n } else if (typeof op.retain === 'number') {\n return op.retain;\n } else if (typeof op.retain === 'object' && op.retain !== null) {\n return 1;\n } else {\n return typeof op.insert === 'string' ? op.insert.length : 1;\n }\n }\n}\n\nexport default Op;\n", "import Op from './Op';\n\nexport default class Iterator {\n ops: Op[];\n index: number;\n offset: number;\n\n constructor(ops: Op[]) {\n this.ops = ops;\n this.index = 0;\n this.offset = 0;\n }\n\n hasNext(): boolean {\n return this.peekLength() < Infinity;\n }\n\n next(length?: number): Op {\n if (!length) {\n length = Infinity;\n }\n const nextOp = this.ops[this.index];\n if (nextOp) {\n const offset = this.offset;\n const opLength = Op.length(nextOp);\n if (length >= opLength - offset) {\n length = opLength - offset;\n this.index += 1;\n this.offset = 0;\n } else {\n this.offset += length;\n }\n if (typeof nextOp.delete === 'number') {\n return { delete: length };\n } else {\n const retOp: Op = {};\n if (nextOp.attributes) {\n retOp.attributes = nextOp.attributes;\n }\n if (typeof nextOp.retain === 'number') {\n retOp.retain = length;\n } else if (\n typeof nextOp.retain === 'object' &&\n nextOp.retain !== null\n ) {\n // offset should === 0, length should === 1\n retOp.retain = nextOp.retain;\n } else if (typeof nextOp.insert === 'string') {\n retOp.insert = nextOp.insert.substr(offset, length);\n } else {\n // offset should === 0, length should === 1\n retOp.insert = nextOp.insert;\n }\n return retOp;\n }\n } else {\n return { retain: Infinity };\n }\n }\n\n peek(): Op {\n return this.ops[this.index];\n }\n\n peekLength(): number {\n if (this.ops[this.index]) {\n // Should never return 0 if our index is being managed correctly\n return Op.length(this.ops[this.index]) - this.offset;\n } else {\n return Infinity;\n }\n }\n\n peekType(): string {\n const op = this.ops[this.index];\n if (op) {\n if (typeof op.delete === 'number') {\n return 'delete';\n } else if (\n typeof op.retain === 'number' ||\n (typeof op.retain === 'object' && op.retain !== null)\n ) {\n return 'retain';\n } else {\n return 'insert';\n }\n }\n return 'retain';\n }\n\n rest(): Op[] {\n if (!this.hasNext()) {\n return [];\n } else if (this.offset === 0) {\n return this.ops.slice(this.index);\n } else {\n const offset = this.offset;\n const index = this.index;\n const next = this.next();\n const rest = this.ops.slice(this.index);\n this.offset = offset;\n this.index = index;\n return [next].concat(rest);\n }\n }\n}\n", "import * as diff from 'fast-diff';\nimport cloneDeep = require('lodash.clonedeep');\nimport isEqual = require('lodash.isequal');\nimport AttributeMap from './AttributeMap';\nimport Op from './Op';\nimport OpIterator from './OpIterator';\n\nconst NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff()\n\ninterface EmbedHandler {\n compose(a: T, b: T, keepNull: boolean): T;\n invert(a: T, b: T): T;\n transform(a: T, b: T, priority: boolean): T;\n}\n\nconst getEmbedTypeAndData = (\n a: Op['insert'] | Op['retain'],\n b: Op['insert'],\n): [string, unknown, unknown] => {\n if (typeof a !== 'object' || a === null) {\n throw new Error(`cannot retain a ${typeof a}`);\n }\n if (typeof b !== 'object' || b === null) {\n throw new Error(`cannot retain a ${typeof b}`);\n }\n const embedType = Object.keys(a)[0];\n if (!embedType || embedType !== Object.keys(b)[0]) {\n throw new Error(\n `embed types not matched: ${embedType} != ${Object.keys(b)[0]}`,\n );\n }\n return [embedType, a[embedType], b[embedType]];\n};\n\nclass Delta {\n static Op = Op;\n static OpIterator = OpIterator;\n static AttributeMap = AttributeMap;\n private static handlers: { [embedType: string]: EmbedHandler } = {};\n\n static registerEmbed(embedType: string, handler: EmbedHandler): void {\n this.handlers[embedType] = handler;\n }\n\n static unregisterEmbed(embedType: string): void {\n delete this.handlers[embedType];\n }\n\n private static getHandler(embedType: string): EmbedHandler {\n const handler = this.handlers[embedType];\n if (!handler) {\n throw new Error(`no handlers for embed type \"${embedType}\"`);\n }\n return handler;\n }\n\n ops: Op[];\n constructor(ops?: Op[] | { ops: Op[] }) {\n // Assume we are given a well formed ops\n if (Array.isArray(ops)) {\n this.ops = ops;\n } else if (ops != null && Array.isArray(ops.ops)) {\n this.ops = ops.ops;\n } else {\n this.ops = [];\n }\n }\n\n insert(\n arg: string | Record,\n attributes?: AttributeMap | null,\n ): this {\n const newOp: Op = {};\n if (typeof arg === 'string' && arg.length === 0) {\n return this;\n }\n newOp.insert = arg;\n if (\n attributes != null &&\n typeof attributes === 'object' &&\n Object.keys(attributes).length > 0\n ) {\n newOp.attributes = attributes;\n }\n return this.push(newOp);\n }\n\n delete(length: number): this {\n if (length <= 0) {\n return this;\n }\n return this.push({ delete: length });\n }\n\n retain(\n length: number | Record,\n attributes?: AttributeMap | null,\n ): this {\n if (typeof length === 'number' && length <= 0) {\n return this;\n }\n const newOp: Op = { retain: length };\n if (\n attributes != null &&\n typeof attributes === 'object' &&\n Object.keys(attributes).length > 0\n ) {\n newOp.attributes = attributes;\n }\n return this.push(newOp);\n }\n\n push(newOp: Op): this {\n let index = this.ops.length;\n let lastOp = this.ops[index - 1];\n newOp = cloneDeep(newOp);\n if (typeof lastOp === 'object') {\n if (\n typeof newOp.delete === 'number' &&\n typeof lastOp.delete === 'number'\n ) {\n this.ops[index - 1] = { delete: lastOp.delete + newOp.delete };\n return this;\n }\n // Since it does not matter if we insert before or after deleting at the same index,\n // always prefer to insert first\n if (typeof lastOp.delete === 'number' && newOp.insert != null) {\n index -= 1;\n lastOp = this.ops[index - 1];\n if (typeof lastOp !== 'object') {\n this.ops.unshift(newOp);\n return this;\n }\n }\n if (isEqual(newOp.attributes, lastOp.attributes)) {\n if (\n typeof newOp.insert === 'string' &&\n typeof lastOp.insert === 'string'\n ) {\n this.ops[index - 1] = { insert: lastOp.insert + newOp.insert };\n if (typeof newOp.attributes === 'object') {\n this.ops[index - 1].attributes = newOp.attributes;\n }\n return this;\n } else if (\n typeof newOp.retain === 'number' &&\n typeof lastOp.retain === 'number'\n ) {\n this.ops[index - 1] = { retain: lastOp.retain + newOp.retain };\n if (typeof newOp.attributes === 'object') {\n this.ops[index - 1].attributes = newOp.attributes;\n }\n return this;\n }\n }\n }\n if (index === this.ops.length) {\n this.ops.push(newOp);\n } else {\n this.ops.splice(index, 0, newOp);\n }\n return this;\n }\n\n chop(): this {\n const lastOp = this.ops[this.ops.length - 1];\n if (lastOp && typeof lastOp.retain === 'number' && !lastOp.attributes) {\n this.ops.pop();\n }\n return this;\n }\n\n filter(predicate: (op: Op, index: number) => boolean): Op[] {\n return this.ops.filter(predicate);\n }\n\n forEach(predicate: (op: Op, index: number) => void): void {\n this.ops.forEach(predicate);\n }\n\n map(predicate: (op: Op, index: number) => T): T[] {\n return this.ops.map(predicate);\n }\n\n partition(predicate: (op: Op) => boolean): [Op[], Op[]] {\n const passed: Op[] = [];\n const failed: Op[] = [];\n this.forEach((op) => {\n const target = predicate(op) ? passed : failed;\n target.push(op);\n });\n return [passed, failed];\n }\n\n reduce(\n predicate: (accum: T, curr: Op, index: number) => T,\n initialValue: T,\n ): T {\n return this.ops.reduce(predicate, initialValue);\n }\n\n changeLength(): number {\n return this.reduce((length, elem) => {\n if (elem.insert) {\n return length + Op.length(elem);\n } else if (elem.delete) {\n return length - elem.delete;\n }\n return length;\n }, 0);\n }\n\n length(): number {\n return this.reduce((length, elem) => {\n return length + Op.length(elem);\n }, 0);\n }\n\n slice(start = 0, end = Infinity): Delta {\n const ops = [];\n const iter = new OpIterator(this.ops);\n let index = 0;\n while (index < end && iter.hasNext()) {\n let nextOp;\n if (index < start) {\n nextOp = iter.next(start - index);\n } else {\n nextOp = iter.next(end - index);\n ops.push(nextOp);\n }\n index += Op.length(nextOp);\n }\n return new Delta(ops);\n }\n\n compose(other: Delta): Delta {\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n const ops = [];\n const firstOther = otherIter.peek();\n if (\n firstOther != null &&\n typeof firstOther.retain === 'number' &&\n firstOther.attributes == null\n ) {\n let firstLeft = firstOther.retain;\n while (\n thisIter.peekType() === 'insert' &&\n thisIter.peekLength() <= firstLeft\n ) {\n firstLeft -= thisIter.peekLength();\n ops.push(thisIter.next());\n }\n if (firstOther.retain - firstLeft > 0) {\n otherIter.next(firstOther.retain - firstLeft);\n }\n }\n const delta = new Delta(ops);\n while (thisIter.hasNext() || otherIter.hasNext()) {\n if (otherIter.peekType() === 'insert') {\n delta.push(otherIter.next());\n } else if (thisIter.peekType() === 'delete') {\n delta.push(thisIter.next());\n } else {\n const length = Math.min(thisIter.peekLength(), otherIter.peekLength());\n const thisOp = thisIter.next(length);\n const otherOp = otherIter.next(length);\n if (otherOp.retain) {\n const newOp: Op = {};\n if (typeof thisOp.retain === 'number') {\n newOp.retain =\n typeof otherOp.retain === 'number' ? length : otherOp.retain;\n } else {\n if (typeof otherOp.retain === 'number') {\n if (thisOp.retain == null) {\n newOp.insert = thisOp.insert;\n } else {\n newOp.retain = thisOp.retain;\n }\n } else {\n const action = thisOp.retain == null ? 'insert' : 'retain';\n const [embedType, thisData, otherData] = getEmbedTypeAndData(\n thisOp[action],\n otherOp.retain,\n );\n const handler = Delta.getHandler(embedType);\n newOp[action] = {\n [embedType]: handler.compose(\n thisData,\n otherData,\n action === 'retain',\n ),\n };\n }\n }\n // Preserve null when composing with a retain, otherwise remove it for inserts\n const attributes = AttributeMap.compose(\n thisOp.attributes,\n otherOp.attributes,\n typeof thisOp.retain === 'number',\n );\n if (attributes) {\n newOp.attributes = attributes;\n }\n delta.push(newOp);\n\n // Optimization if rest of other is just retain\n if (\n !otherIter.hasNext() &&\n isEqual(delta.ops[delta.ops.length - 1], newOp)\n ) {\n const rest = new Delta(thisIter.rest());\n return delta.concat(rest).chop();\n }\n\n // Other op should be delete, we could be an insert or retain\n // Insert + delete cancels out\n } else if (\n typeof otherOp.delete === 'number' &&\n (typeof thisOp.retain === 'number' ||\n (typeof thisOp.retain === 'object' && thisOp.retain !== null))\n ) {\n delta.push(otherOp);\n }\n }\n }\n return delta.chop();\n }\n\n concat(other: Delta): Delta {\n const delta = new Delta(this.ops.slice());\n if (other.ops.length > 0) {\n delta.push(other.ops[0]);\n delta.ops = delta.ops.concat(other.ops.slice(1));\n }\n return delta;\n }\n\n diff(other: Delta, cursor?: number | diff.CursorInfo): Delta {\n if (this.ops === other.ops) {\n return new Delta();\n }\n const strings = [this, other].map((delta) => {\n return delta\n .map((op) => {\n if (op.insert != null) {\n return typeof op.insert === 'string' ? op.insert : NULL_CHARACTER;\n }\n const prep = delta === other ? 'on' : 'with';\n throw new Error('diff() called ' + prep + ' non-document');\n })\n .join('');\n });\n const retDelta = new Delta();\n const diffResult = diff(strings[0], strings[1], cursor, true);\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n diffResult.forEach((component: diff.Diff) => {\n let length = component[1].length;\n while (length > 0) {\n let opLength = 0;\n switch (component[0]) {\n case diff.INSERT:\n opLength = Math.min(otherIter.peekLength(), length);\n retDelta.push(otherIter.next(opLength));\n break;\n case diff.DELETE:\n opLength = Math.min(length, thisIter.peekLength());\n thisIter.next(opLength);\n retDelta.delete(opLength);\n break;\n case diff.EQUAL:\n opLength = Math.min(\n thisIter.peekLength(),\n otherIter.peekLength(),\n length,\n );\n const thisOp = thisIter.next(opLength);\n const otherOp = otherIter.next(opLength);\n if (isEqual(thisOp.insert, otherOp.insert)) {\n retDelta.retain(\n opLength,\n AttributeMap.diff(thisOp.attributes, otherOp.attributes),\n );\n } else {\n retDelta.push(otherOp).delete(opLength);\n }\n break;\n }\n length -= opLength;\n }\n });\n return retDelta.chop();\n }\n\n eachLine(\n predicate: (\n line: Delta,\n attributes: AttributeMap,\n index: number,\n ) => boolean | void,\n newline = '\\n',\n ): void {\n const iter = new OpIterator(this.ops);\n let line = new Delta();\n let i = 0;\n while (iter.hasNext()) {\n if (iter.peekType() !== 'insert') {\n return;\n }\n const thisOp = iter.peek();\n const start = Op.length(thisOp) - iter.peekLength();\n const index =\n typeof thisOp.insert === 'string'\n ? thisOp.insert.indexOf(newline, start) - start\n : -1;\n if (index < 0) {\n line.push(iter.next());\n } else if (index > 0) {\n line.push(iter.next(index));\n } else {\n if (predicate(line, iter.next(1).attributes || {}, i) === false) {\n return;\n }\n i += 1;\n line = new Delta();\n }\n }\n if (line.length() > 0) {\n predicate(line, {}, i);\n }\n }\n\n invert(base: Delta): Delta {\n const inverted = new Delta();\n this.reduce((baseIndex, op) => {\n if (op.insert) {\n inverted.delete(Op.length(op));\n } else if (typeof op.retain === 'number' && op.attributes == null) {\n inverted.retain(op.retain);\n return baseIndex + op.retain;\n } else if (op.delete || typeof op.retain === 'number') {\n const length = (op.delete || op.retain) as number;\n const slice = base.slice(baseIndex, baseIndex + length);\n slice.forEach((baseOp) => {\n if (op.delete) {\n inverted.push(baseOp);\n } else if (op.retain && op.attributes) {\n inverted.retain(\n Op.length(baseOp),\n AttributeMap.invert(op.attributes, baseOp.attributes),\n );\n }\n });\n return baseIndex + length;\n } else if (typeof op.retain === 'object' && op.retain !== null) {\n const slice = base.slice(baseIndex, baseIndex + 1);\n const baseOp = new OpIterator(slice.ops).next();\n const [embedType, opData, baseOpData] = getEmbedTypeAndData(\n op.retain,\n baseOp.insert,\n );\n const handler = Delta.getHandler(embedType);\n inverted.retain(\n { [embedType]: handler.invert(opData, baseOpData) },\n AttributeMap.invert(op.attributes, baseOp.attributes),\n );\n return baseIndex + 1;\n }\n return baseIndex;\n }, 0);\n return inverted.chop();\n }\n\n transform(index: number, priority?: boolean): number;\n transform(other: Delta, priority?: boolean): Delta;\n transform(arg: number | Delta, priority = false): typeof arg {\n priority = !!priority;\n if (typeof arg === 'number') {\n return this.transformPosition(arg, priority);\n }\n const other: Delta = arg;\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n const delta = new Delta();\n while (thisIter.hasNext() || otherIter.hasNext()) {\n if (\n thisIter.peekType() === 'insert' &&\n (priority || otherIter.peekType() !== 'insert')\n ) {\n delta.retain(Op.length(thisIter.next()));\n } else if (otherIter.peekType() === 'insert') {\n delta.push(otherIter.next());\n } else {\n const length = Math.min(thisIter.peekLength(), otherIter.peekLength());\n const thisOp = thisIter.next(length);\n const otherOp = otherIter.next(length);\n if (thisOp.delete) {\n // Our delete either makes their delete redundant or removes their retain\n continue;\n } else if (otherOp.delete) {\n delta.push(otherOp);\n } else {\n const thisData = thisOp.retain;\n const otherData = otherOp.retain;\n let transformedData: Op['retain'] =\n typeof otherData === 'object' && otherData !== null\n ? otherData\n : length;\n if (\n typeof thisData === 'object' &&\n thisData !== null &&\n typeof otherData === 'object' &&\n otherData !== null\n ) {\n const embedType = Object.keys(thisData)[0];\n if (embedType === Object.keys(otherData)[0]) {\n const handler = Delta.getHandler(embedType);\n if (handler) {\n transformedData = {\n [embedType]: handler.transform(\n thisData[embedType],\n otherData[embedType],\n priority,\n ),\n };\n }\n }\n }\n\n // We retain either their retain or insert\n delta.retain(\n transformedData,\n AttributeMap.transform(\n thisOp.attributes,\n otherOp.attributes,\n priority,\n ),\n );\n }\n }\n }\n return delta.chop();\n }\n\n transformPosition(index: number, priority = false): number {\n priority = !!priority;\n const thisIter = new OpIterator(this.ops);\n let offset = 0;\n while (thisIter.hasNext() && offset <= index) {\n const length = thisIter.peekLength();\n const nextType = thisIter.peekType();\n thisIter.next();\n if (nextType === 'delete') {\n index -= Math.min(length, index - offset);\n continue;\n } else if (nextType === 'insert' && (offset < index || !priority)) {\n index += length;\n }\n offset += length;\n }\n return index;\n }\n}\n\nexport default Delta;\n\nexport { Op, OpIterator, AttributeMap };\n\nif (typeof module === 'object') {\n module.exports = Delta;\n module.exports.default = Delta;\n}\n", "import { EmbedBlot } from 'parchment';\n\nclass Break extends EmbedBlot {\n static value() {\n return undefined;\n }\n\n optimize() {\n if (this.prev || this.next) {\n this.remove();\n }\n }\n\n length() {\n return 0;\n }\n\n value() {\n return '';\n }\n}\nBreak.blotName = 'break';\nBreak.tagName = 'BR';\n\nexport default Break;\n", "import { TextBlot } from 'parchment';\n\nclass Text extends TextBlot {}\n\nfunction escapeText(text: string) {\n return text.replace(/[&<>\"']/g, (s) => {\n // https://lodash.com/docs#escape\n const entityMap: Record = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n };\n return entityMap[s];\n });\n}\n\nexport { Text as default, escapeText };\n", "import { EmbedBlot, InlineBlot, Scope } from 'parchment';\nimport type { BlotConstructor } from 'parchment';\nimport Break from './break.js';\nimport Text from './text.js';\n\nclass Inline extends InlineBlot {\n static allowedChildren: BlotConstructor[] = [Inline, Break, EmbedBlot, Text];\n // Lower index means deeper in the DOM tree, since not found (-1) is for embeds\n static order = [\n 'cursor',\n 'inline', // Must be lower\n 'link', // Chrome wants to be lower\n 'underline',\n 'strike',\n 'italic',\n 'bold',\n 'script',\n 'code', // Must be higher\n ];\n\n static compare(self: string, other: string) {\n const selfIndex = Inline.order.indexOf(self);\n const otherIndex = Inline.order.indexOf(other);\n if (selfIndex >= 0 || otherIndex >= 0) {\n return selfIndex - otherIndex;\n }\n if (self === other) {\n return 0;\n }\n if (self < other) {\n return -1;\n }\n return 1;\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (\n Inline.compare(this.statics.blotName, name) < 0 &&\n this.scroll.query(name, Scope.BLOT)\n ) {\n const blot = this.isolate(index, length);\n if (value) {\n blot.wrap(name, value);\n }\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n if (\n this.parent instanceof Inline &&\n Inline.compare(this.statics.blotName, this.parent.statics.blotName) > 0\n ) {\n const parent = this.parent.isolate(this.offset(), this.length());\n // @ts-expect-error TODO: make isolate generic\n this.moveChildren(parent);\n parent.wrap(this);\n }\n }\n}\n\nexport default Inline;\n", "import {\n AttributorStore,\n BlockBlot,\n EmbedBlot,\n LeafBlot,\n Scope,\n} from 'parchment';\nimport type { Blot, Parent } from 'parchment';\nimport Delta from 'quill-delta';\nimport Break from './break.js';\nimport Inline from './inline.js';\nimport TextBlot from './text.js';\n\nconst NEWLINE_LENGTH = 1;\n\nclass Block extends BlockBlot {\n cache: { delta?: Delta | null; length?: number } = {};\n\n delta(): Delta {\n if (this.cache.delta == null) {\n this.cache.delta = blockDelta(this);\n }\n return this.cache.delta;\n }\n\n deleteAt(index: number, length: number) {\n super.deleteAt(index, length);\n this.cache = {};\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (length <= 0) return;\n if (this.scroll.query(name, Scope.BLOCK)) {\n if (index + length === this.length()) {\n this.format(name, value);\n }\n } else {\n super.formatAt(\n index,\n Math.min(length, this.length() - index - 1),\n name,\n value,\n );\n }\n this.cache = {};\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (def != null) {\n super.insertAt(index, value, def);\n this.cache = {};\n return;\n }\n if (value.length === 0) return;\n const lines = value.split('\\n');\n const text = lines.shift() as string;\n if (text.length > 0) {\n if (index < this.length() - 1 || this.children.tail == null) {\n super.insertAt(Math.min(index, this.length() - 1), text);\n } else {\n this.children.tail.insertAt(this.children.tail.length(), text);\n }\n this.cache = {};\n }\n // TODO: Fix this next time the file is edited.\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let block: Blot | this = this;\n lines.reduce((lineIndex, line) => {\n // @ts-expect-error Fix me later\n block = block.split(lineIndex, true);\n block.insertAt(0, line);\n return line.length;\n }, index + text.length);\n }\n\n insertBefore(blot: Blot, ref?: Blot | null) {\n const { head } = this.children;\n super.insertBefore(blot, ref);\n if (head instanceof Break) {\n head.remove();\n }\n this.cache = {};\n }\n\n length() {\n if (this.cache.length == null) {\n this.cache.length = super.length() + NEWLINE_LENGTH;\n }\n return this.cache.length;\n }\n\n moveChildren(target: Parent, ref?: Blot | null) {\n super.moveChildren(target, ref);\n this.cache = {};\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n this.cache = {};\n }\n\n path(index: number) {\n return super.path(index, true);\n }\n\n removeChild(child: Blot) {\n super.removeChild(child);\n this.cache = {};\n }\n\n split(index: number, force: boolean | undefined = false): Blot | null {\n if (force && (index === 0 || index >= this.length() - NEWLINE_LENGTH)) {\n const clone = this.clone();\n if (index === 0) {\n this.parent.insertBefore(clone, this);\n return this;\n }\n this.parent.insertBefore(clone, this.next);\n return clone;\n }\n const next = super.split(index, force);\n this.cache = {};\n return next;\n }\n}\nBlock.blotName = 'block';\nBlock.tagName = 'P';\nBlock.defaultChild = Break;\nBlock.allowedChildren = [Break, Inline, EmbedBlot, TextBlot];\n\nclass BlockEmbed extends EmbedBlot {\n attributes: AttributorStore;\n domNode: HTMLElement;\n\n attach() {\n super.attach();\n this.attributes = new AttributorStore(this.domNode);\n }\n\n delta() {\n return new Delta().insert(this.value(), {\n ...this.formats(),\n ...this.attributes.values(),\n });\n }\n\n format(name: string, value: unknown) {\n const attribute = this.scroll.query(name, Scope.BLOCK_ATTRIBUTE);\n if (attribute != null) {\n // @ts-expect-error TODO: Scroll#query() should return Attributor when scope is attribute\n this.attributes.attribute(attribute, value);\n }\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n this.format(name, value);\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (def != null) {\n super.insertAt(index, value, def);\n return;\n }\n const lines = value.split('\\n');\n const text = lines.pop();\n const blocks = lines.map((line) => {\n const block = this.scroll.create(Block.blotName);\n block.insertAt(0, line);\n return block;\n });\n const ref = this.split(index);\n blocks.forEach((block) => {\n this.parent.insertBefore(block, ref);\n });\n if (text) {\n this.parent.insertBefore(this.scroll.create('text', text), ref);\n }\n }\n}\nBlockEmbed.scope = Scope.BLOCK_BLOT;\n// It is important for cursor behavior BlockEmbeds use tags that are block level elements\n\nfunction blockDelta(blot: BlockBlot, filter = true) {\n return blot\n .descendants(LeafBlot)\n .reduce((delta, leaf) => {\n if (leaf.length() === 0) {\n return delta;\n }\n return delta.insert(leaf.value(), bubbleFormats(leaf, {}, filter));\n }, new Delta())\n .insert('\\n', bubbleFormats(blot));\n}\n\nfunction bubbleFormats(\n blot: Blot | null,\n formats: Record = {},\n filter = true,\n): Record {\n if (blot == null) return formats;\n if ('formats' in blot && typeof blot.formats === 'function') {\n formats = {\n ...formats,\n ...blot.formats(),\n };\n if (filter) {\n // exclude syntax highlighting from deltas and getFormat()\n delete formats['code-token'];\n }\n }\n if (\n blot.parent == null ||\n blot.parent.statics.blotName === 'scroll' ||\n blot.parent.statics.scope !== blot.statics.scope\n ) {\n return formats;\n }\n return bubbleFormats(blot.parent, formats, filter);\n}\n\nexport { blockDelta, bubbleFormats, BlockEmbed, Block as default };\n", "import { EmbedBlot, Scope } from 'parchment';\nimport type { Parent, ScrollBlot } from 'parchment';\nimport type Selection from '../core/selection.js';\nimport TextBlot from './text.js';\nimport type { EmbedContextRange } from './embed.js';\n\nclass Cursor extends EmbedBlot {\n static blotName = 'cursor';\n static className = 'ql-cursor';\n static tagName = 'span';\n static CONTENTS = '\\uFEFF'; // Zero width no break space\n\n static value() {\n return undefined;\n }\n\n selection: Selection;\n textNode: Text;\n savedLength: number;\n\n constructor(scroll: ScrollBlot, domNode: HTMLElement, selection: Selection) {\n super(scroll, domNode);\n this.selection = selection;\n this.textNode = document.createTextNode(Cursor.CONTENTS);\n this.domNode.appendChild(this.textNode);\n this.savedLength = 0;\n }\n\n detach() {\n // super.detach() will also clear domNode.__blot\n if (this.parent != null) this.parent.removeChild(this);\n }\n\n format(name: string, value: unknown) {\n if (this.savedLength !== 0) {\n super.format(name, value);\n return;\n }\n // TODO: Fix this next time the file is edited.\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let target: Parent | this = this;\n let index = 0;\n while (target != null && target.statics.scope !== Scope.BLOCK_BLOT) {\n index += target.offset(target.parent);\n target = target.parent;\n }\n if (target != null) {\n this.savedLength = Cursor.CONTENTS.length;\n // @ts-expect-error TODO: allow empty context in Parchment\n target.optimize();\n target.formatAt(index, Cursor.CONTENTS.length, name, value);\n this.savedLength = 0;\n }\n }\n\n index(node: Node, offset: number) {\n if (node === this.textNode) return 0;\n return super.index(node, offset);\n }\n\n length() {\n return this.savedLength;\n }\n\n position(): [Text, number] {\n return [this.textNode, this.textNode.data.length];\n }\n\n remove() {\n super.remove();\n // @ts-expect-error Fix me later\n this.parent = null;\n }\n\n restore(): EmbedContextRange | null {\n if (this.selection.composing || this.parent == null) return null;\n const range = this.selection.getNativeRange();\n // Browser may push down styles/nodes inside the cursor blot.\n // https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#push-down-values\n while (\n this.domNode.lastChild != null &&\n this.domNode.lastChild !== this.textNode\n ) {\n // @ts-expect-error Fix me later\n this.domNode.parentNode.insertBefore(\n this.domNode.lastChild,\n this.domNode,\n );\n }\n\n const prevTextBlot = this.prev instanceof TextBlot ? this.prev : null;\n const prevTextLength = prevTextBlot ? prevTextBlot.length() : 0;\n const nextTextBlot = this.next instanceof TextBlot ? this.next : null;\n // @ts-expect-error TODO: make TextBlot.text public\n const nextText = nextTextBlot ? nextTextBlot.text : '';\n const { textNode } = this;\n // take text from inside this blot and reset it\n const newText = textNode.data.split(Cursor.CONTENTS).join('');\n textNode.data = Cursor.CONTENTS;\n\n // proactively merge TextBlots around cursor so that optimization\n // doesn't lose the cursor. the reason we are here in cursor.restore\n // could be that the user clicked in prevTextBlot or nextTextBlot, or\n // the user typed something.\n let mergedTextBlot;\n if (prevTextBlot) {\n mergedTextBlot = prevTextBlot;\n if (newText || nextTextBlot) {\n prevTextBlot.insertAt(prevTextBlot.length(), newText + nextText);\n if (nextTextBlot) {\n nextTextBlot.remove();\n }\n }\n } else if (nextTextBlot) {\n mergedTextBlot = nextTextBlot;\n nextTextBlot.insertAt(0, newText);\n } else {\n const newTextNode = document.createTextNode(newText);\n mergedTextBlot = this.scroll.create(newTextNode);\n this.parent.insertBefore(mergedTextBlot, this);\n }\n\n this.remove();\n if (range) {\n // calculate selection to restore\n const remapOffset = (node: Node, offset: number) => {\n if (prevTextBlot && node === prevTextBlot.domNode) {\n return offset;\n }\n if (node === textNode) {\n return prevTextLength + offset - 1;\n }\n if (nextTextBlot && node === nextTextBlot.domNode) {\n return prevTextLength + newText.length + offset;\n }\n return null;\n };\n\n const start = remapOffset(range.start.node, range.start.offset);\n const end = remapOffset(range.end.node, range.end.offset);\n if (start !== null && end !== null) {\n return {\n startNode: mergedTextBlot.domNode,\n startOffset: start,\n endNode: mergedTextBlot.domNode,\n endOffset: end,\n };\n }\n }\n return null;\n }\n\n update(mutations: MutationRecord[], context: Record) {\n if (\n mutations.some((mutation) => {\n return (\n mutation.type === 'characterData' && mutation.target === this.textNode\n );\n })\n ) {\n const range = this.restore();\n if (range) context.range = range;\n }\n }\n\n // Avoid .ql-cursor being a descendant of ``.\n // The reason is Safari pushes down `` on text insertion.\n // That will cause DOM nodes not sync with the model.\n //\n // For example ({I} is the caret), given the markup:\n // \\uFEFF{I}\n // When typing a char \"x\", `` will be pushed down inside the `` first:\n // \\uFEFF{I}\n // And then \"x\" will be inserted after ``:\n // \\uFEFFd{I}\n optimize(context?: unknown) {\n // @ts-expect-error Fix me later\n super.optimize(context);\n\n let { parent } = this;\n while (parent) {\n if (parent.domNode.tagName === 'A') {\n this.savedLength = Cursor.CONTENTS.length;\n // @ts-expect-error TODO: make isolate generic\n parent.isolate(this.offset(parent), this.length()).unwrap();\n this.savedLength = 0;\n break;\n }\n parent = parent.parent;\n }\n }\n\n value() {\n return '';\n }\n}\n\nexport default Cursor;\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "import type Quill from '../core.js';\n\nexport default new WeakMap();\n", "const levels = ['error', 'warn', 'log', 'info'] as const;\nexport type DebugLevel = (typeof levels)[number];\nlet level: DebugLevel | false = 'warn';\n\nfunction debug(method: DebugLevel, ...args: unknown[]) {\n if (level) {\n if (levels.indexOf(method) <= levels.indexOf(level)) {\n console[method](...args); // eslint-disable-line no-console\n }\n }\n}\n\nfunction namespace(\n ns: string,\n): Record void> {\n return levels.reduce(\n (logger, method) => {\n logger[method] = debug.bind(console, method, ns);\n return logger;\n },\n {} as Record void>,\n );\n}\n\nnamespace.level = (newLevel: DebugLevel | false) => {\n level = newLevel;\n};\ndebug.level = namespace.level;\n\nexport default namespace;\n", "import { EventEmitter } from 'eventemitter3';\nimport instances from './instances.js';\nimport logger from './logger.js';\n\nconst debug = logger('quill:events');\nconst EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click'];\n\nEVENTS.forEach((eventName) => {\n document.addEventListener(eventName, (...args) => {\n Array.from(document.querySelectorAll('.ql-container')).forEach((node) => {\n const quill = instances.get(node);\n if (quill && quill.emitter) {\n quill.emitter.handleDOM(...args);\n }\n });\n });\n});\n\nclass Emitter extends EventEmitter {\n static events = {\n EDITOR_CHANGE: 'editor-change',\n SCROLL_BEFORE_UPDATE: 'scroll-before-update',\n SCROLL_BLOT_MOUNT: 'scroll-blot-mount',\n SCROLL_BLOT_UNMOUNT: 'scroll-blot-unmount',\n SCROLL_OPTIMIZE: 'scroll-optimize',\n SCROLL_UPDATE: 'scroll-update',\n SCROLL_EMBED_UPDATE: 'scroll-embed-update',\n SELECTION_CHANGE: 'selection-change',\n TEXT_CHANGE: 'text-change',\n COMPOSITION_BEFORE_START: 'composition-before-start',\n COMPOSITION_START: 'composition-start',\n COMPOSITION_BEFORE_END: 'composition-before-end',\n COMPOSITION_END: 'composition-end',\n } as const;\n\n static sources = {\n API: 'api',\n SILENT: 'silent',\n USER: 'user',\n } as const;\n\n protected domListeners: Record;\n\n constructor() {\n super();\n this.domListeners = {};\n this.on('error', debug.error);\n }\n\n emit(...args: unknown[]): boolean {\n debug.log.call(debug, ...args);\n // @ts-expect-error\n return super.emit(...args);\n }\n\n handleDOM(event: Event, ...args: unknown[]) {\n (this.domListeners[event.type] || []).forEach(({ node, handler }) => {\n if (event.target === node || node.contains(event.target as Node)) {\n handler(event, ...args);\n }\n });\n }\n\n listenDOM(eventName: string, node: Node, handler: EventListener) {\n if (!this.domListeners[eventName]) {\n this.domListeners[eventName] = [];\n }\n this.domListeners[eventName].push({ node, handler });\n }\n}\n\nexport type EmitterSource =\n (typeof Emitter.sources)[keyof typeof Emitter.sources];\n\nexport default Emitter;\n", "import { LeafBlot, Scope } from 'parchment';\nimport { cloneDeep, isEqual } from 'lodash-es';\nimport Emitter from './emitter.js';\nimport type { EmitterSource } from './emitter.js';\nimport logger from './logger.js';\nimport type Cursor from '../blots/cursor.js';\nimport type Scroll from '../blots/scroll.js';\n\nconst debug = logger('quill:selection');\n\ntype NativeRange = AbstractRange;\n\ninterface NormalizedRange {\n start: {\n node: NativeRange['startContainer'];\n offset: NativeRange['startOffset'];\n };\n end: { node: NativeRange['endContainer']; offset: NativeRange['endOffset'] };\n native: NativeRange;\n}\n\nexport interface Bounds {\n bottom: number;\n height: number;\n left: number;\n right: number;\n top: number;\n width: number;\n}\n\nexport class Range {\n constructor(\n public index: number,\n public length = 0,\n ) {}\n}\n\nclass Selection {\n scroll: Scroll;\n emitter: Emitter;\n composing: boolean;\n mouseDown: boolean;\n\n root: HTMLElement;\n cursor: Cursor;\n savedRange: Range;\n lastRange: Range | null;\n lastNative: NormalizedRange | null;\n\n constructor(scroll: Scroll, emitter: Emitter) {\n this.emitter = emitter;\n this.scroll = scroll;\n this.composing = false;\n this.mouseDown = false;\n this.root = this.scroll.domNode;\n // @ts-expect-error\n this.cursor = this.scroll.create('cursor', this);\n // savedRange is last non-null range\n this.savedRange = new Range(0, 0);\n this.lastRange = this.savedRange;\n this.lastNative = null;\n this.handleComposition();\n this.handleDragging();\n this.emitter.listenDOM('selectionchange', document, () => {\n if (!this.mouseDown && !this.composing) {\n setTimeout(this.update.bind(this, Emitter.sources.USER), 1);\n }\n });\n this.emitter.on(Emitter.events.SCROLL_BEFORE_UPDATE, () => {\n if (!this.hasFocus()) return;\n const native = this.getNativeRange();\n if (native == null) return;\n if (native.start.node === this.cursor.textNode) return; // cursor.restore() will handle\n this.emitter.once(\n Emitter.events.SCROLL_UPDATE,\n (source, mutations: MutationRecord[]) => {\n try {\n if (\n this.root.contains(native.start.node) &&\n this.root.contains(native.end.node)\n ) {\n this.setNativeRange(\n native.start.node,\n native.start.offset,\n native.end.node,\n native.end.offset,\n );\n }\n const triggeredByTyping = mutations.some(\n (mutation) =>\n mutation.type === 'characterData' ||\n mutation.type === 'childList' ||\n (mutation.type === 'attributes' &&\n mutation.target === this.root),\n );\n this.update(triggeredByTyping ? Emitter.sources.SILENT : source);\n } catch (ignored) {\n // ignore\n }\n },\n );\n });\n this.emitter.on(Emitter.events.SCROLL_OPTIMIZE, (mutations, context) => {\n if (context.range) {\n const { startNode, startOffset, endNode, endOffset } = context.range;\n this.setNativeRange(startNode, startOffset, endNode, endOffset);\n this.update(Emitter.sources.SILENT);\n }\n });\n this.update(Emitter.sources.SILENT);\n }\n\n handleComposition() {\n this.emitter.on(Emitter.events.COMPOSITION_BEFORE_START, () => {\n this.composing = true;\n });\n this.emitter.on(Emitter.events.COMPOSITION_END, () => {\n this.composing = false;\n if (this.cursor.parent) {\n const range = this.cursor.restore();\n if (!range) return;\n setTimeout(() => {\n this.setNativeRange(\n range.startNode,\n range.startOffset,\n range.endNode,\n range.endOffset,\n );\n }, 1);\n }\n });\n }\n\n handleDragging() {\n this.emitter.listenDOM('mousedown', document.body, () => {\n this.mouseDown = true;\n });\n this.emitter.listenDOM('mouseup', document.body, () => {\n this.mouseDown = false;\n this.update(Emitter.sources.USER);\n });\n }\n\n focus() {\n if (this.hasFocus()) return;\n this.root.focus({ preventScroll: true });\n this.setRange(this.savedRange);\n }\n\n format(format: string, value: unknown) {\n this.scroll.update();\n const nativeRange = this.getNativeRange();\n if (\n nativeRange == null ||\n !nativeRange.native.collapsed ||\n this.scroll.query(format, Scope.BLOCK)\n )\n return;\n if (nativeRange.start.node !== this.cursor.textNode) {\n const blot = this.scroll.find(nativeRange.start.node, false);\n if (blot == null) return;\n // TODO Give blot ability to not split\n if (blot instanceof LeafBlot) {\n const after = blot.split(nativeRange.start.offset);\n blot.parent.insertBefore(this.cursor, after);\n } else {\n // @ts-expect-error TODO: nativeRange.start.node doesn't seem to match function signature\n blot.insertBefore(this.cursor, nativeRange.start.node); // Should never happen\n }\n this.cursor.attach();\n }\n this.cursor.format(format, value);\n this.scroll.optimize();\n this.setNativeRange(this.cursor.textNode, this.cursor.textNode.data.length);\n this.update();\n }\n\n getBounds(index: number, length = 0) {\n const scrollLength = this.scroll.length();\n index = Math.min(index, scrollLength - 1);\n length = Math.min(index + length, scrollLength - 1) - index;\n let node: Node;\n let [leaf, offset] = this.scroll.leaf(index);\n if (leaf == null) return null;\n if (length > 0 && offset === leaf.length()) {\n const [next] = this.scroll.leaf(index + 1);\n if (next) {\n const [line] = this.scroll.line(index);\n const [nextLine] = this.scroll.line(index + 1);\n if (line === nextLine) {\n leaf = next;\n offset = 0;\n }\n }\n }\n [node, offset] = leaf.position(offset, true);\n const range = document.createRange();\n if (length > 0) {\n range.setStart(node, offset);\n [leaf, offset] = this.scroll.leaf(index + length);\n if (leaf == null) return null;\n [node, offset] = leaf.position(offset, true);\n range.setEnd(node, offset);\n return range.getBoundingClientRect();\n }\n let side: 'left' | 'right' = 'left';\n let rect: DOMRect;\n if (node instanceof Text) {\n // Return null if the text node is empty because it is\n // not able to get a useful client rect:\n // https://github.com/w3c/csswg-drafts/issues/2514.\n // Empty text nodes are most likely caused by TextBlot#optimize()\n // not getting called when editor content changes.\n if (!node.data.length) {\n return null;\n }\n if (offset < node.data.length) {\n range.setStart(node, offset);\n range.setEnd(node, offset + 1);\n } else {\n range.setStart(node, offset - 1);\n range.setEnd(node, offset);\n side = 'right';\n }\n rect = range.getBoundingClientRect();\n } else {\n if (!(leaf.domNode instanceof Element)) return null;\n rect = leaf.domNode.getBoundingClientRect();\n if (offset > 0) side = 'right';\n }\n return {\n bottom: rect.top + rect.height,\n height: rect.height,\n left: rect[side],\n right: rect[side],\n top: rect.top,\n width: 0,\n };\n }\n\n getNativeRange(): NormalizedRange | null {\n const selection = document.getSelection();\n if (selection == null || selection.rangeCount <= 0) return null;\n const nativeRange = selection.getRangeAt(0);\n if (nativeRange == null) return null;\n const range = this.normalizeNative(nativeRange);\n debug.info('getNativeRange', range);\n return range;\n }\n\n getRange(): [Range, NormalizedRange] | [null, null] {\n const root = this.scroll.domNode;\n if ('isConnected' in root && !root.isConnected) {\n // document.getSelection() forces layout on Blink, so we trend to\n // not calling it.\n return [null, null];\n }\n const normalized = this.getNativeRange();\n if (normalized == null) return [null, null];\n const range = this.normalizedToRange(normalized);\n return [range, normalized];\n }\n\n hasFocus(): boolean {\n return (\n document.activeElement === this.root ||\n (document.activeElement != null &&\n contains(this.root, document.activeElement))\n );\n }\n\n normalizedToRange(range: NormalizedRange) {\n const positions: [Node, number][] = [\n [range.start.node, range.start.offset],\n ];\n if (!range.native.collapsed) {\n positions.push([range.end.node, range.end.offset]);\n }\n const indexes = positions.map((position) => {\n const [node, offset] = position;\n const blot = this.scroll.find(node, true);\n // @ts-expect-error Fix me later\n const index = blot.offset(this.scroll);\n if (offset === 0) {\n return index;\n }\n if (blot instanceof LeafBlot) {\n return index + blot.index(node, offset);\n }\n // @ts-expect-error Fix me later\n return index + blot.length();\n });\n const end = Math.min(Math.max(...indexes), this.scroll.length() - 1);\n const start = Math.min(end, ...indexes);\n return new Range(start, end - start);\n }\n\n normalizeNative(nativeRange: NativeRange) {\n if (\n !contains(this.root, nativeRange.startContainer) ||\n (!nativeRange.collapsed && !contains(this.root, nativeRange.endContainer))\n ) {\n return null;\n }\n const range = {\n start: {\n node: nativeRange.startContainer,\n offset: nativeRange.startOffset,\n },\n end: { node: nativeRange.endContainer, offset: nativeRange.endOffset },\n native: nativeRange,\n };\n [range.start, range.end].forEach((position) => {\n let { node, offset } = position;\n while (!(node instanceof Text) && node.childNodes.length > 0) {\n if (node.childNodes.length > offset) {\n node = node.childNodes[offset];\n offset = 0;\n } else if (node.childNodes.length === offset) {\n // @ts-expect-error Fix me later\n node = node.lastChild;\n if (node instanceof Text) {\n offset = node.data.length;\n } else if (node.childNodes.length > 0) {\n // Container case\n offset = node.childNodes.length;\n } else {\n // Embed case\n offset = node.childNodes.length + 1;\n }\n } else {\n break;\n }\n }\n position.node = node;\n position.offset = offset;\n });\n return range;\n }\n\n rangeToNative(range: Range): [Node | null, number, Node | null, number] {\n const scrollLength = this.scroll.length();\n\n const getPosition = (\n index: number,\n inclusive: boolean,\n ): [Node | null, number] => {\n index = Math.min(scrollLength - 1, index);\n const [leaf, leafOffset] = this.scroll.leaf(index);\n return leaf ? leaf.position(leafOffset, inclusive) : [null, -1];\n };\n return [\n ...getPosition(range.index, false),\n ...getPosition(range.index + range.length, true),\n ];\n }\n\n setNativeRange(\n startNode: Node | null,\n startOffset?: number,\n endNode = startNode,\n endOffset = startOffset,\n force = false,\n ) {\n debug.info('setNativeRange', startNode, startOffset, endNode, endOffset);\n if (\n startNode != null &&\n (this.root.parentNode == null ||\n startNode.parentNode == null ||\n // @ts-expect-error Fix me later\n endNode.parentNode == null)\n ) {\n return;\n }\n const selection = document.getSelection();\n if (selection == null) return;\n if (startNode != null) {\n if (!this.hasFocus()) this.root.focus({ preventScroll: true });\n const { native } = this.getNativeRange() || {};\n if (\n native == null ||\n force ||\n startNode !== native.startContainer ||\n startOffset !== native.startOffset ||\n endNode !== native.endContainer ||\n endOffset !== native.endOffset\n ) {\n if (startNode instanceof Element && startNode.tagName === 'BR') {\n // @ts-expect-error Fix me later\n startOffset = Array.from(startNode.parentNode.childNodes).indexOf(\n startNode,\n );\n startNode = startNode.parentNode;\n }\n if (endNode instanceof Element && endNode.tagName === 'BR') {\n // @ts-expect-error Fix me later\n endOffset = Array.from(endNode.parentNode.childNodes).indexOf(\n endNode,\n );\n endNode = endNode.parentNode;\n }\n const range = document.createRange();\n // @ts-expect-error Fix me later\n range.setStart(startNode, startOffset);\n // @ts-expect-error Fix me later\n range.setEnd(endNode, endOffset);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n } else {\n selection.removeAllRanges();\n this.root.blur();\n }\n }\n\n setRange(range: Range | null, force: boolean, source?: EmitterSource): void;\n setRange(range: Range | null, source?: EmitterSource): void;\n setRange(\n range: Range | null,\n force: boolean | EmitterSource = false,\n source: EmitterSource = Emitter.sources.API,\n ): void {\n if (typeof force === 'string') {\n source = force;\n force = false;\n }\n debug.info('setRange', range);\n if (range != null) {\n const args = this.rangeToNative(range);\n this.setNativeRange(...args, force);\n } else {\n this.setNativeRange(null);\n }\n this.update(source);\n }\n\n update(source: EmitterSource = Emitter.sources.USER) {\n const oldRange = this.lastRange;\n const [lastRange, nativeRange] = this.getRange();\n this.lastRange = lastRange;\n this.lastNative = nativeRange;\n if (this.lastRange != null) {\n this.savedRange = this.lastRange;\n }\n if (!isEqual(oldRange, this.lastRange)) {\n if (\n !this.composing &&\n nativeRange != null &&\n nativeRange.native.collapsed &&\n nativeRange.start.node !== this.cursor.textNode\n ) {\n const range = this.cursor.restore();\n if (range) {\n this.setNativeRange(\n range.startNode,\n range.startOffset,\n range.endNode,\n range.endOffset,\n );\n }\n }\n const args = [\n Emitter.events.SELECTION_CHANGE,\n cloneDeep(this.lastRange),\n cloneDeep(oldRange),\n source,\n ];\n this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);\n if (source !== Emitter.sources.SILENT) {\n this.emitter.emit(...args);\n }\n }\n }\n}\n\nfunction contains(parent: Node, descendant: Node) {\n try {\n // Firefox inserts inaccessible nodes around video elements\n descendant.parentNode; // eslint-disable-line @typescript-eslint/no-unused-expressions\n } catch (e) {\n return false;\n }\n return parent.contains(descendant);\n}\n\nexport default Selection;\n", "import { cloneDeep, isEqual, merge } from 'lodash-es';\nimport { LeafBlot, EmbedBlot, Scope, ParentBlot } from 'parchment';\nimport type { Blot } from 'parchment';\nimport Delta, { AttributeMap, Op } from 'quill-delta';\nimport Block, { BlockEmbed, bubbleFormats } from '../blots/block.js';\nimport Break from '../blots/break.js';\nimport CursorBlot from '../blots/cursor.js';\nimport type Scroll from '../blots/scroll.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport { Range } from './selection.js';\n\nconst ASCII = /^[ -~]*$/;\n\ntype SelectionInfo = {\n newRange: Range;\n oldRange: Range;\n};\n\nclass Editor {\n scroll: Scroll;\n delta: Delta;\n\n constructor(scroll: Scroll) {\n this.scroll = scroll;\n this.delta = this.getDelta();\n }\n\n applyDelta(delta: Delta): Delta {\n this.scroll.update();\n let scrollLength = this.scroll.length();\n this.scroll.batchStart();\n const normalizedDelta = normalizeDelta(delta);\n const deleteDelta = new Delta();\n const normalizedOps = splitOpLines(normalizedDelta.ops.slice());\n normalizedOps.reduce((index, op) => {\n const length = Op.length(op);\n let attributes = op.attributes || {};\n let isImplicitNewlinePrepended = false;\n let isImplicitNewlineAppended = false;\n if (op.insert != null) {\n deleteDelta.retain(length);\n if (typeof op.insert === 'string') {\n const text = op.insert;\n isImplicitNewlineAppended =\n !text.endsWith('\\n') &&\n (scrollLength <= index ||\n !!this.scroll.descendant(BlockEmbed, index)[0]);\n this.scroll.insertAt(index, text);\n const [line, offset] = this.scroll.line(index);\n let formats = merge({}, bubbleFormats(line));\n if (line instanceof Block) {\n const [leaf] = line.descendant(LeafBlot, offset);\n if (leaf) {\n formats = merge(formats, bubbleFormats(leaf));\n }\n }\n attributes = AttributeMap.diff(formats, attributes) || {};\n } else if (typeof op.insert === 'object') {\n const key = Object.keys(op.insert)[0]; // There should only be one key\n if (key == null) return index;\n const isInlineEmbed = this.scroll.query(key, Scope.INLINE) != null;\n if (isInlineEmbed) {\n if (\n scrollLength <= index ||\n !!this.scroll.descendant(BlockEmbed, index)[0]\n ) {\n isImplicitNewlineAppended = true;\n }\n } else if (index > 0) {\n const [leaf, offset] = this.scroll.descendant(LeafBlot, index - 1);\n if (leaf instanceof TextBlot) {\n const text = leaf.value();\n if (text[offset] !== '\\n') {\n isImplicitNewlinePrepended = true;\n }\n } else if (\n leaf instanceof EmbedBlot &&\n leaf.statics.scope === Scope.INLINE_BLOT\n ) {\n isImplicitNewlinePrepended = true;\n }\n }\n this.scroll.insertAt(index, key, op.insert[key]);\n\n if (isInlineEmbed) {\n const [leaf] = this.scroll.descendant(LeafBlot, index);\n if (leaf) {\n const formats = merge({}, bubbleFormats(leaf));\n attributes = AttributeMap.diff(formats, attributes) || {};\n }\n }\n }\n scrollLength += length;\n } else {\n deleteDelta.push(op);\n\n if (op.retain !== null && typeof op.retain === 'object') {\n const key = Object.keys(op.retain)[0];\n if (key == null) return index;\n this.scroll.updateEmbedAt(index, key, op.retain[key]);\n }\n }\n Object.keys(attributes).forEach((name) => {\n this.scroll.formatAt(index, length, name, attributes[name]);\n });\n const prependedLength = isImplicitNewlinePrepended ? 1 : 0;\n const addedLength = isImplicitNewlineAppended ? 1 : 0;\n scrollLength += prependedLength + addedLength;\n deleteDelta.retain(prependedLength);\n deleteDelta.delete(addedLength);\n return index + length + prependedLength + addedLength;\n }, 0);\n deleteDelta.reduce((index, op) => {\n if (typeof op.delete === 'number') {\n this.scroll.deleteAt(index, op.delete);\n return index;\n }\n return index + Op.length(op);\n }, 0);\n this.scroll.batchEnd();\n this.scroll.optimize();\n return this.update(normalizedDelta);\n }\n\n deleteText(index: number, length: number): Delta {\n this.scroll.deleteAt(index, length);\n return this.update(new Delta().retain(index).delete(length));\n }\n\n formatLine(\n index: number,\n length: number,\n formats: Record = {},\n ): Delta {\n this.scroll.update();\n Object.keys(formats).forEach((format) => {\n this.scroll.lines(index, Math.max(length, 1)).forEach((line) => {\n line.format(format, formats[format]);\n });\n });\n this.scroll.optimize();\n const delta = new Delta().retain(index).retain(length, cloneDeep(formats));\n return this.update(delta);\n }\n\n formatText(\n index: number,\n length: number,\n formats: Record = {},\n ): Delta {\n Object.keys(formats).forEach((format) => {\n this.scroll.formatAt(index, length, format, formats[format]);\n });\n const delta = new Delta().retain(index).retain(length, cloneDeep(formats));\n return this.update(delta);\n }\n\n getContents(index: number, length: number): Delta {\n return this.delta.slice(index, index + length);\n }\n\n getDelta(): Delta {\n return this.scroll.lines().reduce((delta, line) => {\n return delta.concat(line.delta());\n }, new Delta());\n }\n\n getFormat(index: number, length = 0): Record {\n let lines: (Block | BlockEmbed)[] = [];\n let leaves: LeafBlot[] = [];\n if (length === 0) {\n this.scroll.path(index).forEach((path) => {\n const [blot] = path;\n if (blot instanceof Block) {\n lines.push(blot);\n } else if (blot instanceof LeafBlot) {\n leaves.push(blot);\n }\n });\n } else {\n lines = this.scroll.lines(index, length);\n leaves = this.scroll.descendants(LeafBlot, index, length);\n }\n const [lineFormats, leafFormats] = [lines, leaves].map((blots) => {\n const blot = blots.shift();\n if (blot == null) return {};\n let formats = bubbleFormats(blot);\n while (Object.keys(formats).length > 0) {\n const blot = blots.shift();\n if (blot == null) return formats;\n formats = combineFormats(bubbleFormats(blot), formats);\n }\n return formats;\n });\n return { ...lineFormats, ...leafFormats };\n }\n\n getHTML(index: number, length: number): string {\n const [line, lineOffset] = this.scroll.line(index);\n if (line) {\n const lineLength = line.length();\n const isWithinLine = line.length() >= lineOffset + length;\n if (isWithinLine && !(lineOffset === 0 && length === lineLength)) {\n return convertHTML(line, lineOffset, length, true);\n }\n return convertHTML(this.scroll, index, length, true);\n }\n return '';\n }\n\n getText(index: number, length: number): string {\n return this.getContents(index, length)\n .filter((op) => typeof op.insert === 'string')\n .map((op) => op.insert)\n .join('');\n }\n\n insertContents(index: number, contents: Delta): Delta {\n const normalizedDelta = normalizeDelta(contents);\n const change = new Delta().retain(index).concat(normalizedDelta);\n this.scroll.insertContents(index, normalizedDelta);\n return this.update(change);\n }\n\n insertEmbed(index: number, embed: string, value: unknown): Delta {\n this.scroll.insertAt(index, embed, value);\n return this.update(new Delta().retain(index).insert({ [embed]: value }));\n }\n\n insertText(\n index: number,\n text: string,\n formats: Record = {},\n ): Delta {\n text = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n this.scroll.insertAt(index, text);\n Object.keys(formats).forEach((format) => {\n this.scroll.formatAt(index, text.length, format, formats[format]);\n });\n return this.update(\n new Delta().retain(index).insert(text, cloneDeep(formats)),\n );\n }\n\n isBlank(): boolean {\n if (this.scroll.children.length === 0) return true;\n if (this.scroll.children.length > 1) return false;\n const blot = this.scroll.children.head;\n if (blot?.statics.blotName !== Block.blotName) return false;\n const block = blot as Block;\n if (block.children.length > 1) return false;\n return block.children.head instanceof Break;\n }\n\n removeFormat(index: number, length: number): Delta {\n const text = this.getText(index, length);\n const [line, offset] = this.scroll.line(index + length);\n let suffixLength = 0;\n let suffix = new Delta();\n if (line != null) {\n suffixLength = line.length() - offset;\n suffix = line\n .delta()\n .slice(offset, offset + suffixLength - 1)\n .insert('\\n');\n }\n const contents = this.getContents(index, length + suffixLength);\n const diff = contents.diff(new Delta().insert(text).concat(suffix));\n const delta = new Delta().retain(index).concat(diff);\n return this.applyDelta(delta);\n }\n\n update(\n change: Delta | null,\n mutations: MutationRecord[] = [],\n selectionInfo: SelectionInfo | undefined = undefined,\n ): Delta {\n const oldDelta = this.delta;\n if (\n mutations.length === 1 &&\n mutations[0].type === 'characterData' &&\n // @ts-expect-error Fix me later\n mutations[0].target.data.match(ASCII) &&\n this.scroll.find(mutations[0].target)\n ) {\n // Optimization for character changes\n const textBlot = this.scroll.find(mutations[0].target) as Blot;\n const formats = bubbleFormats(textBlot);\n const index = textBlot.offset(this.scroll);\n // @ts-expect-error Fix me later\n const oldValue = mutations[0].oldValue.replace(CursorBlot.CONTENTS, '');\n const oldText = new Delta().insert(oldValue);\n // @ts-expect-error\n const newText = new Delta().insert(textBlot.value());\n const relativeSelectionInfo = selectionInfo && {\n oldRange: shiftRange(selectionInfo.oldRange, -index),\n newRange: shiftRange(selectionInfo.newRange, -index),\n };\n const diffDelta = new Delta()\n .retain(index)\n .concat(oldText.diff(newText, relativeSelectionInfo));\n change = diffDelta.reduce((delta, op) => {\n if (op.insert) {\n return delta.insert(op.insert, formats);\n }\n return delta.push(op);\n }, new Delta());\n this.delta = oldDelta.compose(change);\n } else {\n this.delta = this.getDelta();\n if (!change || !isEqual(oldDelta.compose(change), this.delta)) {\n change = oldDelta.diff(this.delta, selectionInfo);\n }\n }\n return change;\n }\n}\n\ninterface ListItem {\n child: Blot;\n offset: number;\n length: number;\n indent: number;\n type: string;\n}\nfunction convertListHTML(\n items: ListItem[],\n lastIndent: number,\n types: string[],\n): string {\n if (items.length === 0) {\n const [endTag] = getListType(types.pop());\n if (lastIndent <= 0) {\n return ``;\n }\n return `${convertListHTML([], lastIndent - 1, types)}`;\n }\n const [{ child, offset, length, indent, type }, ...rest] = items;\n const [tag, attribute] = getListType(type);\n if (indent > lastIndent) {\n types.push(type);\n if (indent === lastIndent + 1) {\n return `<${tag}>${convertHTML(\n child,\n offset,\n length,\n )}${convertListHTML(rest, indent, types)}`;\n }\n return `<${tag}>
  • ${convertListHTML(items, lastIndent + 1, types)}`;\n }\n const previousType = types[types.length - 1];\n if (indent === lastIndent && type === previousType) {\n return `
  • ${convertHTML(\n child,\n offset,\n length,\n )}${convertListHTML(rest, indent, types)}`;\n }\n const [endTag] = getListType(types.pop());\n return `${convertListHTML(items, lastIndent - 1, types)}`;\n}\n\nfunction convertHTML(\n blot: Blot,\n index: number,\n length: number,\n isRoot = false,\n): string {\n if ('html' in blot && typeof blot.html === 'function') {\n return blot.html(index, length);\n }\n if (blot instanceof TextBlot) {\n return escapeText(blot.value().slice(index, index + length));\n }\n if (blot instanceof ParentBlot) {\n // TODO fix API\n if (blot.statics.blotName === 'list-container') {\n const items: any[] = [];\n blot.children.forEachAt(index, length, (child, offset, childLength) => {\n const formats =\n 'formats' in child && typeof child.formats === 'function'\n ? child.formats()\n : {};\n items.push({\n child,\n offset,\n length: childLength,\n indent: formats.indent || 0,\n type: formats.list,\n });\n });\n return convertListHTML(items, -1, []);\n }\n const parts: string[] = [];\n blot.children.forEachAt(index, length, (child, offset, childLength) => {\n parts.push(convertHTML(child, offset, childLength));\n });\n if (isRoot || blot.statics.blotName === 'list') {\n return parts.join('');\n }\n const { outerHTML, innerHTML } = blot.domNode as Element;\n const [start, end] = outerHTML.split(`>${innerHTML}<`);\n // TODO cleanup\n if (start === '${parts.join('')}<${end}`;\n }\n return `${start}>${parts.join('')}<${end}`;\n }\n return blot.domNode instanceof Element ? blot.domNode.outerHTML : '';\n}\n\nfunction combineFormats(\n formats: Record,\n combined: Record,\n): Record {\n return Object.keys(combined).reduce(\n (merged, name) => {\n if (formats[name] == null) return merged;\n const combinedValue = combined[name];\n if (combinedValue === formats[name]) {\n merged[name] = combinedValue;\n } else if (Array.isArray(combinedValue)) {\n if (combinedValue.indexOf(formats[name]) < 0) {\n merged[name] = combinedValue.concat([formats[name]]);\n } else {\n // If style already exists, don't add to an array, but don't lose other styles\n merged[name] = combinedValue;\n }\n } else {\n merged[name] = [combinedValue, formats[name]];\n }\n return merged;\n },\n {} as Record,\n );\n}\n\nfunction getListType(type: string | undefined) {\n const tag = type === 'ordered' ? 'ol' : 'ul';\n switch (type) {\n case 'checked':\n return [tag, ' data-list=\"checked\"'];\n case 'unchecked':\n return [tag, ' data-list=\"unchecked\"'];\n default:\n return [tag, ''];\n }\n}\n\nfunction normalizeDelta(delta: Delta) {\n return delta.reduce((normalizedDelta, op) => {\n if (typeof op.insert === 'string') {\n const text = op.insert.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n return normalizedDelta.insert(text, op.attributes);\n }\n return normalizedDelta.push(op);\n }, new Delta());\n}\n\nfunction shiftRange({ index, length }: Range, amount: number) {\n return new Range(index + amount, length);\n}\n\nfunction splitOpLines(ops: Op[]) {\n const split: Op[] = [];\n ops.forEach((op) => {\n if (typeof op.insert === 'string') {\n const lines = op.insert.split('\\n');\n lines.forEach((line, index) => {\n if (index) split.push({ insert: '\\n', attributes: op.attributes });\n if (line) split.push({ insert: line, attributes: op.attributes });\n });\n } else {\n split.push(op);\n }\n });\n\n return split;\n}\n\nexport default Editor;\n", "import type Quill from './quill.js';\n\nabstract class Module {\n static DEFAULTS = {};\n\n constructor(\n public quill: Quill,\n protected options: Partial = {},\n ) {}\n}\n\nexport default Module;\n", "import type { ScrollBlot } from 'parchment';\nimport { EmbedBlot } from 'parchment';\nimport TextBlot from './text.js';\n\nconst GUARD_TEXT = '\\uFEFF';\n\nexport interface EmbedContextRange {\n startNode: Node | Text;\n startOffset: number;\n endNode?: Node | Text;\n endOffset?: number;\n}\n\nclass Embed extends EmbedBlot {\n contentNode: HTMLSpanElement;\n leftGuard: Text;\n rightGuard: Text;\n\n constructor(scroll: ScrollBlot, node: Node) {\n super(scroll, node);\n this.contentNode = document.createElement('span');\n this.contentNode.setAttribute('contenteditable', 'false');\n Array.from(this.domNode.childNodes).forEach((childNode) => {\n this.contentNode.appendChild(childNode);\n });\n this.leftGuard = document.createTextNode(GUARD_TEXT);\n this.rightGuard = document.createTextNode(GUARD_TEXT);\n this.domNode.appendChild(this.leftGuard);\n this.domNode.appendChild(this.contentNode);\n this.domNode.appendChild(this.rightGuard);\n }\n\n index(node: Node, offset: number) {\n if (node === this.leftGuard) return 0;\n if (node === this.rightGuard) return 1;\n return super.index(node, offset);\n }\n\n restore(node: Text): EmbedContextRange | null {\n let range: EmbedContextRange | null = null;\n let textNode: Text;\n const text = node.data.split(GUARD_TEXT).join('');\n if (node === this.leftGuard) {\n if (this.prev instanceof TextBlot) {\n const prevLength = this.prev.length();\n this.prev.insertAt(prevLength, text);\n range = {\n startNode: this.prev.domNode,\n startOffset: prevLength + text.length,\n };\n } else {\n textNode = document.createTextNode(text);\n this.parent.insertBefore(this.scroll.create(textNode), this);\n range = {\n startNode: textNode,\n startOffset: text.length,\n };\n }\n } else if (node === this.rightGuard) {\n if (this.next instanceof TextBlot) {\n this.next.insertAt(0, text);\n range = {\n startNode: this.next.domNode,\n startOffset: text.length,\n };\n } else {\n textNode = document.createTextNode(text);\n this.parent.insertBefore(this.scroll.create(textNode), this.next);\n range = {\n startNode: textNode,\n startOffset: text.length,\n };\n }\n }\n node.data = GUARD_TEXT;\n return range;\n }\n\n update(mutations: MutationRecord[], context: Record) {\n mutations.forEach((mutation) => {\n if (\n mutation.type === 'characterData' &&\n (mutation.target === this.leftGuard ||\n mutation.target === this.rightGuard)\n ) {\n const range = this.restore(mutation.target as Text);\n if (range) context.range = range;\n }\n });\n }\n}\n\nexport default Embed;\n", "import Embed from '../blots/embed.js';\nimport type Scroll from '../blots/scroll.js';\nimport Emitter from './emitter.js';\n\nclass Composition {\n isComposing = false;\n\n constructor(\n private scroll: Scroll,\n private emitter: Emitter,\n ) {\n this.setupListeners();\n }\n\n private setupListeners() {\n this.scroll.domNode.addEventListener('compositionstart', (event) => {\n if (!this.isComposing) {\n this.handleCompositionStart(event);\n }\n });\n\n this.scroll.domNode.addEventListener('compositionend', (event) => {\n if (this.isComposing) {\n // Webkit makes DOM changes after compositionend, so we use microtask to\n // ensure the order.\n // https://bugs.webkit.org/show_bug.cgi?id=31902\n queueMicrotask(() => {\n this.handleCompositionEnd(event);\n });\n }\n });\n }\n\n private handleCompositionStart(event: CompositionEvent) {\n const blot =\n event.target instanceof Node\n ? this.scroll.find(event.target, true)\n : null;\n\n if (blot && !(blot instanceof Embed)) {\n this.emitter.emit(Emitter.events.COMPOSITION_BEFORE_START, event);\n this.scroll.batchStart();\n this.emitter.emit(Emitter.events.COMPOSITION_START, event);\n this.isComposing = true;\n }\n }\n\n private handleCompositionEnd(event: CompositionEvent) {\n this.emitter.emit(Emitter.events.COMPOSITION_BEFORE_END, event);\n this.scroll.batchEnd();\n this.emitter.emit(Emitter.events.COMPOSITION_END, event);\n this.isComposing = false;\n }\n}\n\nexport default Composition;\n", "import type Quill from '../core.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type { ToolbarProps } from '../modules/toolbar.js';\nimport type Uploader from '../modules/uploader.js';\n\nexport interface ThemeOptions {\n modules: Record & {\n toolbar?: null | ToolbarProps;\n };\n}\n\nclass Theme {\n static DEFAULTS: ThemeOptions = {\n modules: {},\n };\n\n static themes = {\n default: Theme,\n };\n\n modules: ThemeOptions['modules'] = {};\n\n constructor(\n protected quill: Quill,\n protected options: ThemeOptions,\n ) {}\n\n init() {\n Object.keys(this.options.modules).forEach((name) => {\n if (this.modules[name] == null) {\n this.addModule(name);\n }\n });\n }\n\n addModule(name: 'clipboard'): Clipboard;\n addModule(name: 'keyboard'): Keyboard;\n addModule(name: 'uploader'): Uploader;\n addModule(name: 'history'): History;\n addModule(name: string): unknown;\n addModule(name: string) {\n // @ts-expect-error\n const ModuleClass = this.quill.constructor.import(`modules/${name}`);\n this.modules[name] = new ModuleClass(\n this.quill,\n this.options.modules[name] || {},\n );\n return this.modules[name];\n }\n}\n\nexport interface ThemeConstructor {\n new (quill: Quill, options: unknown): Theme;\n DEFAULTS: ThemeOptions;\n}\n\nexport default Theme;\n", "export type Rect = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\nconst getParentElement = (element: Node): Element | null =>\n element.parentElement || (element.getRootNode() as ShadowRoot).host || null;\n\nconst getElementRect = (element: Element): Rect => {\n const rect = element.getBoundingClientRect();\n const scaleX =\n ('offsetWidth' in element &&\n Math.abs(rect.width) / (element as HTMLElement).offsetWidth) ||\n 1;\n const scaleY =\n ('offsetHeight' in element &&\n Math.abs(rect.height) / (element as HTMLElement).offsetHeight) ||\n 1;\n return {\n top: rect.top,\n right: rect.left + element.clientWidth * scaleX,\n bottom: rect.top + element.clientHeight * scaleY,\n left: rect.left,\n };\n};\n\nconst paddingValueToInt = (value: string) => {\n const number = parseInt(value, 10);\n return Number.isNaN(number) ? 0 : number;\n};\n\n// Follow the steps described in https://www.w3.org/TR/cssom-view-1/#element-scrolling-members,\n// assuming that the scroll option is set to 'nearest'.\nconst getScrollDistance = (\n targetStart: number,\n targetEnd: number,\n scrollStart: number,\n scrollEnd: number,\n scrollPaddingStart: number,\n scrollPaddingEnd: number,\n) => {\n if (targetStart < scrollStart && targetEnd > scrollEnd) {\n return 0;\n }\n\n if (targetStart < scrollStart) {\n return -(scrollStart - targetStart + scrollPaddingStart);\n }\n\n if (targetEnd > scrollEnd) {\n return targetEnd - targetStart > scrollEnd - scrollStart\n ? targetStart + scrollPaddingStart - scrollStart\n : targetEnd - scrollEnd + scrollPaddingEnd;\n }\n return 0;\n};\n\nconst scrollRectIntoView = (root: HTMLElement, targetRect: Rect) => {\n const document = root.ownerDocument;\n\n let rect = targetRect;\n\n let current: Element | null = root;\n while (current) {\n const isDocumentBody: boolean = current === document.body;\n const bounding = isDocumentBody\n ? {\n top: 0,\n right:\n window.visualViewport?.width ??\n document.documentElement.clientWidth,\n bottom:\n window.visualViewport?.height ??\n document.documentElement.clientHeight,\n left: 0,\n }\n : getElementRect(current);\n\n const style = getComputedStyle(current);\n const scrollDistanceX = getScrollDistance(\n rect.left,\n rect.right,\n bounding.left,\n bounding.right,\n paddingValueToInt(style.scrollPaddingLeft),\n paddingValueToInt(style.scrollPaddingRight),\n );\n const scrollDistanceY = getScrollDistance(\n rect.top,\n rect.bottom,\n bounding.top,\n bounding.bottom,\n paddingValueToInt(style.scrollPaddingTop),\n paddingValueToInt(style.scrollPaddingBottom),\n );\n if (scrollDistanceX || scrollDistanceY) {\n if (isDocumentBody) {\n document.defaultView?.scrollBy(scrollDistanceX, scrollDistanceY);\n } else {\n const { scrollLeft, scrollTop } = current;\n if (scrollDistanceY) {\n current.scrollTop += scrollDistanceY;\n }\n if (scrollDistanceX) {\n current.scrollLeft += scrollDistanceX;\n }\n const scrolledLeft = current.scrollLeft - scrollLeft;\n const scrolledTop = current.scrollTop - scrollTop;\n rect = {\n left: rect.left - scrolledLeft,\n top: rect.top - scrolledTop,\n right: rect.right - scrolledLeft,\n bottom: rect.bottom - scrolledTop,\n };\n }\n }\n\n current =\n isDocumentBody || style.position === 'fixed'\n ? null\n : getParentElement(current);\n }\n};\n\nexport default scrollRectIntoView;\n", "import { Registry } from 'parchment';\n\nconst MAX_REGISTER_ITERATIONS = 100;\nconst CORE_FORMATS = ['block', 'break', 'cursor', 'inline', 'scroll', 'text'];\n\nconst createRegistryWithFormats = (\n formats: string[],\n sourceRegistry: Registry,\n debug: { error: (errorMessage: string) => void },\n) => {\n const registry = new Registry();\n CORE_FORMATS.forEach((name) => {\n const coreBlot = sourceRegistry.query(name);\n if (coreBlot) registry.register(coreBlot);\n });\n\n formats.forEach((name) => {\n let format = sourceRegistry.query(name);\n if (!format) {\n debug.error(\n `Cannot register \"${name}\" specified in \"formats\" config. Are you sure it was registered?`,\n );\n }\n let iterations = 0;\n while (format) {\n registry.register(format);\n format = 'blotName' in format ? format.requiredContainer ?? null : null;\n\n iterations += 1;\n if (iterations > MAX_REGISTER_ITERATIONS) {\n debug.error(\n `Cycle detected in registering blot requiredContainer: \"${name}\"`,\n );\n break;\n }\n }\n });\n\n return registry;\n};\n\nexport default createRegistryWithFormats;\n", "import { merge } from 'lodash-es';\nimport * as Parchment from 'parchment';\nimport type { Op } from 'quill-delta';\nimport Delta from 'quill-delta';\nimport type { BlockEmbed } from '../blots/block.js';\nimport type Block from '../blots/block.js';\nimport type Scroll from '../blots/scroll.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type Uploader from '../modules/uploader.js';\nimport Editor from './editor.js';\nimport Emitter from './emitter.js';\nimport type { EmitterSource } from './emitter.js';\nimport instances from './instances.js';\nimport logger from './logger.js';\nimport type { DebugLevel } from './logger.js';\nimport Module from './module.js';\nimport Selection, { Range } from './selection.js';\nimport type { Bounds } from './selection.js';\nimport Composition from './composition.js';\nimport Theme from './theme.js';\nimport type { ThemeConstructor } from './theme.js';\nimport scrollRectIntoView from './utils/scrollRectIntoView.js';\nimport type { Rect } from './utils/scrollRectIntoView.js';\nimport createRegistryWithFormats from './utils/createRegistryWithFormats.js';\n\nconst debug = logger('quill');\n\nconst globalRegistry = new Parchment.Registry();\nParchment.ParentBlot.uiClass = 'ql-ui';\n\n/**\n * Options for initializing a Quill instance\n */\nexport interface QuillOptions {\n theme?: string;\n debug?: DebugLevel | boolean;\n registry?: Parchment.Registry;\n /**\n * Whether to disable the editing\n * @default false\n */\n readOnly?: boolean;\n\n /**\n * Placeholder text to display when the editor is empty\n * @default \"\"\n */\n placeholder?: string;\n bounds?: HTMLElement | string | null;\n modules?: Record;\n\n /**\n * A list of formats that are recognized and can exist within the editor contents.\n * `null` means all formats are allowed.\n * @default null\n */\n formats?: string[] | null;\n}\n\n/**\n * Similar to QuillOptions, but with all properties expanded to their default values,\n * and all selectors resolved to HTMLElements.\n */\nexport interface ExpandedQuillOptions\n extends Omit {\n theme: ThemeConstructor;\n registry: Parchment.Registry;\n container: HTMLElement;\n modules: Record;\n bounds?: HTMLElement | null;\n readOnly: boolean;\n}\n\nclass Quill {\n static DEFAULTS = {\n bounds: null,\n modules: {\n clipboard: true,\n keyboard: true,\n history: true,\n uploader: true,\n },\n placeholder: '',\n readOnly: false,\n registry: globalRegistry,\n theme: 'default',\n } satisfies Partial;\n static events = Emitter.events;\n static sources = Emitter.sources;\n static version = typeof QUILL_VERSION === 'undefined' ? 'dev' : QUILL_VERSION;\n\n static imports: Record = {\n delta: Delta,\n parchment: Parchment,\n 'core/module': Module,\n 'core/theme': Theme,\n };\n\n static debug(limit: DebugLevel | boolean) {\n if (limit === true) {\n limit = 'log';\n }\n logger.level(limit);\n }\n\n static find(node: Node, bubble = false) {\n return instances.get(node) || globalRegistry.find(node, bubble);\n }\n\n static import(name: 'core/module'): typeof Module;\n static import(name: `themes/${string}`): typeof Theme;\n static import(name: 'parchment'): typeof Parchment;\n static import(name: 'delta'): typeof Delta;\n static import(name: string): unknown;\n static import(name: string) {\n if (this.imports[name] == null) {\n debug.error(`Cannot import ${name}. Are you sure it was registered?`);\n }\n return this.imports[name];\n }\n\n static register(\n targets: Record<\n string,\n | Parchment.RegistryDefinition\n | Record // any objects\n | Theme\n | Module\n | Function // ES5 constructors\n >,\n overwrite?: boolean,\n ): void;\n static register(\n target: Parchment.RegistryDefinition,\n overwrite?: boolean,\n ): void;\n static register(path: string, target: any, overwrite?: boolean): void;\n static register(...args: any[]): void {\n if (typeof args[0] !== 'string') {\n const target = args[0];\n const overwrite = !!args[1];\n\n const name = 'attrName' in target ? target.attrName : target.blotName;\n if (typeof name === 'string') {\n // Shortcut for formats:\n // register(Blot | Attributor, overwrite)\n this.register(`formats/${name}`, target, overwrite);\n } else {\n Object.keys(target).forEach((key) => {\n this.register(key, target[key], overwrite);\n });\n }\n } else {\n const path = args[0];\n const target = args[1];\n const overwrite = !!args[2];\n\n if (this.imports[path] != null && !overwrite) {\n debug.warn(`Overwriting ${path} with`, target);\n }\n this.imports[path] = target;\n if (\n (path.startsWith('blots/') || path.startsWith('formats/')) &&\n target &&\n typeof target !== 'boolean' &&\n target.blotName !== 'abstract'\n ) {\n globalRegistry.register(target);\n }\n if (typeof target.register === 'function') {\n target.register(globalRegistry);\n }\n }\n }\n\n container: HTMLElement;\n root: HTMLDivElement;\n scroll: Scroll;\n emitter: Emitter;\n protected allowReadOnlyEdits: boolean;\n editor: Editor;\n composition: Composition;\n selection: Selection;\n\n theme: Theme;\n keyboard: Keyboard;\n clipboard: Clipboard;\n history: History;\n uploader: Uploader;\n\n options: ExpandedQuillOptions;\n\n constructor(container: HTMLElement | string, options: QuillOptions = {}) {\n this.options = expandConfig(container, options);\n this.container = this.options.container;\n if (this.container == null) {\n debug.error('Invalid Quill container', container);\n return;\n }\n if (this.options.debug) {\n Quill.debug(this.options.debug);\n }\n const html = this.container.innerHTML.trim();\n this.container.classList.add('ql-container');\n this.container.innerHTML = '';\n instances.set(this.container, this);\n this.root = this.addContainer('ql-editor');\n this.root.classList.add('ql-blank');\n this.emitter = new Emitter();\n const scrollBlotName = Parchment.ScrollBlot.blotName;\n const ScrollBlot = this.options.registry.query(scrollBlotName);\n if (!ScrollBlot || !('blotName' in ScrollBlot)) {\n throw new Error(\n `Cannot initialize Quill without \"${scrollBlotName}\" blot`,\n );\n }\n this.scroll = new ScrollBlot(this.options.registry, this.root, {\n emitter: this.emitter,\n }) as Scroll;\n this.editor = new Editor(this.scroll);\n this.selection = new Selection(this.scroll, this.emitter);\n this.composition = new Composition(this.scroll, this.emitter);\n this.theme = new this.options.theme(this, this.options); // eslint-disable-line new-cap\n this.keyboard = this.theme.addModule('keyboard');\n this.clipboard = this.theme.addModule('clipboard');\n this.history = this.theme.addModule('history');\n this.uploader = this.theme.addModule('uploader');\n this.theme.addModule('input');\n this.theme.addModule('uiNode');\n this.theme.init();\n this.emitter.on(Emitter.events.EDITOR_CHANGE, (type) => {\n if (type === Emitter.events.TEXT_CHANGE) {\n this.root.classList.toggle('ql-blank', this.editor.isBlank());\n }\n });\n this.emitter.on(Emitter.events.SCROLL_UPDATE, (source, mutations) => {\n const oldRange = this.selection.lastRange;\n const [newRange] = this.selection.getRange();\n const selectionInfo =\n oldRange && newRange ? { oldRange, newRange } : undefined;\n modify.call(\n this,\n () => this.editor.update(null, mutations, selectionInfo),\n source,\n );\n });\n this.emitter.on(Emitter.events.SCROLL_EMBED_UPDATE, (blot, delta) => {\n const oldRange = this.selection.lastRange;\n const [newRange] = this.selection.getRange();\n const selectionInfo =\n oldRange && newRange ? { oldRange, newRange } : undefined;\n modify.call(\n this,\n () => {\n const change = new Delta()\n .retain(blot.offset(this))\n .retain({ [blot.statics.blotName]: delta });\n return this.editor.update(change, [], selectionInfo);\n },\n Quill.sources.USER,\n );\n });\n if (html) {\n const contents = this.clipboard.convert({\n html: `${html}


    `,\n text: '\\n',\n });\n this.setContents(contents);\n }\n this.history.clear();\n if (this.options.placeholder) {\n this.root.setAttribute('data-placeholder', this.options.placeholder);\n }\n if (this.options.readOnly) {\n this.disable();\n }\n this.allowReadOnlyEdits = false;\n }\n\n addContainer(container: string, refNode?: Node | null): HTMLDivElement;\n addContainer(container: HTMLElement, refNode?: Node | null): HTMLElement;\n addContainer(\n container: string | HTMLElement,\n refNode: Node | null = null,\n ): HTMLDivElement | HTMLElement {\n if (typeof container === 'string') {\n const className = container;\n container = document.createElement('div');\n container.classList.add(className);\n }\n this.container.insertBefore(container, refNode);\n return container;\n }\n\n blur() {\n this.selection.setRange(null);\n }\n\n deleteText(range: Range, source?: EmitterSource): Delta;\n deleteText(index: number, length: number, source?: EmitterSource): Delta;\n deleteText(\n index: number | Range,\n length?: number | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n // @ts-expect-error\n [index, length, , source] = overload(index, length, source);\n return modify.call(\n this,\n () => {\n return this.editor.deleteText(index, length);\n },\n source,\n index,\n -1 * length,\n );\n }\n\n disable() {\n this.enable(false);\n }\n\n editReadOnly(modifier: () => T): T {\n this.allowReadOnlyEdits = true;\n const value = modifier();\n this.allowReadOnlyEdits = false;\n return value;\n }\n\n enable(enabled = true) {\n this.scroll.enable(enabled);\n this.container.classList.toggle('ql-disabled', !enabled);\n }\n\n focus(options: { preventScroll?: boolean } = {}) {\n this.selection.focus();\n if (!options.preventScroll) {\n this.scrollSelectionIntoView();\n }\n }\n\n format(\n name: string,\n value: unknown,\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n const range = this.getSelection(true);\n let change = new Delta();\n if (range == null) return change;\n if (this.scroll.query(name, Parchment.Scope.BLOCK)) {\n change = this.editor.formatLine(range.index, range.length, {\n [name]: value,\n });\n } else if (range.length === 0) {\n this.selection.format(name, value);\n return change;\n } else {\n change = this.editor.formatText(range.index, range.length, {\n [name]: value,\n });\n }\n this.setSelection(range, Emitter.sources.SILENT);\n return change;\n },\n source,\n );\n }\n\n formatLine(\n index: number,\n length: number,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n formatLine(\n index: number,\n length: number,\n name: string,\n value?: unknown,\n source?: EmitterSource,\n ): Delta;\n formatLine(\n index: number,\n length: number,\n name: string | Record,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n [index, length, formats, source] = overload(\n index,\n length,\n // @ts-expect-error\n name,\n value,\n source,\n );\n return modify.call(\n this,\n () => {\n return this.editor.formatLine(index, length, formats);\n },\n source,\n index,\n 0,\n );\n }\n\n formatText(\n range: Range,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number,\n length: number,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number,\n length: number,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number | Range,\n length: number | string,\n name: string | unknown,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n [index, length, formats, source] = overload(\n // @ts-expect-error\n index,\n length,\n name,\n value,\n source,\n );\n return modify.call(\n this,\n () => {\n return this.editor.formatText(index, length, formats);\n },\n source,\n index,\n 0,\n );\n }\n\n getBounds(index: number | Range, length = 0): Bounds | null {\n let bounds: Bounds | null = null;\n if (typeof index === 'number') {\n bounds = this.selection.getBounds(index, length);\n } else {\n bounds = this.selection.getBounds(index.index, index.length);\n }\n if (!bounds) return null;\n const containerBounds = this.container.getBoundingClientRect();\n return {\n bottom: bounds.bottom - containerBounds.top,\n height: bounds.height,\n left: bounds.left - containerBounds.left,\n right: bounds.right - containerBounds.left,\n top: bounds.top - containerBounds.top,\n width: bounds.width,\n };\n }\n\n getContents(index = 0, length = this.getLength() - index) {\n [index, length] = overload(index, length);\n return this.editor.getContents(index, length);\n }\n\n getFormat(index?: number, length?: number): { [format: string]: unknown };\n getFormat(range?: Range): {\n [format: string]: unknown;\n };\n getFormat(\n index: Range | number = this.getSelection(true),\n length = 0,\n ): { [format: string]: unknown } {\n if (typeof index === 'number') {\n return this.editor.getFormat(index, length);\n }\n return this.editor.getFormat(index.index, index.length);\n }\n\n getIndex(blot: Parchment.Blot) {\n return blot.offset(this.scroll);\n }\n\n getLength() {\n return this.scroll.length();\n }\n\n getLeaf(index: number) {\n return this.scroll.leaf(index);\n }\n\n getLine(index: number) {\n return this.scroll.line(index);\n }\n\n getLines(range: Range): (Block | BlockEmbed)[];\n getLines(index?: number, length?: number): (Block | BlockEmbed)[];\n getLines(\n index: Range | number = 0,\n length = Number.MAX_VALUE,\n ): (Block | BlockEmbed)[] {\n if (typeof index !== 'number') {\n return this.scroll.lines(index.index, index.length);\n }\n return this.scroll.lines(index, length);\n }\n\n getModule(name: string) {\n return this.theme.modules[name];\n }\n\n getSelection(focus: true): Range;\n getSelection(focus?: boolean): Range | null;\n getSelection(focus = false): Range | null {\n if (focus) this.focus();\n this.update(); // Make sure we access getRange with editor in consistent state\n return this.selection.getRange()[0];\n }\n\n getSemanticHTML(range: Range): string;\n getSemanticHTML(index?: number, length?: number): string;\n getSemanticHTML(index: Range | number = 0, length?: number) {\n if (typeof index === 'number') {\n length = length ?? this.getLength() - index;\n }\n // @ts-expect-error\n [index, length] = overload(index, length);\n return this.editor.getHTML(index, length);\n }\n\n getText(range?: Range): string;\n getText(index?: number, length?: number): string;\n getText(index: Range | number = 0, length?: number): string {\n if (typeof index === 'number') {\n length = length ?? this.getLength() - index;\n }\n // @ts-expect-error\n [index, length] = overload(index, length);\n return this.editor.getText(index, length);\n }\n\n hasFocus() {\n return this.selection.hasFocus();\n }\n\n insertEmbed(\n index: number,\n embed: string,\n value: unknown,\n source: EmitterSource = Quill.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n return this.editor.insertEmbed(index, embed, value);\n },\n source,\n index,\n );\n }\n\n insertText(index: number, text: string, source?: EmitterSource): Delta;\n insertText(\n index: number,\n text: string,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n insertText(\n index: number,\n text: string,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n insertText(\n index: number,\n text: string,\n name?: string | Record | EmitterSource,\n value?: unknown,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n // @ts-expect-error\n [index, , formats, source] = overload(index, 0, name, value, source);\n return modify.call(\n this,\n () => {\n return this.editor.insertText(index, text, formats);\n },\n source,\n index,\n text.length,\n );\n }\n\n isEnabled() {\n return this.scroll.isEnabled();\n }\n\n off(...args: Parameters<(typeof Emitter)['prototype']['off']>) {\n return this.emitter.off(...args);\n }\n\n on(\n event: (typeof Emitter)['events']['TEXT_CHANGE'],\n handler: (delta: Delta, oldContent: Delta, source: EmitterSource) => void,\n ): Emitter;\n on(\n event: (typeof Emitter)['events']['SELECTION_CHANGE'],\n handler: (range: Range, oldRange: Range, source: EmitterSource) => void,\n ): Emitter;\n on(\n event: (typeof Emitter)['events']['EDITOR_CHANGE'],\n handler: (\n ...args:\n | [\n (typeof Emitter)['events']['TEXT_CHANGE'],\n Delta,\n Delta,\n EmitterSource,\n ]\n | [\n (typeof Emitter)['events']['SELECTION_CHANGE'],\n Range,\n Range,\n EmitterSource,\n ]\n ) => void,\n ): Emitter;\n on(event: string, ...args: unknown[]): Emitter;\n on(...args: Parameters<(typeof Emitter)['prototype']['on']>): Emitter {\n return this.emitter.on(...args);\n }\n\n once(...args: Parameters<(typeof Emitter)['prototype']['once']>) {\n return this.emitter.once(...args);\n }\n\n removeFormat(index: number, length: number, source?: EmitterSource): Delta {\n [index, length, , source] = overload(index, length, source);\n return modify.call(\n this,\n () => {\n return this.editor.removeFormat(index, length);\n },\n source,\n index,\n );\n }\n\n scrollRectIntoView(rect: Rect) {\n scrollRectIntoView(this.root, rect);\n }\n\n /**\n * @deprecated Use Quill#scrollSelectionIntoView() instead.\n */\n scrollIntoView() {\n console.warn(\n 'Quill#scrollIntoView() has been deprecated and will be removed in the near future. Please use Quill#scrollSelectionIntoView() instead.',\n );\n this.scrollSelectionIntoView();\n }\n\n /**\n * Scroll the current selection into the visible area.\n * If the selection is already visible, no scrolling will occur.\n */\n scrollSelectionIntoView() {\n const range = this.selection.lastRange;\n const bounds = range && this.selection.getBounds(range.index, range.length);\n if (bounds) {\n this.scrollRectIntoView(bounds);\n }\n }\n\n setContents(\n delta: Delta | Op[],\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n delta = new Delta(delta);\n const length = this.getLength();\n // Quill will set empty editor to \\n\n const delete1 = this.editor.deleteText(0, length);\n const applied = this.editor.insertContents(0, delta);\n // Remove extra \\n from empty editor initialization\n const delete2 = this.editor.deleteText(this.getLength() - 1, 1);\n return delete1.compose(applied).compose(delete2);\n },\n source,\n );\n }\n setSelection(range: Range | null, source?: EmitterSource): void;\n setSelection(index: number, source?: EmitterSource): void;\n setSelection(index: number, length?: number, source?: EmitterSource): void;\n setSelection(index: number, source?: EmitterSource): void;\n setSelection(\n index: Range | null | number,\n length?: EmitterSource | number,\n source?: EmitterSource,\n ): void {\n if (index == null) {\n // @ts-expect-error https://github.com/microsoft/TypeScript/issues/22609\n this.selection.setRange(null, length || Quill.sources.API);\n } else {\n // @ts-expect-error\n [index, length, , source] = overload(index, length, source);\n this.selection.setRange(new Range(Math.max(0, index), length), source);\n if (source !== Emitter.sources.SILENT) {\n this.scrollSelectionIntoView();\n }\n }\n }\n\n setText(text: string, source: EmitterSource = Emitter.sources.API) {\n const delta = new Delta().insert(text);\n return this.setContents(delta, source);\n }\n\n update(source: EmitterSource = Emitter.sources.USER) {\n const change = this.scroll.update(source); // Will update selection before selection.update() does if text changes\n this.selection.update(source);\n // TODO this is usually undefined\n return change;\n }\n\n updateContents(\n delta: Delta | Op[],\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n delta = new Delta(delta);\n return this.editor.applyDelta(delta);\n },\n source,\n true,\n );\n }\n}\n\nfunction resolveSelector(selector: string | HTMLElement | null | undefined) {\n return typeof selector === 'string'\n ? document.querySelector(selector)\n : selector;\n}\n\nfunction expandModuleConfig(config: Record | undefined) {\n return Object.entries(config ?? {}).reduce(\n (expanded, [key, value]) => ({\n ...expanded,\n [key]: value === true ? {} : value,\n }),\n {} as Record,\n );\n}\n\nfunction omitUndefinedValuesFromOptions(obj: QuillOptions) {\n return Object.fromEntries(\n Object.entries(obj).filter((entry) => entry[1] !== undefined),\n );\n}\n\nfunction expandConfig(\n containerOrSelector: HTMLElement | string,\n options: QuillOptions,\n): ExpandedQuillOptions {\n const container = resolveSelector(containerOrSelector);\n if (!container) {\n throw new Error('Invalid Quill container');\n }\n\n const shouldUseDefaultTheme =\n !options.theme || options.theme === Quill.DEFAULTS.theme;\n const theme = shouldUseDefaultTheme\n ? Theme\n : Quill.import(`themes/${options.theme}`);\n if (!theme) {\n throw new Error(`Invalid theme ${options.theme}. Did you register it?`);\n }\n\n const { modules: quillModuleDefaults, ...quillDefaults } = Quill.DEFAULTS;\n const { modules: themeModuleDefaults, ...themeDefaults } = theme.DEFAULTS;\n\n let userModuleOptions = expandModuleConfig(options.modules);\n // Special case toolbar shorthand\n if (\n userModuleOptions != null &&\n userModuleOptions.toolbar &&\n userModuleOptions.toolbar.constructor !== Object\n ) {\n userModuleOptions = {\n ...userModuleOptions,\n toolbar: { container: userModuleOptions.toolbar },\n };\n }\n\n const modules: ExpandedQuillOptions['modules'] = merge(\n {},\n expandModuleConfig(quillModuleDefaults),\n expandModuleConfig(themeModuleDefaults),\n userModuleOptions,\n );\n\n const config = {\n ...quillDefaults,\n ...omitUndefinedValuesFromOptions(themeDefaults),\n ...omitUndefinedValuesFromOptions(options),\n };\n\n let registry = options.registry;\n if (registry) {\n if (options.formats) {\n debug.warn('Ignoring \"formats\" option because \"registry\" is specified');\n }\n } else {\n registry = options.formats\n ? createRegistryWithFormats(options.formats, config.registry, debug)\n : config.registry;\n }\n\n return {\n ...config,\n registry,\n container,\n theme,\n modules: Object.entries(modules).reduce(\n (modulesWithDefaults, [name, value]) => {\n if (!value) return modulesWithDefaults;\n\n const moduleClass = Quill.import(`modules/${name}`);\n if (moduleClass == null) {\n debug.error(\n `Cannot load ${name} module. Are you sure you registered it?`,\n );\n return modulesWithDefaults;\n }\n return {\n ...modulesWithDefaults,\n // @ts-expect-error\n [name]: merge({}, moduleClass.DEFAULTS || {}, value),\n };\n },\n {},\n ),\n bounds: resolveSelector(config.bounds),\n };\n}\n\n// Handle selection preservation and TEXT_CHANGE emission\n// common to modification APIs\nfunction modify(\n modifier: () => Delta,\n source: EmitterSource,\n index: number | boolean,\n shift: number | null,\n) {\n if (\n !this.isEnabled() &&\n source === Emitter.sources.USER &&\n !this.allowReadOnlyEdits\n ) {\n return new Delta();\n }\n let range = index == null ? null : this.getSelection();\n const oldDelta = this.editor.delta;\n const change = modifier();\n if (range != null) {\n if (index === true) {\n index = range.index; // eslint-disable-line prefer-destructuring\n }\n if (shift == null) {\n range = shiftRange(range, change, source);\n } else if (shift !== 0) {\n // @ts-expect-error index should always be number\n range = shiftRange(range, index, shift, source);\n }\n this.setSelection(range, Emitter.sources.SILENT);\n }\n if (change.length() > 0) {\n const args = [Emitter.events.TEXT_CHANGE, change, oldDelta, source];\n this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);\n if (source !== Emitter.sources.SILENT) {\n this.emitter.emit(...args);\n }\n }\n return change;\n}\n\ntype NormalizedIndexLength = [\n number,\n number,\n Record,\n EmitterSource,\n];\nfunction overload(index: number, source?: EmitterSource): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n format: string,\n value: unknown,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n format: Record,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(range: Range, source?: EmitterSource): NormalizedIndexLength;\nfunction overload(\n range: Range,\n format: string,\n value: unknown,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n range: Range,\n format: Record,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: Range | number,\n length?: number | string | Record | EmitterSource,\n name?: string | unknown | Record | EmitterSource,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n): NormalizedIndexLength {\n let formats: Record = {};\n // @ts-expect-error\n if (typeof index.index === 'number' && typeof index.length === 'number') {\n // Allow for throwaway end (used by insertText/insertEmbed)\n if (typeof length !== 'number') {\n // @ts-expect-error\n source = value;\n value = name;\n name = length;\n // @ts-expect-error\n length = index.length; // eslint-disable-line prefer-destructuring\n // @ts-expect-error\n index = index.index; // eslint-disable-line prefer-destructuring\n } else {\n // @ts-expect-error\n length = index.length; // eslint-disable-line prefer-destructuring\n // @ts-expect-error\n index = index.index; // eslint-disable-line prefer-destructuring\n }\n } else if (typeof length !== 'number') {\n // @ts-expect-error\n source = value;\n value = name;\n name = length;\n length = 0;\n }\n // Handle format being object, two format name/value strings or excluded\n if (typeof name === 'object') {\n // @ts-expect-error Fix me later\n formats = name;\n // @ts-expect-error\n source = value;\n } else if (typeof name === 'string') {\n if (value != null) {\n formats[name] = value;\n } else {\n // @ts-expect-error\n source = name;\n }\n }\n // Handle optional source\n source = source || Emitter.sources.API;\n // @ts-expect-error\n return [index, length, formats, source];\n}\n\nfunction shiftRange(range: Range, change: Delta, source?: EmitterSource): Range;\nfunction shiftRange(\n range: Range,\n index: number,\n length?: number,\n source?: EmitterSource,\n): Range;\nfunction shiftRange(\n range: Range,\n index: number | Delta,\n lengthOrSource?: number | EmitterSource,\n source?: EmitterSource,\n) {\n const length = typeof lengthOrSource === 'number' ? lengthOrSource : 0;\n if (range == null) return null;\n let start;\n let end;\n // @ts-expect-error -- TODO: add a better type guard around `index`\n if (index && typeof index.transformPosition === 'function') {\n [start, end] = [range.index, range.index + range.length].map((pos) =>\n // @ts-expect-error -- TODO: add a better type guard around `index`\n index.transformPosition(pos, source !== Emitter.sources.USER),\n );\n } else {\n [start, end] = [range.index, range.index + range.length].map((pos) => {\n // @ts-expect-error -- TODO: add a better type guard around `index`\n if (pos < index || (pos === index && source === Emitter.sources.USER))\n return pos;\n if (length >= 0) {\n return pos + length;\n }\n // @ts-expect-error -- TODO: add a better type guard around `index`\n return Math.max(index, pos + length);\n });\n }\n return new Range(start, end - start);\n}\n\nexport type { Bounds, DebugLevel, EmitterSource };\nexport { Parchment, Range };\n\nexport { globalRegistry, expandConfig, overload, Quill as default };\n", "import { ContainerBlot } from 'parchment';\n\nclass Container extends ContainerBlot {}\n\nexport default Container;\n", "import { ContainerBlot, LeafBlot, Scope, ScrollBlot } from 'parchment';\nimport type { Blot, Parent, EmbedBlot, ParentBlot, Registry } from 'parchment';\nimport Delta, { AttributeMap, Op } from 'quill-delta';\nimport Emitter from '../core/emitter.js';\nimport type { EmitterSource } from '../core/emitter.js';\nimport Block, { BlockEmbed, bubbleFormats } from './block.js';\nimport Break from './break.js';\nimport Container from './container.js';\n\ntype RenderBlock =\n | {\n type: 'blockEmbed';\n attributes: AttributeMap;\n key: string;\n value: unknown;\n }\n | { type: 'block'; attributes: AttributeMap; delta: Delta };\n\nfunction isLine(blot: unknown): blot is Block | BlockEmbed {\n return blot instanceof Block || blot instanceof BlockEmbed;\n}\n\ninterface UpdatableEmbed {\n updateContent(change: unknown): void;\n}\n\nfunction isUpdatable(blot: Blot): blot is Blot & UpdatableEmbed {\n return typeof (blot as unknown as any).updateContent === 'function';\n}\n\nclass Scroll extends ScrollBlot {\n static blotName = 'scroll';\n static className = 'ql-editor';\n static tagName = 'DIV';\n static defaultChild = Block;\n static allowedChildren = [Block, BlockEmbed, Container];\n\n emitter: Emitter;\n batch: false | MutationRecord[];\n\n constructor(\n registry: Registry,\n domNode: HTMLDivElement,\n { emitter }: { emitter: Emitter },\n ) {\n super(registry, domNode);\n this.emitter = emitter;\n this.batch = false;\n this.optimize();\n this.enable();\n this.domNode.addEventListener('dragstart', (e) => this.handleDragStart(e));\n }\n\n batchStart() {\n if (!Array.isArray(this.batch)) {\n this.batch = [];\n }\n }\n\n batchEnd() {\n if (!this.batch) return;\n const mutations = this.batch;\n this.batch = false;\n this.update(mutations);\n }\n\n emitMount(blot: Blot) {\n this.emitter.emit(Emitter.events.SCROLL_BLOT_MOUNT, blot);\n }\n\n emitUnmount(blot: Blot) {\n this.emitter.emit(Emitter.events.SCROLL_BLOT_UNMOUNT, blot);\n }\n\n emitEmbedUpdate(blot: Blot, change: unknown) {\n this.emitter.emit(Emitter.events.SCROLL_EMBED_UPDATE, blot, change);\n }\n\n deleteAt(index: number, length: number) {\n const [first, offset] = this.line(index);\n const [last] = this.line(index + length);\n super.deleteAt(index, length);\n if (last != null && first !== last && offset > 0) {\n if (first instanceof BlockEmbed || last instanceof BlockEmbed) {\n this.optimize();\n return;\n }\n const ref =\n last.children.head instanceof Break ? null : last.children.head;\n // @ts-expect-error\n first.moveChildren(last, ref);\n // @ts-expect-error\n first.remove();\n }\n this.optimize();\n }\n\n enable(enabled = true) {\n this.domNode.setAttribute('contenteditable', enabled ? 'true' : 'false');\n }\n\n formatAt(index: number, length: number, format: string, value: unknown) {\n super.formatAt(index, length, format, value);\n this.optimize();\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (index >= this.length()) {\n if (def == null || this.scroll.query(value, Scope.BLOCK) == null) {\n const blot = this.scroll.create(this.statics.defaultChild.blotName);\n this.appendChild(blot);\n if (def == null && value.endsWith('\\n')) {\n blot.insertAt(0, value.slice(0, -1), def);\n } else {\n blot.insertAt(0, value, def);\n }\n } else {\n const embed = this.scroll.create(value, def);\n this.appendChild(embed);\n }\n } else {\n super.insertAt(index, value, def);\n }\n this.optimize();\n }\n\n insertBefore(blot: Blot, ref?: Blot | null) {\n if (blot.statics.scope === Scope.INLINE_BLOT) {\n const wrapper = this.scroll.create(\n this.statics.defaultChild.blotName,\n ) as Parent;\n wrapper.appendChild(blot);\n super.insertBefore(wrapper, ref);\n } else {\n super.insertBefore(blot, ref);\n }\n }\n\n insertContents(index: number, delta: Delta) {\n const renderBlocks = this.deltaToRenderBlocks(\n delta.concat(new Delta().insert('\\n')),\n );\n const last = renderBlocks.pop();\n if (last == null) return;\n\n this.batchStart();\n\n const first = renderBlocks.shift();\n if (first) {\n const shouldInsertNewlineChar =\n first.type === 'block' &&\n (first.delta.length() === 0 ||\n (!this.descendant(BlockEmbed, index)[0] && index < this.length()));\n const delta =\n first.type === 'block'\n ? first.delta\n : new Delta().insert({ [first.key]: first.value });\n insertInlineContents(this, index, delta);\n const newlineCharLength = first.type === 'block' ? 1 : 0;\n const lineEndIndex = index + delta.length() + newlineCharLength;\n if (shouldInsertNewlineChar) {\n this.insertAt(lineEndIndex - 1, '\\n');\n }\n\n const formats = bubbleFormats(this.line(index)[0]);\n const attributes = AttributeMap.diff(formats, first.attributes) || {};\n Object.keys(attributes).forEach((name) => {\n this.formatAt(lineEndIndex - 1, 1, name, attributes[name]);\n });\n\n index = lineEndIndex;\n }\n\n let [refBlot, refBlotOffset] = this.children.find(index);\n if (renderBlocks.length) {\n if (refBlot) {\n refBlot = refBlot.split(refBlotOffset);\n refBlotOffset = 0;\n }\n\n renderBlocks.forEach((renderBlock) => {\n if (renderBlock.type === 'block') {\n const block = this.createBlock(\n renderBlock.attributes,\n refBlot || undefined,\n );\n insertInlineContents(block, 0, renderBlock.delta);\n } else {\n const blockEmbed = this.create(\n renderBlock.key,\n renderBlock.value,\n ) as EmbedBlot;\n this.insertBefore(blockEmbed, refBlot || undefined);\n Object.keys(renderBlock.attributes).forEach((name) => {\n blockEmbed.format(name, renderBlock.attributes[name]);\n });\n }\n });\n }\n\n if (last.type === 'block' && last.delta.length()) {\n const offset = refBlot\n ? refBlot.offset(refBlot.scroll) + refBlotOffset\n : this.length();\n insertInlineContents(this, offset, last.delta);\n }\n\n this.batchEnd();\n this.optimize();\n }\n\n isEnabled() {\n return this.domNode.getAttribute('contenteditable') === 'true';\n }\n\n leaf(index: number): [LeafBlot | null, number] {\n const last = this.path(index).pop();\n if (!last) {\n return [null, -1];\n }\n\n const [blot, offset] = last;\n return blot instanceof LeafBlot ? [blot, offset] : [null, -1];\n }\n\n line(index: number): [Block | BlockEmbed | null, number] {\n if (index === this.length()) {\n return this.line(index - 1);\n }\n // @ts-expect-error TODO: make descendant() generic\n return this.descendant(isLine, index);\n }\n\n lines(index = 0, length = Number.MAX_VALUE): (Block | BlockEmbed)[] {\n const getLines = (\n blot: ParentBlot,\n blotIndex: number,\n blotLength: number,\n ) => {\n let lines: (Block | BlockEmbed)[] = [];\n let lengthLeft = blotLength;\n blot.children.forEachAt(\n blotIndex,\n blotLength,\n (child, childIndex, childLength) => {\n if (isLine(child)) {\n lines.push(child);\n } else if (child instanceof ContainerBlot) {\n lines = lines.concat(getLines(child, childIndex, lengthLeft));\n }\n lengthLeft -= childLength;\n },\n );\n return lines;\n };\n return getLines(this, index, length);\n }\n\n optimize(context?: { [key: string]: any }): void;\n optimize(\n mutations?: MutationRecord[],\n context?: { [key: string]: any },\n ): void;\n optimize(mutations = [], context = {}) {\n if (this.batch) return;\n super.optimize(mutations, context);\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_OPTIMIZE, mutations, context);\n }\n }\n\n path(index: number) {\n return super.path(index).slice(1); // Exclude self\n }\n\n remove() {\n // Never remove self\n }\n\n update(source?: EmitterSource): void;\n update(mutations?: MutationRecord[]): void;\n update(mutations?: MutationRecord[] | EmitterSource): void {\n if (this.batch) {\n if (Array.isArray(mutations)) {\n this.batch = this.batch.concat(mutations);\n }\n return;\n }\n let source: EmitterSource = Emitter.sources.USER;\n if (typeof mutations === 'string') {\n source = mutations;\n }\n if (!Array.isArray(mutations)) {\n mutations = this.observer.takeRecords();\n }\n mutations = mutations.filter(({ target }) => {\n const blot = this.find(target, true);\n return blot && !isUpdatable(blot);\n });\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_BEFORE_UPDATE, source, mutations);\n }\n super.update(mutations.concat([])); // pass copy\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_UPDATE, source, mutations);\n }\n }\n\n updateEmbedAt(index: number, key: string, change: unknown) {\n // Currently it only supports top-level embeds (BlockEmbed).\n // We can update `ParentBlot` in parchment to support inline embeds.\n const [blot] = this.descendant((b: Blot) => b instanceof BlockEmbed, index);\n if (blot && blot.statics.blotName === key && isUpdatable(blot)) {\n blot.updateContent(change);\n }\n }\n\n protected handleDragStart(event: DragEvent) {\n event.preventDefault();\n }\n\n private deltaToRenderBlocks(delta: Delta) {\n const renderBlocks: RenderBlock[] = [];\n\n let currentBlockDelta = new Delta();\n delta.forEach((op) => {\n const insert = op?.insert;\n if (!insert) return;\n if (typeof insert === 'string') {\n const splitted = insert.split('\\n');\n splitted.slice(0, -1).forEach((text) => {\n currentBlockDelta.insert(text, op.attributes);\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: op.attributes ?? {},\n });\n currentBlockDelta = new Delta();\n });\n const last = splitted[splitted.length - 1];\n if (last) {\n currentBlockDelta.insert(last, op.attributes);\n }\n } else {\n const key = Object.keys(insert)[0];\n if (!key) return;\n if (this.query(key, Scope.INLINE)) {\n currentBlockDelta.push(op);\n } else {\n if (currentBlockDelta.length()) {\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: {},\n });\n }\n currentBlockDelta = new Delta();\n renderBlocks.push({\n type: 'blockEmbed',\n key,\n value: insert[key],\n attributes: op.attributes ?? {},\n });\n }\n }\n });\n\n if (currentBlockDelta.length()) {\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: {},\n });\n }\n\n return renderBlocks;\n }\n\n private createBlock(attributes: AttributeMap, refBlot?: Blot) {\n let blotName: string | undefined;\n const formats: AttributeMap = {};\n\n Object.entries(attributes).forEach(([key, value]) => {\n const isBlockBlot = this.query(key, Scope.BLOCK & Scope.BLOT) != null;\n if (isBlockBlot) {\n blotName = key;\n } else {\n formats[key] = value;\n }\n });\n\n const block = this.create(\n blotName || this.statics.defaultChild.blotName,\n blotName ? attributes[blotName] : undefined,\n ) as ParentBlot;\n\n this.insertBefore(block, refBlot || undefined);\n\n const length = block.length();\n Object.entries(formats).forEach(([key, value]) => {\n block.formatAt(0, length, key, value);\n });\n\n return block;\n }\n}\n\nfunction insertInlineContents(\n parent: ParentBlot,\n index: number,\n inlineContents: Delta,\n) {\n inlineContents.reduce((index, op) => {\n const length = Op.length(op);\n let attributes = op.attributes || {};\n if (op.insert != null) {\n if (typeof op.insert === 'string') {\n const text = op.insert;\n parent.insertAt(index, text);\n const [leaf] = parent.descendant(LeafBlot, index);\n const formats = bubbleFormats(leaf);\n attributes = AttributeMap.diff(formats, attributes) || {};\n } else if (typeof op.insert === 'object') {\n const key = Object.keys(op.insert)[0]; // There should only be one key\n if (key == null) return index;\n parent.insertAt(index, key, op.insert[key]);\n const isInlineEmbed = parent.scroll.query(key, Scope.INLINE) != null;\n if (isInlineEmbed) {\n const [leaf] = parent.descendant(LeafBlot, index);\n const formats = bubbleFormats(leaf);\n attributes = AttributeMap.diff(formats, attributes) || {};\n }\n }\n }\n Object.keys(attributes).forEach((key) => {\n parent.formatAt(index, length, key, attributes[key]);\n });\n return index + length;\n }, index);\n}\n\nexport default Scroll;\n", "import { Attributor, ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.BLOCK,\n whitelist: ['right', 'center', 'justify'],\n};\n\nconst AlignAttribute = new Attributor('align', 'align', config);\nconst AlignClass = new ClassAttributor('align', 'ql-align', config);\nconst AlignStyle = new StyleAttributor('align', 'text-align', config);\n\nexport { AlignAttribute, AlignClass, AlignStyle };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nclass ColorAttributor extends StyleAttributor {\n value(domNode: HTMLElement) {\n let value = super.value(domNode) as string;\n if (!value.startsWith('rgb(')) return value;\n value = value.replace(/^[^\\d]+/, '').replace(/[^\\d]+$/, '');\n const hex = value\n .split(',')\n .map((component) => `00${parseInt(component, 10).toString(16)}`.slice(-2))\n .join('');\n return `#${hex}`;\n }\n}\n\nconst ColorClass = new ClassAttributor('color', 'ql-color', {\n scope: Scope.INLINE,\n});\nconst ColorStyle = new ColorAttributor('color', 'color', {\n scope: Scope.INLINE,\n});\n\nexport { ColorAttributor, ColorClass, ColorStyle };\n", "import { ClassAttributor, Scope } from 'parchment';\nimport { ColorAttributor } from './color.js';\n\nconst BackgroundClass = new ClassAttributor('background', 'ql-bg', {\n scope: Scope.INLINE,\n});\nconst BackgroundStyle = new ColorAttributor('background', 'background-color', {\n scope: Scope.INLINE,\n});\n\nexport { BackgroundClass, BackgroundStyle };\n", "import Block from '../blots/block.js';\nimport Break from '../blots/break.js';\nimport Cursor from '../blots/cursor.js';\nimport Inline from '../blots/inline.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport Container from '../blots/container.js';\nimport Quill from '../core/quill.js';\n\nclass CodeBlockContainer extends Container {\n static create(value: string) {\n const domNode = super.create(value) as Element;\n domNode.setAttribute('spellcheck', 'false');\n return domNode;\n }\n\n code(index: number, length: number) {\n return (\n this.children\n // @ts-expect-error\n .map((child) => (child.length() <= 1 ? '' : child.domNode.innerText))\n .join('\\n')\n .slice(index, index + length)\n );\n }\n\n html(index: number, length: number) {\n // `\\n`s are needed in order to support empty lines at the beginning and the end.\n // https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions\n return `
    \\n${escapeText(this.code(index, length))}\\n
    `;\n }\n}\n\nclass CodeBlock extends Block {\n static TAB = ' ';\n\n static register() {\n Quill.register(CodeBlockContainer);\n }\n}\n\nclass Code extends Inline {}\nCode.blotName = 'code';\nCode.tagName = 'CODE';\n\nCodeBlock.blotName = 'code-block';\nCodeBlock.className = 'ql-code-block';\nCodeBlock.tagName = 'DIV';\nCodeBlockContainer.blotName = 'code-block-container';\nCodeBlockContainer.className = 'ql-code-block-container';\nCodeBlockContainer.tagName = 'DIV';\n\nCodeBlockContainer.allowedChildren = [CodeBlock];\n\nCodeBlock.allowedChildren = [TextBlot, Break, Cursor];\nCodeBlock.requiredContainer = CodeBlockContainer;\n\nexport { Code, CodeBlockContainer, CodeBlock as default };\n", "import { Attributor, ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.BLOCK,\n whitelist: ['rtl'],\n};\n\nconst DirectionAttribute = new Attributor('direction', 'dir', config);\nconst DirectionClass = new ClassAttributor('direction', 'ql-direction', config);\nconst DirectionStyle = new StyleAttributor('direction', 'direction', config);\n\nexport { DirectionAttribute, DirectionClass, DirectionStyle };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.INLINE,\n whitelist: ['serif', 'monospace'],\n};\n\nconst FontClass = new ClassAttributor('font', 'ql-font', config);\n\nclass FontStyleAttributor extends StyleAttributor {\n value(node: HTMLElement) {\n return super.value(node).replace(/[\"']/g, '');\n }\n}\n\nconst FontStyle = new FontStyleAttributor('font', 'font-family', config);\n\nexport { FontStyle, FontClass };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst SizeClass = new ClassAttributor('size', 'ql-size', {\n scope: Scope.INLINE,\n whitelist: ['small', 'large', 'huge'],\n});\nconst SizeStyle = new StyleAttributor('size', 'font-size', {\n scope: Scope.INLINE,\n whitelist: ['10px', '18px', '32px'],\n});\n\nexport { SizeClass, SizeStyle };\n", "import { cloneDeep, isEqual } from 'lodash-es';\nimport Delta, { AttributeMap } from 'quill-delta';\nimport { EmbedBlot, Scope, TextBlot } from 'parchment';\nimport type { Blot, BlockBlot } from 'parchment';\nimport Quill from '../core/quill.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport type { BlockEmbed } from '../blots/block.js';\nimport type { Range } from '../core/selection.js';\n\nconst debug = logger('quill:keyboard');\n\nconst SHORTKEY = /Mac/i.test(navigator.platform) ? 'metaKey' : 'ctrlKey';\n\nexport interface Context {\n collapsed: boolean;\n empty: boolean;\n offset: number;\n prefix: string;\n suffix: string;\n format: Record;\n event: KeyboardEvent;\n line: BlockEmbed | BlockBlot;\n}\n\ninterface BindingObject\n extends Partial> {\n key: number | string | string[];\n shortKey?: boolean | null;\n shiftKey?: boolean | null;\n altKey?: boolean | null;\n metaKey?: boolean | null;\n ctrlKey?: boolean | null;\n prefix?: RegExp;\n suffix?: RegExp;\n format?: Record | string[];\n handler?: (\n this: { quill: Quill },\n range: Range,\n curContext: Context,\n // eslint-disable-next-line no-use-before-define\n binding: NormalizedBinding,\n ) => boolean | void;\n}\n\ntype Binding = BindingObject | string | number;\n\ninterface NormalizedBinding extends Omit {\n key: string | number;\n}\n\ninterface KeyboardOptions {\n bindings: Record;\n}\n\ninterface KeyboardOptions {\n bindings: Record;\n}\n\nclass Keyboard extends Module {\n static DEFAULTS: KeyboardOptions;\n\n static match(evt: KeyboardEvent, binding: BindingObject) {\n if (\n (['altKey', 'ctrlKey', 'metaKey', 'shiftKey'] as const).some((key) => {\n return !!binding[key] !== evt[key] && binding[key] !== null;\n })\n ) {\n return false;\n }\n return binding.key === evt.key || binding.key === evt.which;\n }\n\n bindings: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.bindings = {};\n // @ts-expect-error Fix me later\n Object.keys(this.options.bindings).forEach((name) => {\n // @ts-expect-error Fix me later\n if (this.options.bindings[name]) {\n // @ts-expect-error Fix me later\n this.addBinding(this.options.bindings[name]);\n }\n });\n this.addBinding({ key: 'Enter', shiftKey: null }, this.handleEnter);\n this.addBinding(\n { key: 'Enter', metaKey: null, ctrlKey: null, altKey: null },\n () => {},\n );\n if (/Firefox/i.test(navigator.userAgent)) {\n // Need to handle delete and backspace for Firefox in the general case #1171\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: true },\n this.handleBackspace,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: true },\n this.handleDelete,\n );\n } else {\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: true, prefix: /^.?$/ },\n this.handleBackspace,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: true, suffix: /^.?$/ },\n this.handleDelete,\n );\n }\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: false },\n this.handleDeleteRange,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: false },\n this.handleDeleteRange,\n );\n this.addBinding(\n {\n key: 'Backspace',\n altKey: null,\n ctrlKey: null,\n metaKey: null,\n shiftKey: null,\n },\n { collapsed: true, offset: 0 },\n this.handleBackspace,\n );\n this.listen();\n }\n\n addBinding(\n keyBinding: Binding,\n context:\n | Required\n | Partial> = {},\n handler:\n | Required\n | Partial> = {},\n ) {\n const binding = normalize(keyBinding);\n if (binding == null) {\n debug.warn('Attempted to add invalid keyboard binding', binding);\n return;\n }\n if (typeof context === 'function') {\n context = { handler: context };\n }\n if (typeof handler === 'function') {\n handler = { handler };\n }\n const keys = Array.isArray(binding.key) ? binding.key : [binding.key];\n keys.forEach((key) => {\n const singleBinding = {\n ...binding,\n key,\n ...context,\n ...handler,\n };\n this.bindings[singleBinding.key] = this.bindings[singleBinding.key] || [];\n this.bindings[singleBinding.key].push(singleBinding);\n });\n }\n\n listen() {\n this.quill.root.addEventListener('keydown', (evt) => {\n if (evt.defaultPrevented || evt.isComposing) return;\n\n // evt.isComposing is false when pressing Enter/Backspace when composing in Safari\n // https://bugs.webkit.org/show_bug.cgi?id=165004\n const isComposing =\n evt.keyCode === 229 && (evt.key === 'Enter' || evt.key === 'Backspace');\n if (isComposing) return;\n\n const bindings = (this.bindings[evt.key] || []).concat(\n this.bindings[evt.which] || [],\n );\n const matches = bindings.filter((binding) =>\n Keyboard.match(evt, binding),\n );\n if (matches.length === 0) return;\n // @ts-expect-error\n const blot = Quill.find(evt.target, true);\n if (blot && blot.scroll !== this.quill.scroll) return;\n const range = this.quill.getSelection();\n if (range == null || !this.quill.hasFocus()) return;\n const [line, offset] = this.quill.getLine(range.index);\n const [leafStart, offsetStart] = this.quill.getLeaf(range.index);\n const [leafEnd, offsetEnd] =\n range.length === 0\n ? [leafStart, offsetStart]\n : this.quill.getLeaf(range.index + range.length);\n const prefixText =\n leafStart instanceof TextBlot\n ? leafStart.value().slice(0, offsetStart)\n : '';\n const suffixText =\n leafEnd instanceof TextBlot ? leafEnd.value().slice(offsetEnd) : '';\n const curContext = {\n collapsed: range.length === 0,\n // @ts-expect-error Fix me later\n empty: range.length === 0 && line.length() <= 1,\n format: this.quill.getFormat(range),\n line,\n offset,\n prefix: prefixText,\n suffix: suffixText,\n event: evt,\n };\n const prevented = matches.some((binding) => {\n if (\n binding.collapsed != null &&\n binding.collapsed !== curContext.collapsed\n ) {\n return false;\n }\n if (binding.empty != null && binding.empty !== curContext.empty) {\n return false;\n }\n if (binding.offset != null && binding.offset !== curContext.offset) {\n return false;\n }\n if (Array.isArray(binding.format)) {\n // any format is present\n if (binding.format.every((name) => curContext.format[name] == null)) {\n return false;\n }\n } else if (typeof binding.format === 'object') {\n // all formats must match\n if (\n !Object.keys(binding.format).every((name) => {\n // @ts-expect-error Fix me later\n if (binding.format[name] === true)\n return curContext.format[name] != null;\n // @ts-expect-error Fix me later\n if (binding.format[name] === false)\n return curContext.format[name] == null;\n // @ts-expect-error Fix me later\n return isEqual(binding.format[name], curContext.format[name]);\n })\n ) {\n return false;\n }\n }\n if (binding.prefix != null && !binding.prefix.test(curContext.prefix)) {\n return false;\n }\n if (binding.suffix != null && !binding.suffix.test(curContext.suffix)) {\n return false;\n }\n // @ts-expect-error Fix me later\n return binding.handler.call(this, range, curContext, binding) !== true;\n });\n if (prevented) {\n evt.preventDefault();\n }\n });\n }\n\n handleBackspace(range: Range, context: Context) {\n // Check for astral symbols\n const length = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]$/.test(context.prefix)\n ? 2\n : 1;\n if (range.index === 0 || this.quill.getLength() <= 1) return;\n let formats = {};\n const [line] = this.quill.getLine(range.index);\n let delta = new Delta().retain(range.index - length).delete(length);\n if (context.offset === 0) {\n // Always deleting newline here, length always 1\n const [prev] = this.quill.getLine(range.index - 1);\n if (prev) {\n const isPrevLineEmpty =\n prev.statics.blotName === 'block' && prev.length() <= 1;\n if (!isPrevLineEmpty) {\n // @ts-expect-error Fix me later\n const curFormats = line.formats();\n const prevFormats = this.quill.getFormat(range.index - 1, 1);\n formats = AttributeMap.diff(curFormats, prevFormats) || {};\n if (Object.keys(formats).length > 0) {\n // line.length() - 1 targets \\n in line, another -1 for newline being deleted\n const formatDelta = new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index + line.length() - 2)\n .retain(1, formats);\n delta = delta.compose(formatDelta);\n }\n }\n }\n }\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.focus();\n }\n\n handleDelete(range: Range, context: Context) {\n // Check for astral symbols\n const length = /^[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/.test(context.suffix)\n ? 2\n : 1;\n if (range.index >= this.quill.getLength() - length) return;\n let formats = {};\n const [line] = this.quill.getLine(range.index);\n let delta = new Delta().retain(range.index).delete(length);\n // @ts-expect-error Fix me later\n if (context.offset >= line.length() - 1) {\n const [next] = this.quill.getLine(range.index + 1);\n if (next) {\n // @ts-expect-error Fix me later\n const curFormats = line.formats();\n const nextFormats = this.quill.getFormat(range.index, 1);\n formats = AttributeMap.diff(curFormats, nextFormats) || {};\n if (Object.keys(formats).length > 0) {\n delta = delta.retain(next.length() - 1).retain(1, formats);\n }\n }\n }\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.focus();\n }\n\n handleDeleteRange(range: Range) {\n deleteRange({ range, quill: this.quill });\n this.quill.focus();\n }\n\n handleEnter(range: Range, context: Context) {\n const lineFormats = Object.keys(context.format).reduce(\n (formats: Record, format) => {\n if (\n this.quill.scroll.query(format, Scope.BLOCK) &&\n !Array.isArray(context.format[format])\n ) {\n formats[format] = context.format[format];\n }\n return formats;\n },\n {},\n );\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .insert('\\n', lineFormats);\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.focus();\n }\n}\n\nconst defaultOptions: KeyboardOptions = {\n bindings: {\n bold: makeFormatHandler('bold'),\n italic: makeFormatHandler('italic'),\n underline: makeFormatHandler('underline'),\n indent: {\n // highlight tab or tab at beginning of list, indent or blockquote\n key: 'Tab',\n format: ['blockquote', 'indent', 'list'],\n handler(range, context) {\n if (context.collapsed && context.offset !== 0) return true;\n this.quill.format('indent', '+1', Quill.sources.USER);\n return false;\n },\n },\n outdent: {\n key: 'Tab',\n shiftKey: true,\n format: ['blockquote', 'indent', 'list'],\n // highlight tab or tab at beginning of list, indent or blockquote\n handler(range, context) {\n if (context.collapsed && context.offset !== 0) return true;\n this.quill.format('indent', '-1', Quill.sources.USER);\n return false;\n },\n },\n 'outdent backspace': {\n key: 'Backspace',\n collapsed: true,\n shiftKey: null,\n metaKey: null,\n ctrlKey: null,\n altKey: null,\n format: ['indent', 'list'],\n offset: 0,\n handler(range, context) {\n if (context.format.indent != null) {\n this.quill.format('indent', '-1', Quill.sources.USER);\n } else if (context.format.list != null) {\n this.quill.format('list', false, Quill.sources.USER);\n }\n },\n },\n 'indent code-block': makeCodeBlockHandler(true),\n 'outdent code-block': makeCodeBlockHandler(false),\n 'remove tab': {\n key: 'Tab',\n shiftKey: true,\n collapsed: true,\n prefix: /\\t$/,\n handler(range) {\n this.quill.deleteText(range.index - 1, 1, Quill.sources.USER);\n },\n },\n tab: {\n key: 'Tab',\n handler(range, context) {\n if (context.format.table) return true;\n this.quill.history.cutoff();\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .insert('\\t');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.history.cutoff();\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n return false;\n },\n },\n 'blockquote empty enter': {\n key: 'Enter',\n collapsed: true,\n format: ['blockquote'],\n empty: true,\n handler() {\n this.quill.format('blockquote', false, Quill.sources.USER);\n },\n },\n 'list empty enter': {\n key: 'Enter',\n collapsed: true,\n format: ['list'],\n empty: true,\n handler(range, context) {\n const formats: Record = { list: false };\n if (context.format.indent) {\n formats.indent = false;\n }\n this.quill.formatLine(\n range.index,\n range.length,\n formats,\n Quill.sources.USER,\n );\n },\n },\n 'checklist enter': {\n key: 'Enter',\n collapsed: true,\n format: { list: 'checked' },\n handler(range) {\n const [line, offset] = this.quill.getLine(range.index);\n const formats = {\n // @ts-expect-error Fix me later\n ...line.formats(),\n list: 'checked',\n };\n const delta = new Delta()\n .retain(range.index)\n .insert('\\n', formats)\n // @ts-expect-error Fix me later\n .retain(line.length() - offset - 1)\n .retain(1, { list: 'unchecked' });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.scrollSelectionIntoView();\n },\n },\n 'header enter': {\n key: 'Enter',\n collapsed: true,\n format: ['header'],\n suffix: /^$/,\n handler(range, context) {\n const [line, offset] = this.quill.getLine(range.index);\n const delta = new Delta()\n .retain(range.index)\n .insert('\\n', context.format)\n // @ts-expect-error Fix me later\n .retain(line.length() - offset - 1)\n .retain(1, { header: null });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.scrollSelectionIntoView();\n },\n },\n 'table backspace': {\n key: 'Backspace',\n format: ['table'],\n collapsed: true,\n offset: 0,\n handler() {},\n },\n 'table delete': {\n key: 'Delete',\n format: ['table'],\n collapsed: true,\n suffix: /^$/,\n handler() {},\n },\n 'table enter': {\n key: 'Enter',\n shiftKey: null,\n format: ['table'],\n handler(range) {\n const module = this.quill.getModule('table');\n if (module) {\n // @ts-expect-error\n const [table, row, cell, offset] = module.getTable(range);\n const shift = tableSide(table, row, cell, offset);\n if (shift == null) return;\n let index = table.offset();\n if (shift < 0) {\n const delta = new Delta().retain(index).insert('\\n');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(\n range.index + 1,\n range.length,\n Quill.sources.SILENT,\n );\n } else if (shift > 0) {\n index += table.length();\n const delta = new Delta().retain(index).insert('\\n');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(index, Quill.sources.USER);\n }\n }\n },\n },\n 'table tab': {\n key: 'Tab',\n shiftKey: null,\n format: ['table'],\n handler(range, context) {\n const { event, line: cell } = context;\n const offset = cell.offset(this.quill.scroll);\n if (event.shiftKey) {\n this.quill.setSelection(offset - 1, Quill.sources.USER);\n } else {\n this.quill.setSelection(offset + cell.length(), Quill.sources.USER);\n }\n },\n },\n 'list autofill': {\n key: ' ',\n shiftKey: null,\n collapsed: true,\n format: {\n 'code-block': false,\n blockquote: false,\n table: false,\n },\n prefix: /^\\s*?(\\d+\\.|-|\\*|\\[ ?\\]|\\[x\\])$/,\n handler(range, context) {\n if (this.quill.scroll.query('list') == null) return true;\n const { length } = context.prefix;\n const [line, offset] = this.quill.getLine(range.index);\n if (offset > length) return true;\n let value;\n switch (context.prefix.trim()) {\n case '[]':\n case '[ ]':\n value = 'unchecked';\n break;\n case '[x]':\n value = 'checked';\n break;\n case '-':\n case '*':\n value = 'bullet';\n break;\n default:\n value = 'ordered';\n }\n this.quill.insertText(range.index, ' ', Quill.sources.USER);\n this.quill.history.cutoff();\n const delta = new Delta()\n .retain(range.index - offset)\n .delete(length + 1)\n // @ts-expect-error Fix me later\n .retain(line.length() - 2 - offset)\n .retain(1, { list: value });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.history.cutoff();\n this.quill.setSelection(range.index - length, Quill.sources.SILENT);\n return false;\n },\n },\n 'code exit': {\n key: 'Enter',\n collapsed: true,\n format: ['code-block'],\n prefix: /^$/,\n suffix: /^\\s*$/,\n handler(range) {\n const [line, offset] = this.quill.getLine(range.index);\n let numLines = 2;\n let cur = line;\n while (\n cur != null &&\n cur.length() <= 1 &&\n cur.formats()['code-block']\n ) {\n // @ts-expect-error\n cur = cur.prev;\n numLines -= 1;\n // Requisite prev lines are empty\n if (numLines <= 0) {\n const delta = new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index + line.length() - offset - 2)\n .retain(1, { 'code-block': null })\n .delete(1);\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index - 1, Quill.sources.SILENT);\n return false;\n }\n }\n return true;\n },\n },\n 'embed left': makeEmbedArrowHandler('ArrowLeft', false),\n 'embed left shift': makeEmbedArrowHandler('ArrowLeft', true),\n 'embed right': makeEmbedArrowHandler('ArrowRight', false),\n 'embed right shift': makeEmbedArrowHandler('ArrowRight', true),\n 'table down': makeTableArrowHandler(false),\n 'table up': makeTableArrowHandler(true),\n },\n};\n\nKeyboard.DEFAULTS = defaultOptions;\n\nfunction makeCodeBlockHandler(indent: boolean): BindingObject {\n return {\n key: 'Tab',\n shiftKey: !indent,\n format: { 'code-block': true },\n handler(range, { event }) {\n const CodeBlock = this.quill.scroll.query('code-block');\n // @ts-expect-error\n const { TAB } = CodeBlock;\n if (range.length === 0 && !event.shiftKey) {\n this.quill.insertText(range.index, TAB, Quill.sources.USER);\n this.quill.setSelection(range.index + TAB.length, Quill.sources.SILENT);\n return;\n }\n\n const lines =\n range.length === 0\n ? this.quill.getLines(range.index, 1)\n : this.quill.getLines(range);\n let { index, length } = range;\n lines.forEach((line, i) => {\n if (indent) {\n line.insertAt(0, TAB);\n if (i === 0) {\n index += TAB.length;\n } else {\n length += TAB.length;\n }\n // @ts-expect-error Fix me later\n } else if (line.domNode.textContent.startsWith(TAB)) {\n line.deleteAt(0, TAB.length);\n if (i === 0) {\n index -= TAB.length;\n } else {\n length -= TAB.length;\n }\n }\n });\n this.quill.update(Quill.sources.USER);\n this.quill.setSelection(index, length, Quill.sources.SILENT);\n },\n };\n}\n\nfunction makeEmbedArrowHandler(\n key: string,\n shiftKey: boolean | null,\n): BindingObject {\n const where = key === 'ArrowLeft' ? 'prefix' : 'suffix';\n return {\n key,\n shiftKey,\n altKey: null,\n [where]: /^$/,\n handler(range) {\n let { index } = range;\n if (key === 'ArrowRight') {\n index += range.length + 1;\n }\n const [leaf] = this.quill.getLeaf(index);\n if (!(leaf instanceof EmbedBlot)) return true;\n if (key === 'ArrowLeft') {\n if (shiftKey) {\n this.quill.setSelection(\n range.index - 1,\n range.length + 1,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(range.index - 1, Quill.sources.USER);\n }\n } else if (shiftKey) {\n this.quill.setSelection(\n range.index,\n range.length + 1,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(\n range.index + range.length + 1,\n Quill.sources.USER,\n );\n }\n return false;\n },\n };\n}\n\nfunction makeFormatHandler(format: string): BindingObject {\n return {\n key: format[0],\n shortKey: true,\n handler(range, context) {\n this.quill.format(format, !context.format[format], Quill.sources.USER);\n },\n };\n}\n\nfunction makeTableArrowHandler(up: boolean): BindingObject {\n return {\n key: up ? 'ArrowUp' : 'ArrowDown',\n collapsed: true,\n format: ['table'],\n handler(range, context) {\n // TODO move to table module\n const key = up ? 'prev' : 'next';\n const cell = context.line;\n const targetRow = cell.parent[key];\n if (targetRow != null) {\n if (targetRow.statics.blotName === 'table-row') {\n // @ts-expect-error\n let targetCell = targetRow.children.head;\n let cur = cell;\n while (cur.prev != null) {\n // @ts-expect-error\n cur = cur.prev;\n targetCell = targetCell.next;\n }\n const index =\n targetCell.offset(this.quill.scroll) +\n Math.min(context.offset, targetCell.length() - 1);\n this.quill.setSelection(index, 0, Quill.sources.USER);\n }\n } else {\n // @ts-expect-error\n const targetLine = cell.table()[key];\n if (targetLine != null) {\n if (up) {\n this.quill.setSelection(\n targetLine.offset(this.quill.scroll) + targetLine.length() - 1,\n 0,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(\n targetLine.offset(this.quill.scroll),\n 0,\n Quill.sources.USER,\n );\n }\n }\n }\n return false;\n },\n };\n}\n\nfunction normalize(binding: Binding): BindingObject | null {\n if (typeof binding === 'string' || typeof binding === 'number') {\n binding = { key: binding };\n } else if (typeof binding === 'object') {\n binding = cloneDeep(binding);\n } else {\n return null;\n }\n if (binding.shortKey) {\n binding[SHORTKEY] = binding.shortKey;\n delete binding.shortKey;\n }\n return binding;\n}\n\n// TODO: Move into quill.ts or editor.ts\nfunction deleteRange({ quill, range }: { quill: Quill; range: Range }) {\n const lines = quill.getLines(range);\n let formats = {};\n if (lines.length > 1) {\n const firstFormats = lines[0].formats();\n const lastFormats = lines[lines.length - 1].formats();\n formats = AttributeMap.diff(lastFormats, firstFormats) || {};\n }\n quill.deleteText(range, Quill.sources.USER);\n if (Object.keys(formats).length > 0) {\n quill.formatLine(range.index, 1, formats, Quill.sources.USER);\n }\n quill.setSelection(range.index, Quill.sources.SILENT);\n}\n\nfunction tableSide(_table: unknown, row: Blot, cell: Blot, offset: number) {\n if (row.prev == null && row.next == null) {\n if (cell.prev == null && cell.next == null) {\n return offset === 0 ? -1 : 1;\n }\n return cell.prev == null ? -1 : 1;\n }\n if (row.prev == null) {\n return -1;\n }\n if (row.next == null) {\n return 1;\n }\n return null;\n}\n\nexport { Keyboard as default, SHORTKEY, normalize, deleteRange };\n", "const normalWeightRegexp = /font-weight:\\s*normal/;\nconst blockTagNames = ['P', 'OL', 'UL'];\n\nconst isBlockElement = (element: Element | null) => {\n return element && blockTagNames.includes(element.tagName);\n};\n\nconst normalizeEmptyLines = (doc: Document) => {\n Array.from(doc.querySelectorAll('br'))\n .filter(\n (br) =>\n isBlockElement(br.previousElementSibling) &&\n isBlockElement(br.nextElementSibling),\n )\n .forEach((br) => {\n br.parentNode?.removeChild(br);\n });\n};\n\nconst normalizeFontWeight = (doc: Document) => {\n Array.from(doc.querySelectorAll('b[style*=\"font-weight\"]'))\n .filter((node) => node.getAttribute('style')?.match(normalWeightRegexp))\n .forEach((node) => {\n const fragment = doc.createDocumentFragment();\n fragment.append(...node.childNodes);\n node.parentNode?.replaceChild(fragment, node);\n });\n};\n\nexport default function normalize(doc: Document) {\n if (doc.querySelector('[id^=\"docs-internal-guid-\"]')) {\n normalizeFontWeight(doc);\n normalizeEmptyLines(doc);\n }\n}\n", "const ignoreRegexp = /\\bmso-list:[^;]*ignore/i;\nconst idRegexp = /\\bmso-list:[^;]*\\bl(\\d+)/i;\nconst indentRegexp = /\\bmso-list:[^;]*\\blevel(\\d+)/i;\n\nconst parseListItem = (element: Element, html: string) => {\n const style = element.getAttribute('style');\n const idMatch = style?.match(idRegexp);\n if (!idMatch) {\n return null;\n }\n const id = Number(idMatch[1]);\n\n const indentMatch = style?.match(indentRegexp);\n const indent = indentMatch ? Number(indentMatch[1]) : 1;\n\n const typeRegexp = new RegExp(\n `@list l${id}:level${indent}\\\\s*\\\\{[^\\\\}]*mso-level-number-format:\\\\s*([\\\\w-]+)`,\n 'i',\n );\n const typeMatch = html.match(typeRegexp);\n const type = typeMatch && typeMatch[1] === 'bullet' ? 'bullet' : 'ordered';\n\n return { id, indent, type, element };\n};\n\n// list items are represented as `p` tags with styles like `mso-list: l0 level1` where:\n// 1. \"0\" in \"l0\" means the list item id;\n// 2. \"1\" in \"level1\" means the indent level, starting from 1.\nconst normalizeListItem = (doc: Document) => {\n const msoList = Array.from(doc.querySelectorAll('[style*=mso-list]'));\n const ignored: Element[] = [];\n const others: Element[] = [];\n msoList.forEach((node) => {\n const shouldIgnore = (node.getAttribute('style') || '').match(ignoreRegexp);\n if (shouldIgnore) {\n ignored.push(node);\n } else {\n others.push(node);\n }\n });\n\n // Each list item contains a marker wrapped with \"mso-list: Ignore\".\n ignored.forEach((node) => node.parentNode?.removeChild(node));\n\n // The list stype is not defined inline with the tag, instead, it's in the\n // style tag so we need to pass the html as a string.\n const html = doc.documentElement.innerHTML;\n const listItems = others\n .map((element) => parseListItem(element, html))\n .filter((parsed) => parsed);\n\n while (listItems.length) {\n const childListItems = [];\n\n let current = listItems.shift();\n // Group continuous items into the same group (aka \"ul\")\n while (current) {\n childListItems.push(current);\n current =\n listItems.length &&\n listItems[0]?.element === current.element.nextElementSibling &&\n // Different id means the next item doesn't belong to this group.\n listItems[0].id === current.id\n ? listItems.shift()\n : null;\n }\n\n const ul = document.createElement('ul');\n childListItems.forEach((listItem) => {\n const li = document.createElement('li');\n li.setAttribute('data-list', listItem.type);\n if (listItem.indent > 1) {\n li.setAttribute('class', `ql-indent-${listItem.indent - 1}`);\n }\n li.innerHTML = listItem.element.innerHTML;\n ul.appendChild(li);\n });\n\n const element = childListItems[0]?.element;\n const { parentNode } = element ?? {};\n if (element) {\n parentNode?.replaceChild(ul, element);\n }\n childListItems.slice(1).forEach(({ element: e }) => {\n parentNode?.removeChild(e);\n });\n }\n};\n\nexport default function normalize(doc: Document) {\n if (\n doc.documentElement.getAttribute('xmlns:w') ===\n 'urn:schemas-microsoft-com:office:word'\n ) {\n normalizeListItem(doc);\n }\n}\n", "import googleDocs from './normalizers/googleDocs.js';\nimport msWord from './normalizers/msWord.js';\n\nconst NORMALIZERS = [msWord, googleDocs];\n\nconst normalizeExternalHTML = (doc: Document) => {\n if (doc.documentElement) {\n NORMALIZERS.forEach((normalize) => {\n normalize(doc);\n });\n }\n};\n\nexport default normalizeExternalHTML;\n", "import type { ScrollBlot } from 'parchment';\nimport {\n Attributor,\n BlockBlot,\n ClassAttributor,\n EmbedBlot,\n Scope,\n StyleAttributor,\n} from 'parchment';\nimport Delta from 'quill-delta';\nimport { BlockEmbed } from '../blots/block.js';\nimport type { EmitterSource } from '../core/emitter.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type { Range } from '../core/selection.js';\nimport { AlignAttribute, AlignStyle } from '../formats/align.js';\nimport { BackgroundStyle } from '../formats/background.js';\nimport CodeBlock from '../formats/code.js';\nimport { ColorStyle } from '../formats/color.js';\nimport { DirectionAttribute, DirectionStyle } from '../formats/direction.js';\nimport { FontStyle } from '../formats/font.js';\nimport { SizeStyle } from '../formats/size.js';\nimport { deleteRange } from './keyboard.js';\nimport normalizeExternalHTML from './normalizeExternalHTML/index.js';\n\nconst debug = logger('quill:clipboard');\n\ntype Selector = string | Node['TEXT_NODE'] | Node['ELEMENT_NODE'];\ntype Matcher = (node: Node, delta: Delta, scroll: ScrollBlot) => Delta;\n\nconst CLIPBOARD_CONFIG: [Selector, Matcher][] = [\n [Node.TEXT_NODE, matchText],\n [Node.TEXT_NODE, matchNewline],\n ['br', matchBreak],\n [Node.ELEMENT_NODE, matchNewline],\n [Node.ELEMENT_NODE, matchBlot],\n [Node.ELEMENT_NODE, matchAttributor],\n [Node.ELEMENT_NODE, matchStyles],\n ['li', matchIndent],\n ['ol, ul', matchList],\n ['pre', matchCodeBlock],\n ['tr', matchTable],\n ['b', createMatchAlias('bold')],\n ['i', createMatchAlias('italic')],\n ['strike', createMatchAlias('strike')],\n ['style', matchIgnore],\n];\n\nconst ATTRIBUTE_ATTRIBUTORS = [AlignAttribute, DirectionAttribute].reduce(\n (memo: Record, attr) => {\n memo[attr.keyName] = attr;\n return memo;\n },\n {},\n);\n\nconst STYLE_ATTRIBUTORS = [\n AlignStyle,\n BackgroundStyle,\n ColorStyle,\n DirectionStyle,\n FontStyle,\n SizeStyle,\n].reduce((memo: Record, attr) => {\n memo[attr.keyName] = attr;\n return memo;\n}, {});\n\ninterface ClipboardOptions {\n matchers: [Selector, Matcher][];\n}\n\nclass Clipboard extends Module {\n static DEFAULTS: ClipboardOptions = {\n matchers: [],\n };\n\n matchers: [Selector, Matcher][];\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.quill.root.addEventListener('copy', (e) =>\n this.onCaptureCopy(e, false),\n );\n this.quill.root.addEventListener('cut', (e) => this.onCaptureCopy(e, true));\n this.quill.root.addEventListener('paste', this.onCapturePaste.bind(this));\n this.matchers = [];\n CLIPBOARD_CONFIG.concat(this.options.matchers ?? []).forEach(\n ([selector, matcher]) => {\n this.addMatcher(selector, matcher);\n },\n );\n }\n\n addMatcher(selector: Selector, matcher: Matcher) {\n this.matchers.push([selector, matcher]);\n }\n\n convert(\n { html, text }: { html?: string; text?: string },\n formats: Record = {},\n ) {\n if (formats[CodeBlock.blotName]) {\n return new Delta().insert(text || '', {\n [CodeBlock.blotName]: formats[CodeBlock.blotName],\n });\n }\n if (!html) {\n return new Delta().insert(text || '', formats);\n }\n const delta = this.convertHTML(html);\n // Remove trailing newline\n if (\n deltaEndsWith(delta, '\\n') &&\n (delta.ops[delta.ops.length - 1].attributes == null || formats.table)\n ) {\n return delta.compose(new Delta().retain(delta.length() - 1).delete(1));\n }\n return delta;\n }\n\n protected normalizeHTML(doc: Document) {\n normalizeExternalHTML(doc);\n }\n\n protected convertHTML(html: string) {\n const doc = new DOMParser().parseFromString(html, 'text/html');\n this.normalizeHTML(doc);\n const container = doc.body;\n const nodeMatches = new WeakMap();\n const [elementMatchers, textMatchers] = this.prepareMatching(\n container,\n nodeMatches,\n );\n return traverse(\n this.quill.scroll,\n container,\n elementMatchers,\n textMatchers,\n nodeMatches,\n );\n }\n\n dangerouslyPasteHTML(html: string, source?: EmitterSource): void;\n dangerouslyPasteHTML(\n index: number,\n html: string,\n source?: EmitterSource,\n ): void;\n dangerouslyPasteHTML(\n index: number | string,\n html?: string,\n source: EmitterSource = Quill.sources.API,\n ) {\n if (typeof index === 'string') {\n const delta = this.convert({ html: index, text: '' });\n // @ts-expect-error\n this.quill.setContents(delta, html);\n this.quill.setSelection(0, Quill.sources.SILENT);\n } else {\n const paste = this.convert({ html, text: '' });\n this.quill.updateContents(\n new Delta().retain(index).concat(paste),\n source,\n );\n this.quill.setSelection(index + paste.length(), Quill.sources.SILENT);\n }\n }\n\n onCaptureCopy(e: ClipboardEvent, isCut = false) {\n if (e.defaultPrevented) return;\n e.preventDefault();\n const [range] = this.quill.selection.getRange();\n if (range == null) return;\n const { html, text } = this.onCopy(range, isCut);\n e.clipboardData?.setData('text/plain', text);\n e.clipboardData?.setData('text/html', html);\n if (isCut) {\n deleteRange({ range, quill: this.quill });\n }\n }\n\n /*\n * https://www.iana.org/assignments/media-types/text/uri-list\n */\n private normalizeURIList(urlList: string) {\n return (\n urlList\n .split(/\\r?\\n/)\n // Ignore all comments\n .filter((url) => url[0] !== '#')\n .join('\\n')\n );\n }\n\n onCapturePaste(e: ClipboardEvent) {\n if (e.defaultPrevented || !this.quill.isEnabled()) return;\n e.preventDefault();\n const range = this.quill.getSelection(true);\n if (range == null) return;\n const html = e.clipboardData?.getData('text/html');\n let text = e.clipboardData?.getData('text/plain');\n if (!html && !text) {\n const urlList = e.clipboardData?.getData('text/uri-list');\n if (urlList) {\n text = this.normalizeURIList(urlList);\n }\n }\n const files = Array.from(e.clipboardData?.files || []);\n if (!html && files.length > 0) {\n this.quill.uploader.upload(range, files);\n return;\n }\n if (html && files.length > 0) {\n const doc = new DOMParser().parseFromString(html, 'text/html');\n if (\n doc.body.childElementCount === 1 &&\n doc.body.firstElementChild?.tagName === 'IMG'\n ) {\n this.quill.uploader.upload(range, files);\n return;\n }\n }\n this.onPaste(range, { html, text });\n }\n\n onCopy(range: Range, isCut: boolean): { html: string; text: string };\n onCopy(range: Range) {\n const text = this.quill.getText(range);\n const html = this.quill.getSemanticHTML(range);\n return { html, text };\n }\n\n onPaste(range: Range, { text, html }: { text?: string; html?: string }) {\n const formats = this.quill.getFormat(range.index);\n const pastedDelta = this.convert({ text, html }, formats);\n debug.log('onPaste', pastedDelta, { text, html });\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .concat(pastedDelta);\n this.quill.updateContents(delta, Quill.sources.USER);\n // range.length contributes to delta.length()\n this.quill.setSelection(\n delta.length() - range.length,\n Quill.sources.SILENT,\n );\n this.quill.scrollSelectionIntoView();\n }\n\n prepareMatching(container: Element, nodeMatches: WeakMap) {\n const elementMatchers: Matcher[] = [];\n const textMatchers: Matcher[] = [];\n this.matchers.forEach((pair) => {\n const [selector, matcher] = pair;\n switch (selector) {\n case Node.TEXT_NODE:\n textMatchers.push(matcher);\n break;\n case Node.ELEMENT_NODE:\n elementMatchers.push(matcher);\n break;\n default:\n Array.from(container.querySelectorAll(selector)).forEach((node) => {\n if (nodeMatches.has(node)) {\n const matches = nodeMatches.get(node);\n matches?.push(matcher);\n } else {\n nodeMatches.set(node, [matcher]);\n }\n });\n break;\n }\n });\n return [elementMatchers, textMatchers];\n }\n}\n\nfunction applyFormat(\n delta: Delta,\n format: string,\n value: unknown,\n scroll: ScrollBlot,\n): Delta {\n if (!scroll.query(format)) {\n return delta;\n }\n\n return delta.reduce((newDelta, op) => {\n if (!op.insert) return newDelta;\n if (op.attributes && op.attributes[format]) {\n return newDelta.push(op);\n }\n const formats = value ? { [format]: value } : {};\n return newDelta.insert(op.insert, { ...formats, ...op.attributes });\n }, new Delta());\n}\n\nfunction deltaEndsWith(delta: Delta, text: string) {\n let endText = '';\n for (\n let i = delta.ops.length - 1;\n i >= 0 && endText.length < text.length;\n --i // eslint-disable-line no-plusplus\n ) {\n const op = delta.ops[i];\n if (typeof op.insert !== 'string') break;\n endText = op.insert + endText;\n }\n return endText.slice(-1 * text.length) === text;\n}\n\nfunction isLine(node: Node, scroll: ScrollBlot) {\n if (!(node instanceof Element)) return false;\n const match = scroll.query(node);\n // @ts-expect-error\n if (match && match.prototype instanceof EmbedBlot) return false;\n\n return [\n 'address',\n 'article',\n 'blockquote',\n 'canvas',\n 'dd',\n 'div',\n 'dl',\n 'dt',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'iframe',\n 'li',\n 'main',\n 'nav',\n 'ol',\n 'output',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'td',\n 'tr',\n 'ul',\n 'video',\n ].includes(node.tagName.toLowerCase());\n}\n\nfunction isBetweenInlineElements(node: HTMLElement, scroll: ScrollBlot) {\n return (\n node.previousElementSibling &&\n node.nextElementSibling &&\n !isLine(node.previousElementSibling, scroll) &&\n !isLine(node.nextElementSibling, scroll)\n );\n}\n\nconst preNodes = new WeakMap();\nfunction isPre(node: Node | null) {\n if (node == null) return false;\n if (!preNodes.has(node)) {\n // @ts-expect-error\n if (node.tagName === 'PRE') {\n preNodes.set(node, true);\n } else {\n preNodes.set(node, isPre(node.parentNode));\n }\n }\n return preNodes.get(node);\n}\n\nfunction traverse(\n scroll: ScrollBlot,\n node: ChildNode,\n elementMatchers: Matcher[],\n textMatchers: Matcher[],\n nodeMatches: WeakMap,\n): Delta {\n // Post-order\n if (node.nodeType === node.TEXT_NODE) {\n return textMatchers.reduce((delta: Delta, matcher) => {\n return matcher(node, delta, scroll);\n }, new Delta());\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n return Array.from(node.childNodes || []).reduce((delta, childNode) => {\n let childrenDelta = traverse(\n scroll,\n childNode,\n elementMatchers,\n textMatchers,\n nodeMatches,\n );\n if (childNode.nodeType === node.ELEMENT_NODE) {\n childrenDelta = elementMatchers.reduce((reducedDelta, matcher) => {\n return matcher(childNode as HTMLElement, reducedDelta, scroll);\n }, childrenDelta);\n childrenDelta = (nodeMatches.get(childNode) || []).reduce(\n (reducedDelta, matcher) => {\n return matcher(childNode, reducedDelta, scroll);\n },\n childrenDelta,\n );\n }\n return delta.concat(childrenDelta);\n }, new Delta());\n }\n return new Delta();\n}\n\nfunction createMatchAlias(format: string) {\n return (_node: Element, delta: Delta, scroll: ScrollBlot) => {\n return applyFormat(delta, format, true, scroll);\n };\n}\n\nfunction matchAttributor(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n const attributes = Attributor.keys(node);\n const classes = ClassAttributor.keys(node);\n const styles = StyleAttributor.keys(node);\n const formats: Record = {};\n attributes\n .concat(classes)\n .concat(styles)\n .forEach((name) => {\n let attr = scroll.query(name, Scope.ATTRIBUTE) as Attributor;\n if (attr != null) {\n formats[attr.attrName] = attr.value(node);\n if (formats[attr.attrName]) return;\n }\n attr = ATTRIBUTE_ATTRIBUTORS[name];\n if (attr != null && (attr.attrName === name || attr.keyName === name)) {\n formats[attr.attrName] = attr.value(node) || undefined;\n }\n attr = STYLE_ATTRIBUTORS[name];\n if (attr != null && (attr.attrName === name || attr.keyName === name)) {\n attr = STYLE_ATTRIBUTORS[name];\n formats[attr.attrName] = attr.value(node) || undefined;\n }\n });\n\n return Object.entries(formats).reduce(\n (newDelta, [name, value]) => applyFormat(newDelta, name, value, scroll),\n delta,\n );\n}\n\nfunction matchBlot(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query(node);\n if (match == null) return delta;\n // @ts-expect-error\n if (match.prototype instanceof EmbedBlot) {\n const embed = {};\n // @ts-expect-error\n const value = match.value(node);\n if (value != null) {\n // @ts-expect-error\n embed[match.blotName] = value;\n // @ts-expect-error\n return new Delta().insert(embed, match.formats(node, scroll));\n }\n } else {\n // @ts-expect-error\n if (match.prototype instanceof BlockBlot && !deltaEndsWith(delta, '\\n')) {\n delta.insert('\\n');\n }\n if (\n 'blotName' in match &&\n 'formats' in match &&\n typeof match.formats === 'function'\n ) {\n return applyFormat(\n delta,\n match.blotName,\n match.formats(node, scroll),\n scroll,\n );\n }\n }\n return delta;\n}\n\nfunction matchBreak(node: Node, delta: Delta) {\n if (!deltaEndsWith(delta, '\\n')) {\n delta.insert('\\n');\n }\n return delta;\n}\n\nfunction matchCodeBlock(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query('code-block');\n const language =\n match && 'formats' in match && typeof match.formats === 'function'\n ? match.formats(node, scroll)\n : true;\n return applyFormat(delta, 'code-block', language, scroll);\n}\n\nfunction matchIgnore() {\n return new Delta();\n}\n\nfunction matchIndent(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query(node);\n if (\n match == null ||\n // @ts-expect-error\n match.blotName !== 'list' ||\n !deltaEndsWith(delta, '\\n')\n ) {\n return delta;\n }\n let indent = -1;\n let parent = node.parentNode;\n while (parent != null) {\n // @ts-expect-error\n if (['OL', 'UL'].includes(parent.tagName)) {\n indent += 1;\n }\n parent = parent.parentNode;\n }\n if (indent <= 0) return delta;\n return delta.reduce((composed, op) => {\n if (!op.insert) return composed;\n if (op.attributes && typeof op.attributes.indent === 'number') {\n return composed.push(op);\n }\n return composed.insert(op.insert, { indent, ...(op.attributes || {}) });\n }, new Delta());\n}\n\nfunction matchList(node: Node, delta: Delta, scroll: ScrollBlot) {\n const element = node as Element;\n let list = element.tagName === 'OL' ? 'ordered' : 'bullet';\n\n const checkedAttr = element.getAttribute('data-checked');\n if (checkedAttr) {\n list = checkedAttr === 'true' ? 'checked' : 'unchecked';\n }\n\n return applyFormat(delta, 'list', list, scroll);\n}\n\nfunction matchNewline(node: Node, delta: Delta, scroll: ScrollBlot) {\n if (!deltaEndsWith(delta, '\\n')) {\n if (\n isLine(node, scroll) &&\n (node.childNodes.length > 0 || node instanceof HTMLParagraphElement)\n ) {\n return delta.insert('\\n');\n }\n if (delta.length() > 0 && node.nextSibling) {\n let nextSibling: Node | null = node.nextSibling;\n while (nextSibling != null) {\n if (isLine(nextSibling, scroll)) {\n return delta.insert('\\n');\n }\n const match = scroll.query(nextSibling);\n // @ts-expect-error\n if (match && match.prototype instanceof BlockEmbed) {\n return delta.insert('\\n');\n }\n nextSibling = nextSibling.firstChild;\n }\n }\n }\n return delta;\n}\n\nfunction matchStyles(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n const formats: Record = {};\n const style: Partial = node.style || {};\n if (style.fontStyle === 'italic') {\n formats.italic = true;\n }\n if (style.textDecoration === 'underline') {\n formats.underline = true;\n }\n if (style.textDecoration === 'line-through') {\n formats.strike = true;\n }\n if (\n style.fontWeight?.startsWith('bold') ||\n // @ts-expect-error Fix me later\n parseInt(style.fontWeight, 10) >= 700\n ) {\n formats.bold = true;\n }\n delta = Object.entries(formats).reduce(\n (newDelta, [name, value]) => applyFormat(newDelta, name, value, scroll),\n delta,\n );\n // @ts-expect-error\n if (parseFloat(style.textIndent || 0) > 0) {\n // Could be 0.5in\n return new Delta().insert('\\t').concat(delta);\n }\n return delta;\n}\n\nfunction matchTable(\n node: HTMLTableRowElement,\n delta: Delta,\n scroll: ScrollBlot,\n) {\n const table =\n node.parentElement?.tagName === 'TABLE'\n ? node.parentElement\n : node.parentElement?.parentElement;\n if (table != null) {\n const rows = Array.from(table.querySelectorAll('tr'));\n const row = rows.indexOf(node) + 1;\n return applyFormat(delta, 'table', row, scroll);\n }\n return delta;\n}\n\nfunction matchText(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n // @ts-expect-error\n let text = node.data;\n // Word represents empty line with  \n if (node.parentElement?.tagName === 'O:P') {\n return delta.insert(text.trim());\n }\n if (!isPre(node)) {\n if (\n text.trim().length === 0 &&\n text.includes('\\n') &&\n !isBetweenInlineElements(node, scroll)\n ) {\n return delta;\n }\n const replacer = (collapse: unknown, match: string) => {\n const replaced = match.replace(/[^\\u00a0]/g, ''); // \\u00a0 is nbsp;\n return replaced.length < 1 && collapse ? ' ' : replaced;\n };\n text = text.replace(/\\r\\n/g, ' ').replace(/\\n/g, ' ');\n text = text.replace(/\\s\\s+/g, replacer.bind(replacer, true)); // collapse whitespace\n if (\n (node.previousSibling == null &&\n node.parentElement != null &&\n isLine(node.parentElement, scroll)) ||\n (node.previousSibling instanceof Element &&\n isLine(node.previousSibling, scroll))\n ) {\n text = text.replace(/^\\s+/, replacer.bind(replacer, false));\n }\n if (\n (node.nextSibling == null &&\n node.parentElement != null &&\n isLine(node.parentElement, scroll)) ||\n (node.nextSibling instanceof Element && isLine(node.nextSibling, scroll))\n ) {\n text = text.replace(/\\s+$/, replacer.bind(replacer, false));\n }\n }\n return delta.insert(text);\n}\n\nexport {\n Clipboard as default,\n matchAttributor,\n matchBlot,\n matchNewline,\n matchText,\n traverse,\n};\n", "import { Scope } from 'parchment';\nimport type Delta from 'quill-delta';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type Scroll from '../blots/scroll.js';\nimport type { Range } from '../core/selection.js';\n\nexport interface HistoryOptions {\n userOnly: boolean;\n delay: number;\n maxStack: number;\n}\n\nexport interface StackItem {\n delta: Delta;\n range: Range | null;\n}\n\ninterface Stack {\n undo: StackItem[];\n redo: StackItem[];\n}\n\nclass History extends Module {\n static DEFAULTS: HistoryOptions = {\n delay: 1000,\n maxStack: 100,\n userOnly: false,\n };\n\n lastRecorded = 0;\n ignoreChange = false;\n stack: Stack = { undo: [], redo: [] };\n currentRange: Range | null = null;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.quill.on(\n Quill.events.EDITOR_CHANGE,\n (eventName, value, oldValue, source) => {\n if (eventName === Quill.events.SELECTION_CHANGE) {\n if (value && source !== Quill.sources.SILENT) {\n this.currentRange = value;\n }\n } else if (eventName === Quill.events.TEXT_CHANGE) {\n if (!this.ignoreChange) {\n if (!this.options.userOnly || source === Quill.sources.USER) {\n this.record(value, oldValue);\n } else {\n this.transform(value);\n }\n }\n\n this.currentRange = transformRange(this.currentRange, value);\n }\n },\n );\n\n this.quill.keyboard.addBinding(\n { key: 'z', shortKey: true },\n this.undo.bind(this),\n );\n this.quill.keyboard.addBinding(\n { key: ['z', 'Z'], shortKey: true, shiftKey: true },\n this.redo.bind(this),\n );\n if (/Win/i.test(navigator.platform)) {\n this.quill.keyboard.addBinding(\n { key: 'y', shortKey: true },\n this.redo.bind(this),\n );\n }\n\n this.quill.root.addEventListener('beforeinput', (event) => {\n if (event.inputType === 'historyUndo') {\n this.undo();\n event.preventDefault();\n } else if (event.inputType === 'historyRedo') {\n this.redo();\n event.preventDefault();\n }\n });\n }\n\n change(source: 'undo' | 'redo', dest: 'redo' | 'undo') {\n if (this.stack[source].length === 0) return;\n const item = this.stack[source].pop();\n if (!item) return;\n const base = this.quill.getContents();\n const inverseDelta = item.delta.invert(base);\n this.stack[dest].push({\n delta: inverseDelta,\n range: transformRange(item.range, inverseDelta),\n });\n this.lastRecorded = 0;\n this.ignoreChange = true;\n this.quill.updateContents(item.delta, Quill.sources.USER);\n this.ignoreChange = false;\n\n this.restoreSelection(item);\n }\n\n clear() {\n this.stack = { undo: [], redo: [] };\n }\n\n cutoff() {\n this.lastRecorded = 0;\n }\n\n record(changeDelta: Delta, oldDelta: Delta) {\n if (changeDelta.ops.length === 0) return;\n this.stack.redo = [];\n let undoDelta = changeDelta.invert(oldDelta);\n let undoRange = this.currentRange;\n const timestamp = Date.now();\n if (\n // @ts-expect-error Fix me later\n this.lastRecorded + this.options.delay > timestamp &&\n this.stack.undo.length > 0\n ) {\n const item = this.stack.undo.pop();\n if (item) {\n undoDelta = undoDelta.compose(item.delta);\n undoRange = item.range;\n }\n } else {\n this.lastRecorded = timestamp;\n }\n if (undoDelta.length() === 0) return;\n this.stack.undo.push({ delta: undoDelta, range: undoRange });\n // @ts-expect-error Fix me later\n if (this.stack.undo.length > this.options.maxStack) {\n this.stack.undo.shift();\n }\n }\n\n redo() {\n this.change('redo', 'undo');\n }\n\n transform(delta: Delta) {\n transformStack(this.stack.undo, delta);\n transformStack(this.stack.redo, delta);\n }\n\n undo() {\n this.change('undo', 'redo');\n }\n\n protected restoreSelection(stackItem: StackItem) {\n if (stackItem.range) {\n this.quill.setSelection(stackItem.range, Quill.sources.USER);\n } else {\n const index = getLastChangeIndex(this.quill.scroll, stackItem.delta);\n this.quill.setSelection(index, Quill.sources.USER);\n }\n }\n}\n\nfunction transformStack(stack: StackItem[], delta: Delta) {\n let remoteDelta = delta;\n for (let i = stack.length - 1; i >= 0; i -= 1) {\n const oldItem = stack[i];\n stack[i] = {\n delta: remoteDelta.transform(oldItem.delta, true),\n range: oldItem.range && transformRange(oldItem.range, remoteDelta),\n };\n remoteDelta = oldItem.delta.transform(remoteDelta);\n if (stack[i].delta.length() === 0) {\n stack.splice(i, 1);\n }\n }\n}\n\nfunction endsWithNewlineChange(scroll: Scroll, delta: Delta) {\n const lastOp = delta.ops[delta.ops.length - 1];\n if (lastOp == null) return false;\n if (lastOp.insert != null) {\n return typeof lastOp.insert === 'string' && lastOp.insert.endsWith('\\n');\n }\n if (lastOp.attributes != null) {\n return Object.keys(lastOp.attributes).some((attr) => {\n return scroll.query(attr, Scope.BLOCK) != null;\n });\n }\n return false;\n}\n\nfunction getLastChangeIndex(scroll: Scroll, delta: Delta) {\n const deleteLength = delta.reduce((length, op) => {\n return length + (op.delete || 0);\n }, 0);\n let changeIndex = delta.length() - deleteLength;\n if (endsWithNewlineChange(scroll, delta)) {\n changeIndex -= 1;\n }\n return changeIndex;\n}\n\nfunction transformRange(range: Range | null, delta: Delta) {\n if (!range) return range;\n const start = delta.transformPosition(range.index);\n const end = delta.transformPosition(range.index + range.length);\n return { index: start, length: end - start };\n}\n\nexport { History as default, getLastChangeIndex };\n", "import Delta from 'quill-delta';\nimport type Quill from '../core/quill.js';\nimport Emitter from '../core/emitter.js';\nimport Module from '../core/module.js';\nimport type { Range } from '../core/selection.js';\n\ninterface UploaderOptions {\n mimetypes: string[];\n handler: (this: { quill: Quill }, range: Range, files: File[]) => void;\n}\n\nclass Uploader extends Module {\n static DEFAULTS: UploaderOptions;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n quill.root.addEventListener('drop', (e) => {\n e.preventDefault();\n let native: ReturnType | null = null;\n if (document.caretRangeFromPoint) {\n native = document.caretRangeFromPoint(e.clientX, e.clientY);\n // @ts-expect-error\n } else if (document.caretPositionFromPoint) {\n // @ts-expect-error\n const position = document.caretPositionFromPoint(e.clientX, e.clientY);\n native = document.createRange();\n native.setStart(position.offsetNode, position.offset);\n native.setEnd(position.offsetNode, position.offset);\n }\n\n const normalized = native && quill.selection.normalizeNative(native);\n if (normalized) {\n const range = quill.selection.normalizedToRange(normalized);\n if (e.dataTransfer?.files) {\n this.upload(range, e.dataTransfer.files);\n }\n }\n });\n }\n\n upload(range: Range, files: FileList | File[]) {\n const uploads: File[] = [];\n Array.from(files).forEach((file) => {\n if (file && this.options.mimetypes?.includes(file.type)) {\n uploads.push(file);\n }\n });\n if (uploads.length > 0) {\n // @ts-expect-error Fix me later\n this.options.handler.call(this, range, uploads);\n }\n }\n}\n\nUploader.DEFAULTS = {\n mimetypes: ['image/png', 'image/jpeg'],\n handler(range: Range, files: File[]) {\n if (!this.quill.scroll.query('image')) {\n return;\n }\n const promises = files.map>((file) => {\n return new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => {\n resolve(reader.result as string);\n };\n reader.readAsDataURL(file);\n });\n });\n Promise.all(promises).then((images) => {\n const update = images.reduce((delta: Delta, image) => {\n return delta.insert({ image });\n }, new Delta().retain(range.index).delete(range.length)) as Delta;\n this.quill.updateContents(update, Emitter.sources.USER);\n this.quill.setSelection(\n range.index + images.length,\n Emitter.sources.SILENT,\n );\n });\n },\n};\n\nexport default Uploader;\n", "import Delta from 'quill-delta';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type { Range } from '../core/selection.js';\nimport { deleteRange } from './keyboard.js';\n\nconst INSERT_TYPES = ['insertText', 'insertReplacementText'];\n\nclass Input extends Module {\n constructor(quill: Quill, options: Record) {\n super(quill, options);\n\n quill.root.addEventListener('beforeinput', (event) => {\n this.handleBeforeInput(event);\n });\n\n // Gboard with English input on Android triggers `compositionstart` sometimes even\n // users are not going to type anything.\n if (!/Android/i.test(navigator.userAgent)) {\n quill.on(Quill.events.COMPOSITION_BEFORE_START, () => {\n this.handleCompositionStart();\n });\n }\n }\n\n private deleteRange(range: Range) {\n deleteRange({ range, quill: this.quill });\n }\n\n private replaceText(range: Range, text = '') {\n if (range.length === 0) return false;\n\n if (text) {\n // Follow the native behavior that inherits the formats of the first character\n const formats = this.quill.getFormat(range.index, 1);\n this.deleteRange(range);\n this.quill.updateContents(\n new Delta().retain(range.index).insert(text, formats),\n Quill.sources.USER,\n );\n } else {\n this.deleteRange(range);\n }\n\n this.quill.setSelection(range.index + text.length, 0, Quill.sources.SILENT);\n return true;\n }\n\n private handleBeforeInput(event: InputEvent) {\n if (\n this.quill.composition.isComposing ||\n event.defaultPrevented ||\n !INSERT_TYPES.includes(event.inputType)\n ) {\n return;\n }\n\n const staticRange = event.getTargetRanges\n ? event.getTargetRanges()[0]\n : null;\n if (!staticRange || staticRange.collapsed === true) {\n return;\n }\n\n const text = getPlainTextFromInputEvent(event);\n if (text == null) {\n return;\n }\n const normalized = this.quill.selection.normalizeNative(staticRange);\n const range = normalized\n ? this.quill.selection.normalizedToRange(normalized)\n : null;\n if (range && this.replaceText(range, text)) {\n event.preventDefault();\n }\n }\n\n private handleCompositionStart() {\n const range = this.quill.getSelection();\n if (range) {\n this.replaceText(range);\n }\n }\n}\n\nfunction getPlainTextFromInputEvent(event: InputEvent) {\n // When `inputType` is \"insertText\":\n // - `event.data` should be string (Safari uses `event.dataTransfer`).\n // - `event.dataTransfer` should be null.\n // When `inputType` is \"insertReplacementText\":\n // - `event.data` should be null.\n // - `event.dataTransfer` should contain \"text/plain\" data.\n\n if (typeof event.data === 'string') {\n return event.data;\n }\n if (event.dataTransfer?.types.includes('text/plain')) {\n return event.dataTransfer.getData('text/plain');\n }\n return null;\n}\n\nexport default Input;\n", "import { ParentBlot } from 'parchment';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\n\nconst isMac = /Mac/i.test(navigator.platform);\n\n// Export for testing\nexport const TTL_FOR_VALID_SELECTION_CHANGE = 100;\n\n// A loose check to determine if the shortcut can move the caret before a UI node:\n// [CARET]
    [CONTENT]
    \nconst canMoveCaretBeforeUINode = (event: KeyboardEvent) => {\n if (\n event.key === 'ArrowLeft' ||\n event.key === 'ArrowRight' || // RTL scripts or moving from the end of the previous line\n event.key === 'ArrowUp' ||\n event.key === 'ArrowDown' ||\n event.key === 'Home'\n ) {\n return true;\n }\n\n if (isMac && event.key === 'a' && event.ctrlKey === true) {\n return true;\n }\n\n return false;\n};\n\nclass UINode extends Module {\n isListening = false;\n selectionChangeDeadline = 0;\n\n constructor(quill: Quill, options: Record) {\n super(quill, options);\n\n this.handleArrowKeys();\n this.handleNavigationShortcuts();\n }\n\n private handleArrowKeys() {\n this.quill.keyboard.addBinding({\n key: ['ArrowLeft', 'ArrowRight'],\n offset: 0,\n shiftKey: null,\n handler(range, { line, event }) {\n if (!(line instanceof ParentBlot) || !line.uiNode) {\n return true;\n }\n\n const isRTL = getComputedStyle(line.domNode)['direction'] === 'rtl';\n if (\n (isRTL && event.key !== 'ArrowRight') ||\n (!isRTL && event.key !== 'ArrowLeft')\n ) {\n return true;\n }\n\n this.quill.setSelection(\n range.index - 1,\n range.length + (event.shiftKey ? 1 : 0),\n Quill.sources.USER,\n );\n return false;\n },\n });\n }\n\n private handleNavigationShortcuts() {\n this.quill.root.addEventListener('keydown', (event) => {\n if (!event.defaultPrevented && canMoveCaretBeforeUINode(event)) {\n this.ensureListeningToSelectionChange();\n }\n });\n }\n\n /**\n * We only listen to the `selectionchange` event when\n * there is an intention of moving the caret to the beginning using shortcuts.\n * This is primarily implemented to prevent infinite loops, as we are changing\n * the selection within the handler of a `selectionchange` event.\n */\n private ensureListeningToSelectionChange() {\n this.selectionChangeDeadline = Date.now() + TTL_FOR_VALID_SELECTION_CHANGE;\n\n if (this.isListening) return;\n this.isListening = true;\n\n const listener = () => {\n this.isListening = false;\n\n if (Date.now() <= this.selectionChangeDeadline) {\n this.handleSelectionChange();\n }\n };\n\n document.addEventListener('selectionchange', listener, {\n once: true,\n });\n }\n\n private handleSelectionChange() {\n const selection = document.getSelection();\n if (!selection) return;\n const range = selection.getRangeAt(0);\n if (range.collapsed !== true || range.startOffset !== 0) return;\n\n const line = this.quill.scroll.find(range.startContainer);\n if (!(line instanceof ParentBlot) || !line.uiNode) return;\n\n const newRange = document.createRange();\n newRange.setStartAfter(line.uiNode);\n newRange.setEndAfter(line.uiNode);\n selection.removeAllRanges();\n selection.addRange(newRange);\n }\n}\n\nexport default UINode;\n", "import Quill, { Parchment, Range } from './core/quill.js';\nimport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n} from './core/quill.js';\n\nimport Block, { BlockEmbed } from './blots/block.js';\nimport Break from './blots/break.js';\nimport Container from './blots/container.js';\nimport Cursor from './blots/cursor.js';\nimport Embed from './blots/embed.js';\nimport Inline from './blots/inline.js';\nimport Scroll from './blots/scroll.js';\nimport TextBlot from './blots/text.js';\n\nimport Clipboard from './modules/clipboard.js';\nimport History from './modules/history.js';\nimport Keyboard from './modules/keyboard.js';\nimport Uploader from './modules/uploader.js';\nimport Delta, { Op, OpIterator, AttributeMap } from 'quill-delta';\nimport Input from './modules/input.js';\nimport UINode from './modules/uiNode.js';\n\nexport { default as Module } from './core/module.js';\nexport { Delta, Op, OpIterator, AttributeMap, Parchment, Range };\nexport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n};\n\nQuill.register({\n 'blots/block': Block,\n 'blots/block/embed': BlockEmbed,\n 'blots/break': Break,\n 'blots/container': Container,\n 'blots/cursor': Cursor,\n 'blots/embed': Embed,\n 'blots/inline': Inline,\n 'blots/scroll': Scroll,\n 'blots/text': TextBlot,\n\n 'modules/clipboard': Clipboard,\n 'modules/history': History,\n 'modules/keyboard': Keyboard,\n 'modules/uploader': Uploader,\n 'modules/input': Input,\n 'modules/uiNode': UINode,\n});\n\nexport default Quill;\n", "import { ClassAttributor, Scope } from 'parchment';\n\nclass IndentAttributor extends ClassAttributor {\n add(node: HTMLElement, value: string | number) {\n let normalizedValue = 0;\n if (value === '+1' || value === '-1') {\n const indent = this.value(node) || 0;\n normalizedValue = value === '+1' ? indent + 1 : indent - 1;\n } else if (typeof value === 'number') {\n normalizedValue = value;\n }\n if (normalizedValue === 0) {\n this.remove(node);\n return true;\n }\n return super.add(node, normalizedValue.toString());\n }\n\n canAdd(node: HTMLElement, value: string) {\n return super.canAdd(node, value) || super.canAdd(node, parseInt(value, 10));\n }\n\n value(node: HTMLElement) {\n return parseInt(super.value(node), 10) || undefined; // Don't return NaN\n }\n}\n\nconst IndentClass = new IndentAttributor('indent', 'ql-indent', {\n scope: Scope.BLOCK,\n // @ts-expect-error\n whitelist: [1, 2, 3, 4, 5, 6, 7, 8],\n});\n\nexport default IndentClass;\n", "import Block from '../blots/block.js';\n\nclass Blockquote extends Block {\n static blotName = 'blockquote';\n static tagName = 'blockquote';\n}\n\nexport default Blockquote;\n", "import Block from '../blots/block.js';\n\nclass Header extends Block {\n static blotName = 'header';\n static tagName = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];\n\n static formats(domNode: Element) {\n return this.tagName.indexOf(domNode.tagName) + 1;\n }\n}\n\nexport default Header;\n", "import Block from '../blots/block.js';\nimport Container from '../blots/container.js';\nimport type Scroll from '../blots/scroll.js';\nimport Quill from '../core/quill.js';\n\nclass ListContainer extends Container {}\nListContainer.blotName = 'list-container';\nListContainer.tagName = 'OL';\n\nclass ListItem extends Block {\n static create(value: string) {\n const node = super.create() as HTMLElement;\n node.setAttribute('data-list', value);\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n return domNode.getAttribute('data-list') || undefined;\n }\n\n static register() {\n Quill.register(ListContainer);\n }\n\n constructor(scroll: Scroll, domNode: HTMLElement) {\n super(scroll, domNode);\n const ui = domNode.ownerDocument.createElement('span');\n const listEventHandler = (e: Event) => {\n if (!scroll.isEnabled()) return;\n const format = this.statics.formats(domNode, scroll);\n if (format === 'checked') {\n this.format('list', 'unchecked');\n e.preventDefault();\n } else if (format === 'unchecked') {\n this.format('list', 'checked');\n e.preventDefault();\n }\n };\n ui.addEventListener('mousedown', listEventHandler);\n ui.addEventListener('touchstart', listEventHandler);\n this.attachUI(ui);\n }\n\n format(name: string, value: string) {\n if (name === this.statics.blotName && value) {\n this.domNode.setAttribute('data-list', value);\n } else {\n super.format(name, value);\n }\n }\n}\nListItem.blotName = 'list';\nListItem.tagName = 'LI';\n\nListContainer.allowedChildren = [ListItem];\nListItem.requiredContainer = ListContainer;\n\nexport { ListContainer, ListItem as default };\n", "import Inline from '../blots/inline.js';\n\nclass Bold extends Inline {\n static blotName = 'bold';\n static tagName = ['STRONG', 'B'];\n\n static create() {\n return super.create();\n }\n\n static formats() {\n return true;\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n if (this.domNode.tagName !== this.statics.tagName[0]) {\n this.replaceWith(this.statics.blotName);\n }\n }\n}\n\nexport default Bold;\n", "import Bold from './bold.js';\n\nclass Italic extends Bold {\n static blotName = 'italic';\n static tagName = ['EM', 'I'];\n}\n\nexport default Italic;\n", "import Inline from '../blots/inline.js';\n\nclass Link extends Inline {\n static blotName = 'link';\n static tagName = 'A';\n static SANITIZED_URL = 'about:blank';\n static PROTOCOL_WHITELIST = ['http', 'https', 'mailto', 'tel', 'sms'];\n\n static create(value: string) {\n const node = super.create(value) as HTMLElement;\n node.setAttribute('href', this.sanitize(value));\n node.setAttribute('rel', 'noopener noreferrer');\n node.setAttribute('target', '_blank');\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n return domNode.getAttribute('href');\n }\n\n static sanitize(url: string) {\n return sanitize(url, this.PROTOCOL_WHITELIST) ? url : this.SANITIZED_URL;\n }\n\n format(name: string, value: unknown) {\n if (name !== this.statics.blotName || !value) {\n super.format(name, value);\n } else {\n // @ts-expect-error\n this.domNode.setAttribute('href', this.constructor.sanitize(value));\n }\n }\n}\n\nfunction sanitize(url: string, protocols: string[]) {\n const anchor = document.createElement('a');\n anchor.href = url;\n const protocol = anchor.href.slice(0, anchor.href.indexOf(':'));\n return protocols.indexOf(protocol) > -1;\n}\n\nexport { Link as default, sanitize };\n", "import Inline from '../blots/inline.js';\n\nclass Script extends Inline {\n static blotName = 'script';\n static tagName = ['SUB', 'SUP'];\n\n static create(value: 'super' | 'sub' | (string & {})) {\n if (value === 'super') {\n return document.createElement('sup');\n }\n if (value === 'sub') {\n return document.createElement('sub');\n }\n return super.create(value);\n }\n\n static formats(domNode: HTMLElement) {\n if (domNode.tagName === 'SUB') return 'sub';\n if (domNode.tagName === 'SUP') return 'super';\n return undefined;\n }\n}\n\nexport default Script;\n", "import Bold from './bold.js';\n\nclass Strike extends Bold {\n static blotName = 'strike';\n static tagName = ['S', 'STRIKE'];\n}\n\nexport default Strike;\n", "import Inline from '../blots/inline.js';\n\nclass Underline extends Inline {\n static blotName = 'underline';\n static tagName = 'U';\n}\n\nexport default Underline;\n", "import Embed from '../blots/embed.js';\n\nclass Formula extends Embed {\n static blotName = 'formula';\n static className = 'ql-formula';\n static tagName = 'SPAN';\n\n static create(value: string) {\n // @ts-expect-error\n if (window.katex == null) {\n throw new Error('Formula module requires KaTeX.');\n }\n const node = super.create(value) as Element;\n if (typeof value === 'string') {\n // @ts-expect-error\n window.katex.render(value, node, {\n throwOnError: false,\n errorColor: '#f00',\n });\n node.setAttribute('data-value', value);\n }\n return node;\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('data-value');\n }\n\n html() {\n const { formula } = this.value();\n return `${formula}`;\n }\n}\n\nexport default Formula;\n", "import { EmbedBlot } from 'parchment';\nimport { sanitize } from './link.js';\n\nconst ATTRIBUTES = ['alt', 'height', 'width'];\n\nclass Image extends EmbedBlot {\n static blotName = 'image';\n static tagName = 'IMG';\n\n static create(value: string) {\n const node = super.create(value) as Element;\n if (typeof value === 'string') {\n node.setAttribute('src', this.sanitize(value));\n }\n return node;\n }\n\n static formats(domNode: Element) {\n return ATTRIBUTES.reduce(\n (formats: Record, attribute) => {\n if (domNode.hasAttribute(attribute)) {\n formats[attribute] = domNode.getAttribute(attribute);\n }\n return formats;\n },\n {},\n );\n }\n\n static match(url: string) {\n return /\\.(jpe?g|gif|png)$/.test(url) || /^data:image\\/.+;base64/.test(url);\n }\n\n static sanitize(url: string) {\n return sanitize(url, ['http', 'https', 'data']) ? url : '//:0';\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('src');\n }\n\n domNode: HTMLImageElement;\n\n format(name: string, value: string) {\n if (ATTRIBUTES.indexOf(name) > -1) {\n if (value) {\n this.domNode.setAttribute(name, value);\n } else {\n this.domNode.removeAttribute(name);\n }\n } else {\n super.format(name, value);\n }\n }\n}\n\nexport default Image;\n", "import { BlockEmbed } from '../blots/block.js';\nimport Link from './link.js';\n\nconst ATTRIBUTES = ['height', 'width'];\n\nclass Video extends BlockEmbed {\n static blotName = 'video';\n static className = 'ql-video';\n static tagName = 'IFRAME';\n\n static create(value: string) {\n const node = super.create(value) as Element;\n node.setAttribute('frameborder', '0');\n node.setAttribute('allowfullscreen', 'true');\n node.setAttribute('src', this.sanitize(value));\n return node;\n }\n\n static formats(domNode: Element) {\n return ATTRIBUTES.reduce(\n (formats: Record, attribute) => {\n if (domNode.hasAttribute(attribute)) {\n formats[attribute] = domNode.getAttribute(attribute);\n }\n return formats;\n },\n {},\n );\n }\n\n static sanitize(url: string) {\n return Link.sanitize(url);\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('src');\n }\n\n domNode: HTMLVideoElement;\n\n format(name: string, value: string) {\n if (ATTRIBUTES.indexOf(name) > -1) {\n if (value) {\n this.domNode.setAttribute(name, value);\n } else {\n this.domNode.removeAttribute(name);\n }\n } else {\n super.format(name, value);\n }\n }\n\n html() {\n const { video } = this.value();\n return `${video}`;\n }\n}\n\nexport default Video;\n", "import Delta from 'quill-delta';\nimport { ClassAttributor, Scope } from 'parchment';\nimport type { Blot, ScrollBlot } from 'parchment';\nimport Inline from '../blots/inline.js';\nimport Quill from '../core/quill.js';\nimport Module from '../core/module.js';\nimport { blockDelta } from '../blots/block.js';\nimport BreakBlot from '../blots/break.js';\nimport CursorBlot from '../blots/cursor.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport CodeBlock, { CodeBlockContainer } from '../formats/code.js';\nimport { traverse } from './clipboard.js';\n\nconst TokenAttributor = new ClassAttributor('code-token', 'hljs', {\n scope: Scope.INLINE,\n});\nclass CodeToken extends Inline {\n static formats(node: Element, scroll: ScrollBlot) {\n while (node != null && node !== scroll.domNode) {\n if (node.classList && node.classList.contains(CodeBlock.className)) {\n // @ts-expect-error\n return super.formats(node, scroll);\n }\n // @ts-expect-error\n node = node.parentNode;\n }\n return undefined;\n }\n\n constructor(scroll: ScrollBlot, domNode: Node, value: unknown) {\n // @ts-expect-error\n super(scroll, domNode, value);\n TokenAttributor.add(this.domNode, value);\n }\n\n format(format: string, value: unknown) {\n if (format !== CodeToken.blotName) {\n super.format(format, value);\n } else if (value) {\n TokenAttributor.add(this.domNode, value);\n } else {\n TokenAttributor.remove(this.domNode);\n this.domNode.classList.remove(this.statics.className);\n }\n }\n\n optimize(...args: unknown[]) {\n // @ts-expect-error\n super.optimize(...args);\n if (!TokenAttributor.value(this.domNode)) {\n this.unwrap();\n }\n }\n}\nCodeToken.blotName = 'code-token';\nCodeToken.className = 'ql-token';\n\nclass SyntaxCodeBlock extends CodeBlock {\n static create(value: unknown) {\n const domNode = super.create(value);\n if (typeof value === 'string') {\n domNode.setAttribute('data-language', value);\n }\n return domNode;\n }\n\n static formats(domNode: Node) {\n // @ts-expect-error\n return domNode.getAttribute('data-language') || 'plain';\n }\n\n static register() {} // Syntax module will register\n\n format(name: string, value: unknown) {\n if (name === this.statics.blotName && value) {\n // @ts-expect-error\n this.domNode.setAttribute('data-language', value);\n } else {\n super.format(name, value);\n }\n }\n\n replaceWith(name: string | Blot, value?: any) {\n this.formatAt(0, this.length(), CodeToken.blotName, false);\n return super.replaceWith(name, value);\n }\n}\n\nclass SyntaxCodeBlockContainer extends CodeBlockContainer {\n forceNext?: boolean;\n cachedText?: string | null;\n\n attach() {\n super.attach();\n this.forceNext = false;\n // @ts-expect-error\n this.scroll.emitMount(this);\n }\n\n format(name: string, value: unknown) {\n if (name === SyntaxCodeBlock.blotName) {\n this.forceNext = true;\n this.children.forEach((child) => {\n // @ts-expect-error\n child.format(name, value);\n });\n }\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (name === SyntaxCodeBlock.blotName) {\n this.forceNext = true;\n }\n super.formatAt(index, length, name, value);\n }\n\n highlight(\n highlight: (text: string, language: string) => Delta,\n forced = false,\n ) {\n if (this.children.head == null) return;\n const nodes = Array.from(this.domNode.childNodes).filter(\n (node) => node !== this.uiNode,\n );\n const text = `${nodes.map((node) => node.textContent).join('\\n')}\\n`;\n const language = SyntaxCodeBlock.formats(this.children.head.domNode);\n if (forced || this.forceNext || this.cachedText !== text) {\n if (text.trim().length > 0 || this.cachedText == null) {\n const oldDelta = this.children.reduce((delta, child) => {\n // @ts-expect-error\n return delta.concat(blockDelta(child, false));\n }, new Delta());\n const delta = highlight(text, language);\n oldDelta.diff(delta).reduce((index, { retain, attributes }) => {\n // Should be all retains\n if (!retain) return index;\n if (attributes) {\n Object.keys(attributes).forEach((format) => {\n if (\n [SyntaxCodeBlock.blotName, CodeToken.blotName].includes(format)\n ) {\n // @ts-expect-error\n this.formatAt(index, retain, format, attributes[format]);\n }\n });\n }\n // @ts-expect-error\n return index + retain;\n }, 0);\n }\n this.cachedText = text;\n this.forceNext = false;\n }\n }\n\n html(index: number, length: number) {\n const [codeBlock] = this.children.find(index);\n const language = codeBlock\n ? SyntaxCodeBlock.formats(codeBlock.domNode)\n : 'plain';\n\n return `
    \\n${escapeText(\n      this.code(index, length),\n    )}\\n
    `;\n }\n\n optimize(context: Record) {\n super.optimize(context);\n if (\n this.parent != null &&\n this.children.head != null &&\n this.uiNode != null\n ) {\n const language = SyntaxCodeBlock.formats(this.children.head.domNode);\n // @ts-expect-error\n if (language !== this.uiNode.value) {\n // @ts-expect-error\n this.uiNode.value = language;\n }\n }\n }\n}\n\nSyntaxCodeBlockContainer.allowedChildren = [SyntaxCodeBlock];\nSyntaxCodeBlock.requiredContainer = SyntaxCodeBlockContainer;\nSyntaxCodeBlock.allowedChildren = [CodeToken, CursorBlot, TextBlot, BreakBlot];\n\ninterface SyntaxOptions {\n interval: number;\n languages: { key: string; label: string }[];\n hljs: any;\n}\n\nconst highlight = (lib: any, language: string, text: string) => {\n if (typeof lib.versionString === 'string') {\n const majorVersion = lib.versionString.split('.')[0];\n if (parseInt(majorVersion, 10) >= 11) {\n return lib.highlight(text, { language }).value;\n }\n }\n return lib.highlight(language, text).value;\n};\n\nclass Syntax extends Module {\n static DEFAULTS: SyntaxOptions & { hljs: any };\n\n static register() {\n Quill.register(CodeToken, true);\n Quill.register(SyntaxCodeBlock, true);\n Quill.register(SyntaxCodeBlockContainer, true);\n }\n\n languages: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n if (this.options.hljs == null) {\n throw new Error(\n 'Syntax module requires highlight.js. Please include the library on the page before Quill.',\n );\n }\n // @ts-expect-error Fix me later\n this.languages = this.options.languages.reduce(\n (memo: Record, { key }) => {\n memo[key] = true;\n return memo;\n },\n {},\n );\n this.highlightBlot = this.highlightBlot.bind(this);\n this.initListener();\n this.initTimer();\n }\n\n initListener() {\n this.quill.on(Quill.events.SCROLL_BLOT_MOUNT, (blot: Blot) => {\n if (!(blot instanceof SyntaxCodeBlockContainer)) return;\n const select = this.quill.root.ownerDocument.createElement('select');\n // @ts-expect-error Fix me later\n this.options.languages.forEach(({ key, label }) => {\n const option = select.ownerDocument.createElement('option');\n option.textContent = label;\n option.setAttribute('value', key);\n select.appendChild(option);\n });\n select.addEventListener('change', () => {\n blot.format(SyntaxCodeBlock.blotName, select.value);\n this.quill.root.focus(); // Prevent scrolling\n this.highlight(blot, true);\n });\n if (blot.uiNode == null) {\n blot.attachUI(select);\n if (blot.children.head) {\n select.value = SyntaxCodeBlock.formats(blot.children.head.domNode);\n }\n }\n });\n }\n\n initTimer() {\n let timer: ReturnType | null = null;\n this.quill.on(Quill.events.SCROLL_OPTIMIZE, () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = setTimeout(() => {\n this.highlight();\n timer = null;\n }, this.options.interval);\n });\n }\n\n highlight(blot: SyntaxCodeBlockContainer | null = null, force = false) {\n if (this.quill.selection.composing) return;\n this.quill.update(Quill.sources.USER);\n const range = this.quill.getSelection();\n const blots =\n blot == null\n ? this.quill.scroll.descendants(SyntaxCodeBlockContainer)\n : [blot];\n blots.forEach((container) => {\n container.highlight(this.highlightBlot, force);\n });\n this.quill.update(Quill.sources.SILENT);\n if (range != null) {\n this.quill.setSelection(range, Quill.sources.SILENT);\n }\n }\n\n highlightBlot(text: string, language = 'plain') {\n language = this.languages[language] ? language : 'plain';\n if (language === 'plain') {\n return escapeText(text)\n .split('\\n')\n .reduce((delta, line, i) => {\n if (i !== 0) {\n delta.insert('\\n', { [CodeBlock.blotName]: language });\n }\n return delta.insert(line);\n }, new Delta());\n }\n const container = this.quill.root.ownerDocument.createElement('div');\n container.classList.add(CodeBlock.className);\n container.innerHTML = highlight(this.options.hljs, language, text);\n return traverse(\n this.quill.scroll,\n container,\n [\n (node, delta) => {\n // @ts-expect-error\n const value = TokenAttributor.value(node);\n if (value) {\n return delta.compose(\n new Delta().retain(delta.length(), {\n [CodeToken.blotName]: value,\n }),\n );\n }\n return delta;\n },\n ],\n [\n (node, delta) => {\n // @ts-expect-error\n return node.data.split('\\n').reduce((memo, nodeText, i) => {\n if (i !== 0) memo.insert('\\n', { [CodeBlock.blotName]: language });\n return memo.insert(nodeText);\n }, delta);\n },\n ],\n new WeakMap(),\n );\n }\n}\nSyntax.DEFAULTS = {\n hljs: (() => {\n return window.hljs;\n })(),\n interval: 1000,\n languages: [\n { key: 'plain', label: 'Plain' },\n { key: 'bash', label: 'Bash' },\n { key: 'cpp', label: 'C++' },\n { key: 'cs', label: 'C#' },\n { key: 'css', label: 'CSS' },\n { key: 'diff', label: 'Diff' },\n { key: 'xml', label: 'HTML/XML' },\n { key: 'java', label: 'Java' },\n { key: 'javascript', label: 'JavaScript' },\n { key: 'markdown', label: 'Markdown' },\n { key: 'php', label: 'PHP' },\n { key: 'python', label: 'Python' },\n { key: 'ruby', label: 'Ruby' },\n { key: 'sql', label: 'SQL' },\n ],\n};\n\nexport { SyntaxCodeBlock as CodeBlock, CodeToken, Syntax as default };\n", "import type { LinkedList } from 'parchment';\nimport Block from '../blots/block.js';\nimport Container from '../blots/container.js';\n\nclass TableCell extends Block {\n static blotName = 'table';\n static tagName = 'TD';\n\n static create(value: string) {\n const node = super.create() as HTMLElement;\n if (value) {\n node.setAttribute('data-row', value);\n } else {\n node.setAttribute('data-row', tableId());\n }\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n if (domNode.hasAttribute('data-row')) {\n return domNode.getAttribute('data-row');\n }\n return undefined;\n }\n\n next: this | null;\n\n cellOffset() {\n if (this.parent) {\n return this.parent.children.indexOf(this);\n }\n return -1;\n }\n\n format(name: string, value: string) {\n if (name === TableCell.blotName && value) {\n this.domNode.setAttribute('data-row', value);\n } else {\n super.format(name, value);\n }\n }\n\n row(): TableRow {\n return this.parent as TableRow;\n }\n\n rowOffset() {\n if (this.row()) {\n return this.row().rowOffset();\n }\n return -1;\n }\n\n table() {\n return this.row() && this.row().table();\n }\n}\n\nclass TableRow extends Container {\n static blotName = 'table-row';\n static tagName = 'TR';\n\n children: LinkedList;\n next: this | null;\n\n checkMerge() {\n // @ts-expect-error\n if (super.checkMerge() && this.next.children.head != null) {\n // @ts-expect-error\n const thisHead = this.children.head.formats();\n // @ts-expect-error\n const thisTail = this.children.tail.formats();\n // @ts-expect-error\n const nextHead = this.next.children.head.formats();\n // @ts-expect-error\n const nextTail = this.next.children.tail.formats();\n return (\n thisHead.table === thisTail.table &&\n thisHead.table === nextHead.table &&\n thisHead.table === nextTail.table\n );\n }\n return false;\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n this.children.forEach((child) => {\n if (child.next == null) return;\n const childFormats = child.formats();\n const nextFormats = child.next.formats();\n if (childFormats.table !== nextFormats.table) {\n const next = this.splitAfter(child);\n if (next) {\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n next.optimize();\n }\n // We might be able to merge with prev now\n if (this.prev) {\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n this.prev.optimize();\n }\n }\n });\n }\n\n rowOffset() {\n if (this.parent) {\n return this.parent.children.indexOf(this);\n }\n return -1;\n }\n\n table() {\n return this.parent && this.parent.parent;\n }\n}\n\nclass TableBody extends Container {\n static blotName = 'table-body';\n static tagName = 'TBODY';\n\n children: LinkedList;\n}\n\nclass TableContainer extends Container {\n static blotName = 'table-container';\n static tagName = 'TABLE';\n\n children: LinkedList;\n\n balanceCells() {\n const rows = this.descendants(TableRow);\n const maxColumns = rows.reduce((max, row) => {\n return Math.max(row.children.length, max);\n }, 0);\n rows.forEach((row) => {\n new Array(maxColumns - row.children.length).fill(0).forEach(() => {\n let value;\n if (row.children.head != null) {\n value = TableCell.formats(row.children.head.domNode);\n }\n const blot = this.scroll.create(TableCell.blotName, value);\n row.appendChild(blot);\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n blot.optimize(); // Add break blot\n });\n });\n }\n\n cells(column: number) {\n return this.rows().map((row) => row.children.at(column));\n }\n\n deleteColumn(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n body.children.forEach((row) => {\n const cell = row.children.at(index);\n if (cell != null) {\n cell.remove();\n }\n });\n }\n\n insertColumn(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n body.children.forEach((row) => {\n const ref = row.children.at(index);\n // @ts-expect-error\n const value = TableCell.formats(row.children.head.domNode);\n const cell = this.scroll.create(TableCell.blotName, value);\n row.insertBefore(cell, ref);\n });\n }\n\n insertRow(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n const id = tableId();\n const row = this.scroll.create(TableRow.blotName) as TableRow;\n body.children.head.children.forEach(() => {\n const cell = this.scroll.create(TableCell.blotName, id);\n row.appendChild(cell);\n });\n const ref = body.children.at(index);\n body.insertBefore(row, ref);\n }\n\n rows() {\n const body = this.children.head;\n if (body == null) return [];\n return body.children.map((row) => row);\n }\n}\n\nTableContainer.allowedChildren = [TableBody];\nTableBody.requiredContainer = TableContainer;\n\nTableBody.allowedChildren = [TableRow];\nTableRow.requiredContainer = TableBody;\n\nTableRow.allowedChildren = [TableCell];\nTableCell.requiredContainer = TableRow;\n\nfunction tableId() {\n const id = Math.random().toString(36).slice(2, 6);\n return `row-${id}`;\n}\n\nexport { TableCell, TableRow, TableBody, TableContainer, tableId };\n", "import Delta from 'quill-delta';\nimport Quill from '../core/quill.js';\nimport Module from '../core/module.js';\nimport {\n TableCell,\n TableRow,\n TableBody,\n TableContainer,\n tableId,\n} from '../formats/table.js';\n\nclass Table extends Module {\n static register() {\n Quill.register(TableCell);\n Quill.register(TableRow);\n Quill.register(TableBody);\n Quill.register(TableContainer);\n }\n\n constructor(...args: ConstructorParameters) {\n super(...args);\n this.listenBalanceCells();\n }\n\n balanceTables() {\n this.quill.scroll.descendants(TableContainer).forEach((table) => {\n table.balanceCells();\n });\n }\n\n deleteColumn() {\n const [table, , cell] = this.getTable();\n if (cell == null) return;\n // @ts-expect-error\n table.deleteColumn(cell.cellOffset());\n this.quill.update(Quill.sources.USER);\n }\n\n deleteRow() {\n const [, row] = this.getTable();\n if (row == null) return;\n row.remove();\n this.quill.update(Quill.sources.USER);\n }\n\n deleteTable() {\n const [table] = this.getTable();\n if (table == null) return;\n // @ts-expect-error\n const offset = table.offset();\n // @ts-expect-error\n table.remove();\n this.quill.update(Quill.sources.USER);\n this.quill.setSelection(offset, Quill.sources.SILENT);\n }\n\n getTable(\n range = this.quill.getSelection(),\n ): [null, null, null, -1] | [Table, TableRow, TableCell, number] {\n if (range == null) return [null, null, null, -1];\n const [cell, offset] = this.quill.getLine(range.index);\n if (cell == null || cell.statics.blotName !== TableCell.blotName) {\n return [null, null, null, -1];\n }\n const row = cell.parent;\n const table = row.parent.parent;\n // @ts-expect-error\n return [table, row, cell, offset];\n }\n\n insertColumn(offset: number) {\n const range = this.quill.getSelection();\n if (!range) return;\n const [table, row, cell] = this.getTable(range);\n if (cell == null) return;\n const column = cell.cellOffset();\n table.insertColumn(column + offset);\n this.quill.update(Quill.sources.USER);\n let shift = row.rowOffset();\n if (offset === 0) {\n shift += 1;\n }\n this.quill.setSelection(\n range.index + shift,\n range.length,\n Quill.sources.SILENT,\n );\n }\n\n insertColumnLeft() {\n this.insertColumn(0);\n }\n\n insertColumnRight() {\n this.insertColumn(1);\n }\n\n insertRow(offset: number) {\n const range = this.quill.getSelection();\n if (!range) return;\n const [table, row, cell] = this.getTable(range);\n if (cell == null) return;\n const index = row.rowOffset();\n table.insertRow(index + offset);\n this.quill.update(Quill.sources.USER);\n if (offset > 0) {\n this.quill.setSelection(range, Quill.sources.SILENT);\n } else {\n this.quill.setSelection(\n range.index + row.children.length,\n range.length,\n Quill.sources.SILENT,\n );\n }\n }\n\n insertRowAbove() {\n this.insertRow(0);\n }\n\n insertRowBelow() {\n this.insertRow(1);\n }\n\n insertTable(rows: number, columns: number) {\n const range = this.quill.getSelection();\n if (range == null) return;\n const delta = new Array(rows).fill(0).reduce((memo) => {\n const text = new Array(columns).fill('\\n').join('');\n return memo.insert(text, { table: tableId() });\n }, new Delta().retain(range.index));\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index, Quill.sources.SILENT);\n this.balanceTables();\n }\n\n listenBalanceCells() {\n this.quill.on(\n Quill.events.SCROLL_OPTIMIZE,\n (mutations: MutationRecord[]) => {\n mutations.some((mutation) => {\n if (\n ['TD', 'TR', 'TBODY', 'TABLE'].includes(\n (mutation.target as HTMLElement).tagName,\n )\n ) {\n this.quill.once(Quill.events.TEXT_CHANGE, (delta, old, source) => {\n if (source !== Quill.sources.USER) return;\n this.balanceTables();\n });\n return true;\n }\n return false;\n });\n },\n );\n }\n}\n\nexport default Table;\n", "import Delta from 'quill-delta';\nimport { EmbedBlot, Scope } from 'parchment';\nimport Quill from '../core/quill.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport type { Range } from '../core/selection.js';\n\nconst debug = logger('quill:toolbar');\n\ntype Handler = (this: Toolbar, value: any) => void;\n\nexport type ToolbarConfig = Array<\n string[] | Array>\n>;\nexport interface ToolbarProps {\n container?: HTMLElement | ToolbarConfig | null;\n handlers?: Record;\n option?: number;\n module?: boolean;\n theme?: boolean;\n}\n\nclass Toolbar extends Module {\n static DEFAULTS: ToolbarProps;\n\n container?: HTMLElement | null;\n controls: [string, HTMLElement][];\n handlers: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n if (Array.isArray(this.options.container)) {\n const container = document.createElement('div');\n container.setAttribute('role', 'toolbar');\n addControls(container, this.options.container);\n quill.container?.parentNode?.insertBefore(container, quill.container);\n this.container = container;\n } else if (typeof this.options.container === 'string') {\n this.container = document.querySelector(this.options.container);\n } else {\n this.container = this.options.container;\n }\n if (!(this.container instanceof HTMLElement)) {\n debug.error('Container required for toolbar', this.options);\n return;\n }\n this.container.classList.add('ql-toolbar');\n this.controls = [];\n this.handlers = {};\n if (this.options.handlers) {\n Object.keys(this.options.handlers).forEach((format) => {\n const handler = this.options.handlers?.[format];\n if (handler) {\n this.addHandler(format, handler);\n }\n });\n }\n Array.from(this.container.querySelectorAll('button, select')).forEach(\n (input) => {\n // @ts-expect-error\n this.attach(input);\n },\n );\n this.quill.on(Quill.events.EDITOR_CHANGE, () => {\n const [range] = this.quill.selection.getRange(); // quill.getSelection triggers update\n this.update(range);\n });\n }\n\n addHandler(format: string, handler: Handler) {\n this.handlers[format] = handler;\n }\n\n attach(input: HTMLElement) {\n let format = Array.from(input.classList).find((className) => {\n return className.indexOf('ql-') === 0;\n });\n if (!format) return;\n format = format.slice('ql-'.length);\n if (input.tagName === 'BUTTON') {\n input.setAttribute('type', 'button');\n }\n if (\n this.handlers[format] == null &&\n this.quill.scroll.query(format) == null\n ) {\n debug.warn('ignoring attaching to nonexistent format', format, input);\n return;\n }\n const eventName = input.tagName === 'SELECT' ? 'change' : 'click';\n input.addEventListener(eventName, (e) => {\n let value;\n if (input.tagName === 'SELECT') {\n // @ts-expect-error\n if (input.selectedIndex < 0) return;\n // @ts-expect-error\n const selected = input.options[input.selectedIndex];\n if (selected.hasAttribute('selected')) {\n value = false;\n } else {\n value = selected.value || false;\n }\n } else {\n if (input.classList.contains('ql-active')) {\n value = false;\n } else {\n // @ts-expect-error\n value = input.value || !input.hasAttribute('value');\n }\n e.preventDefault();\n }\n this.quill.focus();\n const [range] = this.quill.selection.getRange();\n if (this.handlers[format] != null) {\n this.handlers[format].call(this, value);\n } else if (\n // @ts-expect-error\n this.quill.scroll.query(format).prototype instanceof EmbedBlot\n ) {\n value = prompt(`Enter ${format}`); // eslint-disable-line no-alert\n if (!value) return;\n this.quill.updateContents(\n new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index)\n // @ts-expect-error Fix me later\n .delete(range.length)\n .insert({ [format]: value }),\n Quill.sources.USER,\n );\n } else {\n this.quill.format(format, value, Quill.sources.USER);\n }\n this.update(range);\n });\n this.controls.push([format, input]);\n }\n\n update(range: Range | null) {\n const formats = range == null ? {} : this.quill.getFormat(range);\n this.controls.forEach((pair) => {\n const [format, input] = pair;\n if (input.tagName === 'SELECT') {\n let option: HTMLOptionElement | null = null;\n if (range == null) {\n option = null;\n } else if (formats[format] == null) {\n option = input.querySelector('option[selected]');\n } else if (!Array.isArray(formats[format])) {\n let value = formats[format];\n if (typeof value === 'string') {\n value = value.replace(/\"/g, '\\\\\"');\n }\n option = input.querySelector(`option[value=\"${value}\"]`);\n }\n if (option == null) {\n // @ts-expect-error TODO fix me later\n input.value = ''; // TODO make configurable?\n // @ts-expect-error TODO fix me later\n input.selectedIndex = -1;\n } else {\n option.selected = true;\n }\n } else if (range == null) {\n input.classList.remove('ql-active');\n input.setAttribute('aria-pressed', 'false');\n } else if (input.hasAttribute('value')) {\n // both being null should match (default values)\n // '1' should match with 1 (headers)\n const value = formats[format] as boolean | number | string | object;\n const isActive =\n value === input.getAttribute('value') ||\n (value != null && value.toString() === input.getAttribute('value')) ||\n (value == null && !input.getAttribute('value'));\n input.classList.toggle('ql-active', isActive);\n input.setAttribute('aria-pressed', isActive.toString());\n } else {\n const isActive = formats[format] != null;\n input.classList.toggle('ql-active', isActive);\n input.setAttribute('aria-pressed', isActive.toString());\n }\n });\n }\n}\nToolbar.DEFAULTS = {};\n\nfunction addButton(container: HTMLElement, format: string, value?: string) {\n const input = document.createElement('button');\n input.setAttribute('type', 'button');\n input.classList.add(`ql-${format}`);\n input.setAttribute('aria-pressed', 'false');\n if (value != null) {\n input.value = value;\n input.setAttribute('aria-label', `${format}: ${value}`);\n } else {\n input.setAttribute('aria-label', format);\n }\n container.appendChild(input);\n}\n\nfunction addControls(\n container: HTMLElement,\n groups:\n | (string | Record)[][]\n | (string | Record)[],\n) {\n if (!Array.isArray(groups[0])) {\n // @ts-expect-error\n groups = [groups];\n }\n groups.forEach((controls: any) => {\n const group = document.createElement('span');\n group.classList.add('ql-formats');\n controls.forEach((control: any) => {\n if (typeof control === 'string') {\n addButton(group, control);\n } else {\n const format = Object.keys(control)[0];\n const value = control[format];\n if (Array.isArray(value)) {\n addSelect(group, format, value);\n } else {\n addButton(group, format, value);\n }\n }\n });\n container.appendChild(group);\n });\n}\n\nfunction addSelect(\n container: HTMLElement,\n format: string,\n values: Array,\n) {\n const input = document.createElement('select');\n input.classList.add(`ql-${format}`);\n values.forEach((value) => {\n const option = document.createElement('option');\n if (value !== false) {\n option.setAttribute('value', String(value));\n } else {\n option.setAttribute('selected', 'selected');\n }\n input.appendChild(option);\n });\n container.appendChild(input);\n}\n\nToolbar.DEFAULTS = {\n container: null,\n handlers: {\n clean() {\n const range = this.quill.getSelection();\n if (range == null) return;\n if (range.length === 0) {\n const formats = this.quill.getFormat();\n Object.keys(formats).forEach((name) => {\n // Clean functionality in existing apps only clean inline formats\n if (this.quill.scroll.query(name, Scope.INLINE) != null) {\n this.quill.format(name, false, Quill.sources.USER);\n }\n });\n } else {\n this.quill.removeFormat(range.index, range.length, Quill.sources.USER);\n }\n },\n direction(value) {\n const { align } = this.quill.getFormat();\n if (value === 'rtl' && align == null) {\n this.quill.format('align', 'right', Quill.sources.USER);\n } else if (!value && align === 'right') {\n this.quill.format('align', false, Quill.sources.USER);\n }\n this.quill.format('direction', value, Quill.sources.USER);\n },\n indent(value) {\n const range = this.quill.getSelection();\n // @ts-expect-error\n const formats = this.quill.getFormat(range);\n // @ts-expect-error\n const indent = parseInt(formats.indent || 0, 10);\n if (value === '+1' || value === '-1') {\n let modifier = value === '+1' ? 1 : -1;\n if (formats.direction === 'rtl') modifier *= -1;\n this.quill.format('indent', indent + modifier, Quill.sources.USER);\n }\n },\n link(value) {\n if (value === true) {\n value = prompt('Enter link URL:'); // eslint-disable-line no-alert\n }\n this.quill.format('link', value, Quill.sources.USER);\n },\n list(value) {\n const range = this.quill.getSelection();\n // @ts-expect-error\n const formats = this.quill.getFormat(range);\n if (value === 'check') {\n if (formats.list === 'checked' || formats.list === 'unchecked') {\n this.quill.format('list', false, Quill.sources.USER);\n } else {\n this.quill.format('list', 'unchecked', Quill.sources.USER);\n }\n } else {\n this.quill.format('list', value, Quill.sources.USER);\n }\n },\n },\n};\n\nexport { Toolbar as default, addControls };\n", "import alignLeftIcon from '../assets/icons/align-left.svg';\nimport alignCenterIcon from '../assets/icons/align-center.svg';\nimport alignRightIcon from '../assets/icons/align-right.svg';\nimport alignJustifyIcon from '../assets/icons/align-justify.svg';\nimport backgroundIcon from '../assets/icons/background.svg';\nimport blockquoteIcon from '../assets/icons/blockquote.svg';\nimport boldIcon from '../assets/icons/bold.svg';\nimport cleanIcon from '../assets/icons/clean.svg';\nimport codeIcon from '../assets/icons/code.svg';\nimport colorIcon from '../assets/icons/color.svg';\nimport directionLeftToRightIcon from '../assets/icons/direction-ltr.svg';\nimport directionRightToLeftIcon from '../assets/icons/direction-rtl.svg';\nimport formulaIcon from '../assets/icons/formula.svg';\nimport headerIcon from '../assets/icons/header.svg';\nimport header2Icon from '../assets/icons/header-2.svg';\nimport header3Icon from '../assets/icons/header-3.svg';\nimport header4Icon from '../assets/icons/header-4.svg';\nimport header5Icon from '../assets/icons/header-5.svg';\nimport header6Icon from '../assets/icons/header-6.svg';\nimport italicIcon from '../assets/icons/italic.svg';\nimport imageIcon from '../assets/icons/image.svg';\nimport indentIcon from '../assets/icons/indent.svg';\nimport outdentIcon from '../assets/icons/outdent.svg';\nimport linkIcon from '../assets/icons/link.svg';\nimport listBulletIcon from '../assets/icons/list-bullet.svg';\nimport listCheckIcon from '../assets/icons/list-check.svg';\nimport listOrderedIcon from '../assets/icons/list-ordered.svg';\nimport subscriptIcon from '../assets/icons/subscript.svg';\nimport superscriptIcon from '../assets/icons/superscript.svg';\nimport strikeIcon from '../assets/icons/strike.svg';\nimport tableIcon from '../assets/icons/table.svg';\nimport underlineIcon from '../assets/icons/underline.svg';\nimport videoIcon from '../assets/icons/video.svg';\n\nexport default {\n align: {\n '': alignLeftIcon,\n center: alignCenterIcon,\n right: alignRightIcon,\n justify: alignJustifyIcon,\n },\n background: backgroundIcon,\n blockquote: blockquoteIcon,\n bold: boldIcon,\n clean: cleanIcon,\n code: codeIcon,\n 'code-block': codeIcon,\n color: colorIcon,\n direction: {\n '': directionLeftToRightIcon,\n rtl: directionRightToLeftIcon,\n },\n formula: formulaIcon,\n header: {\n '1': headerIcon,\n '2': header2Icon,\n '3': header3Icon,\n '4': header4Icon,\n '5': header5Icon,\n '6': header6Icon,\n },\n italic: italicIcon,\n image: imageIcon,\n indent: {\n '+1': indentIcon,\n '-1': outdentIcon,\n },\n link: linkIcon,\n list: {\n bullet: listBulletIcon,\n check: listCheckIcon,\n ordered: listOrderedIcon,\n },\n script: {\n sub: subscriptIcon,\n super: superscriptIcon,\n },\n strike: strikeIcon,\n table: tableIcon,\n underline: underlineIcon,\n video: videoIcon,\n};\n", "import DropdownIcon from '../assets/icons/dropdown.svg';\n\nlet optionsCounter = 0;\n\nfunction toggleAriaAttribute(element: HTMLElement, attribute: string) {\n element.setAttribute(\n attribute,\n `${!(element.getAttribute(attribute) === 'true')}`,\n );\n}\n\nclass Picker {\n select: HTMLSelectElement;\n container: HTMLElement;\n label: HTMLElement;\n\n constructor(select: HTMLSelectElement) {\n this.select = select;\n this.container = document.createElement('span');\n this.buildPicker();\n this.select.style.display = 'none';\n // @ts-expect-error Fix me later\n this.select.parentNode.insertBefore(this.container, this.select);\n\n this.label.addEventListener('mousedown', () => {\n this.togglePicker();\n });\n this.label.addEventListener('keydown', (event) => {\n switch (event.key) {\n case 'Enter':\n this.togglePicker();\n break;\n case 'Escape':\n this.escape();\n event.preventDefault();\n break;\n default:\n }\n });\n this.select.addEventListener('change', this.update.bind(this));\n }\n\n togglePicker() {\n this.container.classList.toggle('ql-expanded');\n // Toggle aria-expanded and aria-hidden to make the picker accessible\n toggleAriaAttribute(this.label, 'aria-expanded');\n // @ts-expect-error\n toggleAriaAttribute(this.options, 'aria-hidden');\n }\n\n buildItem(option: HTMLOptionElement) {\n const item = document.createElement('span');\n // @ts-expect-error\n item.tabIndex = '0';\n item.setAttribute('role', 'button');\n item.classList.add('ql-picker-item');\n const value = option.getAttribute('value');\n if (value) {\n item.setAttribute('data-value', value);\n }\n if (option.textContent) {\n item.setAttribute('data-label', option.textContent);\n }\n item.addEventListener('click', () => {\n this.selectItem(item, true);\n });\n item.addEventListener('keydown', (event) => {\n switch (event.key) {\n case 'Enter':\n this.selectItem(item, true);\n event.preventDefault();\n break;\n case 'Escape':\n this.escape();\n event.preventDefault();\n break;\n default:\n }\n });\n\n return item;\n }\n\n buildLabel() {\n const label = document.createElement('span');\n label.classList.add('ql-picker-label');\n label.innerHTML = DropdownIcon;\n // @ts-expect-error\n label.tabIndex = '0';\n label.setAttribute('role', 'button');\n label.setAttribute('aria-expanded', 'false');\n this.container.appendChild(label);\n return label;\n }\n\n buildOptions() {\n const options = document.createElement('span');\n options.classList.add('ql-picker-options');\n\n // Don't want screen readers to read this until options are visible\n options.setAttribute('aria-hidden', 'true');\n // @ts-expect-error\n options.tabIndex = '-1';\n\n // Need a unique id for aria-controls\n options.id = `ql-picker-options-${optionsCounter}`;\n optionsCounter += 1;\n this.label.setAttribute('aria-controls', options.id);\n\n // @ts-expect-error\n this.options = options;\n\n Array.from(this.select.options).forEach((option) => {\n const item = this.buildItem(option);\n options.appendChild(item);\n if (option.selected === true) {\n this.selectItem(item);\n }\n });\n this.container.appendChild(options);\n }\n\n buildPicker() {\n Array.from(this.select.attributes).forEach((item) => {\n this.container.setAttribute(item.name, item.value);\n });\n this.container.classList.add('ql-picker');\n this.label = this.buildLabel();\n this.buildOptions();\n }\n\n escape() {\n // Close menu and return focus to trigger label\n this.close();\n // Need setTimeout for accessibility to ensure that the browser executes\n // focus on the next process thread and after any DOM content changes\n setTimeout(() => this.label.focus(), 1);\n }\n\n close() {\n this.container.classList.remove('ql-expanded');\n this.label.setAttribute('aria-expanded', 'false');\n // @ts-expect-error\n this.options.setAttribute('aria-hidden', 'true');\n }\n\n selectItem(item: HTMLElement | null, trigger = false) {\n const selected = this.container.querySelector('.ql-selected');\n if (item === selected) return;\n if (selected != null) {\n selected.classList.remove('ql-selected');\n }\n if (item == null) return;\n item.classList.add('ql-selected');\n // @ts-expect-error Fix me later\n this.select.selectedIndex = Array.from(item.parentNode.children).indexOf(\n item,\n );\n if (item.hasAttribute('data-value')) {\n // @ts-expect-error Fix me later\n this.label.setAttribute('data-value', item.getAttribute('data-value'));\n } else {\n this.label.removeAttribute('data-value');\n }\n if (item.hasAttribute('data-label')) {\n // @ts-expect-error Fix me later\n this.label.setAttribute('data-label', item.getAttribute('data-label'));\n } else {\n this.label.removeAttribute('data-label');\n }\n if (trigger) {\n this.select.dispatchEvent(new Event('change'));\n this.close();\n }\n }\n\n update() {\n let option;\n if (this.select.selectedIndex > -1) {\n const item =\n // @ts-expect-error Fix me later\n this.container.querySelector('.ql-picker-options').children[\n this.select.selectedIndex\n ];\n option = this.select.options[this.select.selectedIndex];\n // @ts-expect-error\n this.selectItem(item);\n } else {\n this.selectItem(null);\n }\n const isActive =\n option != null &&\n option !== this.select.querySelector('option[selected]');\n this.label.classList.toggle('ql-active', isActive);\n }\n}\n\nexport default Picker;\n", "import Picker from './picker.js';\n\nclass ColorPicker extends Picker {\n constructor(select: HTMLSelectElement, label: string) {\n super(select);\n this.label.innerHTML = label;\n this.container.classList.add('ql-color-picker');\n Array.from(this.container.querySelectorAll('.ql-picker-item'))\n .slice(0, 7)\n .forEach((item) => {\n item.classList.add('ql-primary');\n });\n }\n\n buildItem(option: HTMLOptionElement) {\n const item = super.buildItem(option);\n item.style.backgroundColor = option.getAttribute('value') || '';\n return item;\n }\n\n selectItem(item: HTMLElement | null, trigger?: boolean) {\n super.selectItem(item, trigger);\n const colorLabel = this.label.querySelector('.ql-color-label');\n const value = item ? item.getAttribute('data-value') || '' : '';\n if (colorLabel) {\n if (colorLabel.tagName === 'line') {\n colorLabel.style.stroke = value;\n } else {\n colorLabel.style.fill = value;\n }\n }\n }\n}\n\nexport default ColorPicker;\n", "import Picker from './picker.js';\n\nclass IconPicker extends Picker {\n defaultItem: HTMLElement | null;\n\n constructor(select: HTMLSelectElement, icons: Record) {\n super(select);\n this.container.classList.add('ql-icon-picker');\n Array.from(this.container.querySelectorAll('.ql-picker-item')).forEach(\n (item) => {\n item.innerHTML = icons[item.getAttribute('data-value') || ''];\n },\n );\n this.defaultItem = this.container.querySelector('.ql-selected');\n this.selectItem(this.defaultItem);\n }\n\n selectItem(target: HTMLElement | null, trigger?: boolean) {\n super.selectItem(target, trigger);\n const item = target || this.defaultItem;\n if (item != null) {\n if (this.label.innerHTML === item.innerHTML) return;\n this.label.innerHTML = item.innerHTML;\n }\n }\n}\n\nexport default IconPicker;\n", "import type Quill from '../core.js';\nimport type { Bounds } from '../core/selection.js';\n\nconst isScrollable = (el: Element) => {\n const { overflowY } = getComputedStyle(el, null);\n return overflowY !== 'visible' && overflowY !== 'clip';\n};\n\nclass Tooltip {\n quill: Quill;\n boundsContainer: HTMLElement;\n root: HTMLDivElement;\n\n constructor(quill: Quill, boundsContainer?: HTMLElement) {\n this.quill = quill;\n this.boundsContainer = boundsContainer || document.body;\n this.root = quill.addContainer('ql-tooltip');\n // @ts-expect-error\n this.root.innerHTML = this.constructor.TEMPLATE;\n if (isScrollable(this.quill.root)) {\n this.quill.root.addEventListener('scroll', () => {\n this.root.style.marginTop = `${-1 * this.quill.root.scrollTop}px`;\n });\n }\n this.hide();\n }\n\n hide() {\n this.root.classList.add('ql-hidden');\n }\n\n position(reference: Bounds) {\n const left =\n reference.left + reference.width / 2 - this.root.offsetWidth / 2;\n // root.scrollTop should be 0 if scrollContainer !== root\n const top = reference.bottom + this.quill.root.scrollTop;\n this.root.style.left = `${left}px`;\n this.root.style.top = `${top}px`;\n this.root.classList.remove('ql-flip');\n const containerBounds = this.boundsContainer.getBoundingClientRect();\n const rootBounds = this.root.getBoundingClientRect();\n let shift = 0;\n if (rootBounds.right > containerBounds.right) {\n shift = containerBounds.right - rootBounds.right;\n this.root.style.left = `${left + shift}px`;\n }\n if (rootBounds.left < containerBounds.left) {\n shift = containerBounds.left - rootBounds.left;\n this.root.style.left = `${left + shift}px`;\n }\n if (rootBounds.bottom > containerBounds.bottom) {\n const height = rootBounds.bottom - rootBounds.top;\n const verticalShift = reference.bottom - reference.top + height;\n this.root.style.top = `${top - verticalShift}px`;\n this.root.classList.add('ql-flip');\n }\n return shift;\n }\n\n show() {\n this.root.classList.remove('ql-editing');\n this.root.classList.remove('ql-hidden');\n }\n}\n\nexport default Tooltip;\n", "import { merge } from 'lodash-es';\nimport type Quill from '../core/quill.js';\nimport Emitter from '../core/emitter.js';\nimport Theme from '../core/theme.js';\nimport type { ThemeOptions } from '../core/theme.js';\nimport ColorPicker from '../ui/color-picker.js';\nimport IconPicker from '../ui/icon-picker.js';\nimport Picker from '../ui/picker.js';\nimport Tooltip from '../ui/tooltip.js';\nimport type { Range } from '../core/selection.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type Uploader from '../modules/uploader.js';\nimport type Selection from '../core/selection.js';\n\nconst ALIGNS = [false, 'center', 'right', 'justify'];\n\nconst COLORS = [\n '#000000',\n '#e60000',\n '#ff9900',\n '#ffff00',\n '#008a00',\n '#0066cc',\n '#9933ff',\n '#ffffff',\n '#facccc',\n '#ffebcc',\n '#ffffcc',\n '#cce8cc',\n '#cce0f5',\n '#ebd6ff',\n '#bbbbbb',\n '#f06666',\n '#ffc266',\n '#ffff66',\n '#66b966',\n '#66a3e0',\n '#c285ff',\n '#888888',\n '#a10000',\n '#b26b00',\n '#b2b200',\n '#006100',\n '#0047b2',\n '#6b24b2',\n '#444444',\n '#5c0000',\n '#663d00',\n '#666600',\n '#003700',\n '#002966',\n '#3d1466',\n];\n\nconst FONTS = [false, 'serif', 'monospace'];\n\nconst HEADERS = ['1', '2', '3', false];\n\nconst SIZES = ['small', false, 'large', 'huge'];\n\nclass BaseTheme extends Theme {\n pickers: Picker[];\n tooltip?: Tooltip;\n\n constructor(quill: Quill, options: ThemeOptions) {\n super(quill, options);\n const listener = (e: MouseEvent) => {\n if (!document.body.contains(quill.root)) {\n document.body.removeEventListener('click', listener);\n return;\n }\n if (\n this.tooltip != null &&\n // @ts-expect-error\n !this.tooltip.root.contains(e.target) &&\n // @ts-expect-error\n document.activeElement !== this.tooltip.textbox &&\n !this.quill.hasFocus()\n ) {\n this.tooltip.hide();\n }\n if (this.pickers != null) {\n this.pickers.forEach((picker) => {\n // @ts-expect-error\n if (!picker.container.contains(e.target)) {\n picker.close();\n }\n });\n }\n };\n quill.emitter.listenDOM('click', document.body, listener);\n }\n\n addModule(name: 'clipboard'): Clipboard;\n addModule(name: 'keyboard'): Keyboard;\n addModule(name: 'uploader'): Uploader;\n addModule(name: 'history'): History;\n addModule(name: 'selection'): Selection;\n addModule(name: string): unknown;\n addModule(name: string) {\n const module = super.addModule(name);\n if (name === 'toolbar') {\n // @ts-expect-error\n this.extendToolbar(module);\n }\n return module;\n }\n\n buildButtons(\n buttons: NodeListOf,\n icons: Record | string>,\n ) {\n Array.from(buttons).forEach((button) => {\n const className = button.getAttribute('class') || '';\n className.split(/\\s+/).forEach((name) => {\n if (!name.startsWith('ql-')) return;\n name = name.slice('ql-'.length);\n if (icons[name] == null) return;\n if (name === 'direction') {\n // @ts-expect-error\n button.innerHTML = icons[name][''] + icons[name].rtl;\n } else if (typeof icons[name] === 'string') {\n // @ts-expect-error\n button.innerHTML = icons[name];\n } else {\n // @ts-expect-error\n const value = button.value || '';\n // @ts-expect-error\n if (value != null && icons[name][value]) {\n // @ts-expect-error\n button.innerHTML = icons[name][value];\n }\n }\n });\n });\n }\n\n buildPickers(\n selects: NodeListOf,\n icons: Record>,\n ) {\n this.pickers = Array.from(selects).map((select) => {\n if (select.classList.contains('ql-align')) {\n if (select.querySelector('option') == null) {\n fillSelect(select, ALIGNS);\n }\n if (typeof icons.align === 'object') {\n return new IconPicker(select, icons.align);\n }\n }\n if (\n select.classList.contains('ql-background') ||\n select.classList.contains('ql-color')\n ) {\n const format = select.classList.contains('ql-background')\n ? 'background'\n : 'color';\n if (select.querySelector('option') == null) {\n fillSelect(\n select,\n COLORS,\n format === 'background' ? '#ffffff' : '#000000',\n );\n }\n return new ColorPicker(select, icons[format] as string);\n }\n if (select.querySelector('option') == null) {\n if (select.classList.contains('ql-font')) {\n fillSelect(select, FONTS);\n } else if (select.classList.contains('ql-header')) {\n fillSelect(select, HEADERS);\n } else if (select.classList.contains('ql-size')) {\n fillSelect(select, SIZES);\n }\n }\n return new Picker(select);\n });\n const update = () => {\n this.pickers.forEach((picker) => {\n picker.update();\n });\n };\n this.quill.on(Emitter.events.EDITOR_CHANGE, update);\n }\n}\nBaseTheme.DEFAULTS = merge({}, Theme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n formula() {\n this.quill.theme.tooltip.edit('formula');\n },\n image() {\n let fileInput = this.container.querySelector(\n 'input.ql-image[type=file]',\n );\n if (fileInput == null) {\n fileInput = document.createElement('input');\n fileInput.setAttribute('type', 'file');\n fileInput.setAttribute(\n 'accept',\n this.quill.uploader.options.mimetypes.join(', '),\n );\n fileInput.classList.add('ql-image');\n fileInput.addEventListener('change', () => {\n const range = this.quill.getSelection(true);\n this.quill.uploader.upload(range, fileInput.files);\n fileInput.value = '';\n });\n this.container.appendChild(fileInput);\n }\n fileInput.click();\n },\n video() {\n this.quill.theme.tooltip.edit('video');\n },\n },\n },\n },\n});\n\nclass BaseTooltip extends Tooltip {\n textbox: HTMLInputElement | null;\n linkRange?: Range;\n\n constructor(quill: Quill, boundsContainer?: HTMLElement) {\n super(quill, boundsContainer);\n this.textbox = this.root.querySelector('input[type=\"text\"]');\n this.listen();\n }\n\n listen() {\n // @ts-expect-error Fix me later\n this.textbox.addEventListener('keydown', (event) => {\n if (event.key === 'Enter') {\n this.save();\n event.preventDefault();\n } else if (event.key === 'Escape') {\n this.cancel();\n event.preventDefault();\n }\n });\n }\n\n cancel() {\n this.hide();\n this.restoreFocus();\n }\n\n edit(mode = 'link', preview: string | null = null) {\n this.root.classList.remove('ql-hidden');\n this.root.classList.add('ql-editing');\n if (this.textbox == null) return;\n\n if (preview != null) {\n this.textbox.value = preview;\n } else if (mode !== this.root.getAttribute('data-mode')) {\n this.textbox.value = '';\n }\n const bounds = this.quill.getBounds(this.quill.selection.savedRange);\n if (bounds != null) {\n this.position(bounds);\n }\n this.textbox.select();\n this.textbox.setAttribute(\n 'placeholder',\n this.textbox.getAttribute(`data-${mode}`) || '',\n );\n this.root.setAttribute('data-mode', mode);\n }\n\n restoreFocus() {\n this.quill.focus({ preventScroll: true });\n }\n\n save() {\n // @ts-expect-error Fix me later\n let { value } = this.textbox;\n switch (this.root.getAttribute('data-mode')) {\n case 'link': {\n const { scrollTop } = this.quill.root;\n if (this.linkRange) {\n this.quill.formatText(\n this.linkRange,\n 'link',\n value,\n Emitter.sources.USER,\n );\n delete this.linkRange;\n } else {\n this.restoreFocus();\n this.quill.format('link', value, Emitter.sources.USER);\n }\n this.quill.root.scrollTop = scrollTop;\n break;\n }\n case 'video': {\n value = extractVideoUrl(value);\n } // eslint-disable-next-line no-fallthrough\n case 'formula': {\n if (!value) break;\n const range = this.quill.getSelection(true);\n if (range != null) {\n const index = range.index + range.length;\n this.quill.insertEmbed(\n index,\n // @ts-expect-error Fix me later\n this.root.getAttribute('data-mode'),\n value,\n Emitter.sources.USER,\n );\n if (this.root.getAttribute('data-mode') === 'formula') {\n this.quill.insertText(index + 1, ' ', Emitter.sources.USER);\n }\n this.quill.setSelection(index + 2, Emitter.sources.USER);\n }\n break;\n }\n default:\n }\n // @ts-expect-error Fix me later\n this.textbox.value = '';\n this.hide();\n }\n}\n\nfunction extractVideoUrl(url: string) {\n let match =\n url.match(\n /^(?:(https?):\\/\\/)?(?:(?:www|m)\\.)?youtube\\.com\\/watch.*v=([a-zA-Z0-9_-]+)/,\n ) ||\n url.match(/^(?:(https?):\\/\\/)?(?:(?:www|m)\\.)?youtu\\.be\\/([a-zA-Z0-9_-]+)/);\n if (match) {\n return `${match[1] || 'https'}://www.youtube.com/embed/${\n match[2]\n }?showinfo=0`;\n }\n // eslint-disable-next-line no-cond-assign\n if ((match = url.match(/^(?:(https?):\\/\\/)?(?:www\\.)?vimeo\\.com\\/(\\d+)/))) {\n return `${match[1] || 'https'}://player.vimeo.com/video/${match[2]}/`;\n }\n return url;\n}\n\nfunction fillSelect(\n select: HTMLSelectElement,\n values: Array,\n defaultValue: unknown = false,\n) {\n values.forEach((value) => {\n const option = document.createElement('option');\n if (value === defaultValue) {\n option.setAttribute('selected', 'selected');\n } else {\n option.setAttribute('value', String(value));\n }\n select.appendChild(option);\n });\n}\n\nexport { BaseTooltip, BaseTheme as default };\n", "import { merge } from 'lodash-es';\nimport Emitter from '../core/emitter.js';\nimport BaseTheme, { BaseTooltip } from './base.js';\nimport { Range } from '../core/selection.js';\nimport type { Bounds } from '../core/selection.js';\nimport icons from '../ui/icons.js';\nimport Quill from '../core/quill.js';\nimport type { ThemeOptions } from '../core/theme.js';\nimport type Toolbar from '../modules/toolbar.js';\nimport type { ToolbarConfig } from '../modules/toolbar.js';\n\nconst TOOLBAR_CONFIG: ToolbarConfig = [\n ['bold', 'italic', 'link'],\n [{ header: 1 }, { header: 2 }, 'blockquote'],\n];\n\nclass BubbleTooltip extends BaseTooltip {\n static TEMPLATE = [\n '',\n '
    ',\n '',\n '',\n '
    ',\n ].join('');\n\n constructor(quill: Quill, bounds?: HTMLElement) {\n super(quill, bounds);\n this.quill.on(\n Emitter.events.EDITOR_CHANGE,\n (type, range, oldRange, source) => {\n if (type !== Emitter.events.SELECTION_CHANGE) return;\n if (\n range != null &&\n range.length > 0 &&\n source === Emitter.sources.USER\n ) {\n this.show();\n // Lock our width so we will expand beyond our offsetParent boundaries\n this.root.style.left = '0px';\n this.root.style.width = '';\n this.root.style.width = `${this.root.offsetWidth}px`;\n const lines = this.quill.getLines(range.index, range.length);\n if (lines.length === 1) {\n const bounds = this.quill.getBounds(range);\n if (bounds != null) {\n this.position(bounds);\n }\n } else {\n const lastLine = lines[lines.length - 1];\n const index = this.quill.getIndex(lastLine);\n const length = Math.min(\n lastLine.length() - 1,\n range.index + range.length - index,\n );\n const indexBounds = this.quill.getBounds(new Range(index, length));\n if (indexBounds != null) {\n this.position(indexBounds);\n }\n }\n } else if (\n document.activeElement !== this.textbox &&\n this.quill.hasFocus()\n ) {\n this.hide();\n }\n },\n );\n }\n\n listen() {\n super.listen();\n // @ts-expect-error Fix me later\n this.root.querySelector('.ql-close').addEventListener('click', () => {\n this.root.classList.remove('ql-editing');\n });\n this.quill.on(Emitter.events.SCROLL_OPTIMIZE, () => {\n // Let selection be restored by toolbar handlers before repositioning\n setTimeout(() => {\n if (this.root.classList.contains('ql-hidden')) return;\n const range = this.quill.getSelection();\n if (range != null) {\n const bounds = this.quill.getBounds(range);\n if (bounds != null) {\n this.position(bounds);\n }\n }\n }, 1);\n });\n }\n\n cancel() {\n this.show();\n }\n\n position(reference: Bounds) {\n const shift = super.position(reference);\n const arrow = this.root.querySelector('.ql-tooltip-arrow');\n // @ts-expect-error\n arrow.style.marginLeft = '';\n if (shift !== 0) {\n // @ts-expect-error\n arrow.style.marginLeft = `${-1 * shift - arrow.offsetWidth / 2}px`;\n }\n return shift;\n }\n}\n\nclass BubbleTheme extends BaseTheme {\n tooltip: BubbleTooltip;\n\n constructor(quill: Quill, options: ThemeOptions) {\n if (\n options.modules.toolbar != null &&\n options.modules.toolbar.container == null\n ) {\n options.modules.toolbar.container = TOOLBAR_CONFIG;\n }\n super(quill, options);\n this.quill.container.classList.add('ql-bubble');\n }\n\n extendToolbar(toolbar: Toolbar) {\n // @ts-expect-error\n this.tooltip = new BubbleTooltip(this.quill, this.options.bounds);\n if (toolbar.container != null) {\n this.tooltip.root.appendChild(toolbar.container);\n this.buildButtons(toolbar.container.querySelectorAll('button'), icons);\n this.buildPickers(toolbar.container.querySelectorAll('select'), icons);\n }\n }\n}\nBubbleTheme.DEFAULTS = merge({}, BaseTheme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n link(value: string) {\n if (!value) {\n this.quill.format('link', false, Quill.sources.USER);\n } else {\n // @ts-expect-error\n this.quill.theme.tooltip.edit();\n }\n },\n },\n },\n },\n} satisfies ThemeOptions);\n\nexport { BubbleTooltip, BubbleTheme as default };\n", "import { merge } from 'lodash-es';\nimport Emitter from '../core/emitter.js';\nimport BaseTheme, { BaseTooltip } from './base.js';\nimport LinkBlot from '../formats/link.js';\nimport { Range } from '../core/selection.js';\nimport icons from '../ui/icons.js';\nimport Quill from '../core/quill.js';\nimport type { Context } from '../modules/keyboard.js';\nimport type Toolbar from '../modules/toolbar.js';\nimport type { ToolbarConfig } from '../modules/toolbar.js';\nimport type { ThemeOptions } from '../core/theme.js';\n\nconst TOOLBAR_CONFIG: ToolbarConfig = [\n [{ header: ['1', '2', '3', false] }],\n ['bold', 'italic', 'underline', 'link'],\n [{ list: 'ordered' }, { list: 'bullet' }],\n ['clean'],\n];\n\nclass SnowTooltip extends BaseTooltip {\n static TEMPLATE = [\n '',\n '',\n '',\n '',\n ].join('');\n\n preview = this.root.querySelector('a.ql-preview');\n\n listen() {\n super.listen();\n // @ts-expect-error Fix me later\n this.root\n .querySelector('a.ql-action')\n .addEventListener('click', (event) => {\n if (this.root.classList.contains('ql-editing')) {\n this.save();\n } else {\n // @ts-expect-error Fix me later\n this.edit('link', this.preview.textContent);\n }\n event.preventDefault();\n });\n // @ts-expect-error Fix me later\n this.root\n .querySelector('a.ql-remove')\n .addEventListener('click', (event) => {\n if (this.linkRange != null) {\n const range = this.linkRange;\n this.restoreFocus();\n this.quill.formatText(range, 'link', false, Emitter.sources.USER);\n delete this.linkRange;\n }\n event.preventDefault();\n this.hide();\n });\n this.quill.on(\n Emitter.events.SELECTION_CHANGE,\n (range, oldRange, source) => {\n if (range == null) return;\n if (range.length === 0 && source === Emitter.sources.USER) {\n const [link, offset] = this.quill.scroll.descendant(\n LinkBlot,\n range.index,\n );\n if (link != null) {\n this.linkRange = new Range(range.index - offset, link.length());\n const preview = LinkBlot.formats(link.domNode);\n // @ts-expect-error Fix me later\n this.preview.textContent = preview;\n // @ts-expect-error Fix me later\n this.preview.setAttribute('href', preview);\n this.show();\n const bounds = this.quill.getBounds(this.linkRange);\n if (bounds != null) {\n this.position(bounds);\n }\n return;\n }\n } else {\n delete this.linkRange;\n }\n this.hide();\n },\n );\n }\n\n show() {\n super.show();\n this.root.removeAttribute('data-mode');\n }\n}\n\nclass SnowTheme extends BaseTheme {\n constructor(quill: Quill, options: ThemeOptions) {\n if (\n options.modules.toolbar != null &&\n options.modules.toolbar.container == null\n ) {\n options.modules.toolbar.container = TOOLBAR_CONFIG;\n }\n super(quill, options);\n this.quill.container.classList.add('ql-snow');\n }\n\n extendToolbar(toolbar: Toolbar) {\n if (toolbar.container != null) {\n toolbar.container.classList.add('ql-snow');\n this.buildButtons(toolbar.container.querySelectorAll('button'), icons);\n this.buildPickers(toolbar.container.querySelectorAll('select'), icons);\n // @ts-expect-error\n this.tooltip = new SnowTooltip(this.quill, this.options.bounds);\n if (toolbar.container.querySelector('.ql-link')) {\n this.quill.keyboard.addBinding(\n { key: 'k', shortKey: true },\n (_range: Range, context: Context) => {\n toolbar.handlers.link.call(toolbar, !context.format.link);\n },\n );\n }\n }\n }\n}\nSnowTheme.DEFAULTS = merge({}, BaseTheme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n link(value: string) {\n if (value) {\n const range = this.quill.getSelection();\n if (range == null || range.length === 0) return;\n let preview = this.quill.getText(range);\n if (\n /^\\S+@\\S+\\.\\S+$/.test(preview) &&\n preview.indexOf('mailto:') !== 0\n ) {\n preview = `mailto:${preview}`;\n }\n // @ts-expect-error\n const { tooltip } = this.quill.theme;\n tooltip.edit('link', preview);\n } else {\n this.quill.format('link', false, Quill.sources.USER);\n }\n },\n },\n },\n },\n} satisfies ThemeOptions);\n\nexport default SnowTheme;\n", "import Quill, { Parchment, Range } from './core.js';\nimport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n} from './core.js';\n\nimport { AlignClass, AlignStyle } from './formats/align.js';\nimport {\n DirectionAttribute,\n DirectionClass,\n DirectionStyle,\n} from './formats/direction.js';\nimport Indent from './formats/indent.js';\n\nimport Blockquote from './formats/blockquote.js';\nimport Header from './formats/header.js';\nimport List from './formats/list.js';\n\nimport { BackgroundClass, BackgroundStyle } from './formats/background.js';\nimport { ColorClass, ColorStyle } from './formats/color.js';\nimport { FontClass, FontStyle } from './formats/font.js';\nimport { SizeClass, SizeStyle } from './formats/size.js';\n\nimport Bold from './formats/bold.js';\nimport Italic from './formats/italic.js';\nimport Link from './formats/link.js';\nimport Script from './formats/script.js';\nimport Strike from './formats/strike.js';\nimport Underline from './formats/underline.js';\n\nimport Formula from './formats/formula.js';\nimport Image from './formats/image.js';\nimport Video from './formats/video.js';\n\nimport CodeBlock, { Code as InlineCode } from './formats/code.js';\n\nimport Syntax from './modules/syntax.js';\nimport Table from './modules/table.js';\nimport Toolbar from './modules/toolbar.js';\n\nimport Icons from './ui/icons.js';\nimport Picker from './ui/picker.js';\nimport ColorPicker from './ui/color-picker.js';\nimport IconPicker from './ui/icon-picker.js';\nimport Tooltip from './ui/tooltip.js';\n\nimport BubbleTheme from './themes/bubble.js';\nimport SnowTheme from './themes/snow.js';\n\nQuill.register(\n {\n 'attributors/attribute/direction': DirectionAttribute,\n\n 'attributors/class/align': AlignClass,\n 'attributors/class/background': BackgroundClass,\n 'attributors/class/color': ColorClass,\n 'attributors/class/direction': DirectionClass,\n 'attributors/class/font': FontClass,\n 'attributors/class/size': SizeClass,\n\n 'attributors/style/align': AlignStyle,\n 'attributors/style/background': BackgroundStyle,\n 'attributors/style/color': ColorStyle,\n 'attributors/style/direction': DirectionStyle,\n 'attributors/style/font': FontStyle,\n 'attributors/style/size': SizeStyle,\n },\n true,\n);\n\nQuill.register(\n {\n 'formats/align': AlignClass,\n 'formats/direction': DirectionClass,\n 'formats/indent': Indent,\n\n 'formats/background': BackgroundStyle,\n 'formats/color': ColorStyle,\n 'formats/font': FontClass,\n 'formats/size': SizeClass,\n\n 'formats/blockquote': Blockquote,\n 'formats/code-block': CodeBlock,\n 'formats/header': Header,\n 'formats/list': List,\n\n 'formats/bold': Bold,\n 'formats/code': InlineCode,\n 'formats/italic': Italic,\n 'formats/link': Link,\n 'formats/script': Script,\n 'formats/strike': Strike,\n 'formats/underline': Underline,\n\n 'formats/formula': Formula,\n 'formats/image': Image,\n 'formats/video': Video,\n\n 'modules/syntax': Syntax,\n 'modules/table': Table,\n 'modules/toolbar': Toolbar,\n\n 'themes/bubble': BubbleTheme,\n 'themes/snow': SnowTheme,\n\n 'ui/icons': Icons,\n 'ui/picker': Picker,\n 'ui/icon-picker': IconPicker,\n 'ui/color-picker': ColorPicker,\n 'ui/tooltip': Tooltip,\n },\n true,\n);\n\nexport { Module } from './core.js';\nexport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n};\nexport { Parchment, Range };\n\nexport default Quill;\n", "/*! For license information please see quill-cursors.js.LICENSE.txt */\n!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define([],e):\"object\"==typeof exports?exports.QuillCursors=e():t.QuillCursors=e()}(self,(()=>(()=>{var t={582:(t,e,r)=>{\"use strict\";r.d(e,{Z:()=>s});var n=r(81),i=r.n(n),o=r(645),a=r.n(o)()(i());a.push([t.id,\".ql-container{position:relative;overflow:hidden}@media(pointer: coarse){.ql-cursor-caret-container{z-index:-1}}.ql-cursor.hidden{display:none}.ql-cursor .ql-cursor-caret-container,.ql-cursor .ql-cursor-flag{position:absolute}.ql-cursor .ql-cursor-flag{z-index:1;transform:translate3d(-1px, -100%, 0);opacity:0;visibility:hidden;color:#fff;padding-bottom:2px;border-radius:0 3px 3px 0}.ql-cursor .ql-cursor-flag.flag-flipped{border-radius:3px 0 0 3px;transform:translate3d(calc(-100% + 1px ), -100%, 0)}@media screen{.ql-cursor .ql-cursor-flag{transition:opacity 0ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 0ms,visibility 0ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 0ms}}.ql-cursor .ql-cursor-flag .ql-cursor-name{margin-left:5px;margin-right:5px;display:inline-block;margin-top:-2px;white-space:nowrap}.ql-cursor .ql-cursor-flag.no-delay[style]{transition-delay:unset !important}.ql-cursor .ql-cursor-caret-container{cursor:text;margin-left:-9px;padding:0 9px}.ql-cursor .ql-cursor-caret-container.hover+.ql-cursor-flag{opacity:1;visibility:visible;transition:none}.ql-cursor .ql-cursor-caret-container.no-pointer{pointer-events:none}.ql-cursor .ql-cursor-caret-container .ql-cursor-caret{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background-color:attr(data-color)}.ql-cursor .ql-cursor-selection-block{position:absolute;pointer-events:none}\",\"\"]);const s=a},645:t=>{\"use strict\";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var r=\"\",n=void 0!==e[5];return e[4]&&(r+=\"@supports (\".concat(e[4],\") {\")),e[2]&&(r+=\"@media \".concat(e[2],\" {\")),n&&(r+=\"@layer\".concat(e[5].length>0?\" \".concat(e[5]):\"\",\" {\")),r+=t(e),n&&(r+=\"}\"),e[2]&&(r+=\"}\"),e[4]&&(r+=\"}\"),r})).join(\"\")},e.i=function(t,r,n,i,o){\"string\"==typeof t&&(t=[[null,t,void 0]]);var a={};if(n)for(var s=0;s0?\" \".concat(l[5]):\"\",\" {\").concat(l[1],\"}\")),l[5]=o),r&&(l[2]?(l[1]=\"@media \".concat(l[2],\" {\").concat(l[1],\"}\"),l[2]=r):l[2]=r),i&&(l[4]?(l[1]=\"@supports (\".concat(l[4],\") {\").concat(l[1],\"}\"),l[4]=i):l[4]=\"\".concat(i)),e.push(l))}},e}},81:t=>{\"use strict\";t.exports=function(t){return t[1]}},529:t=>{var e=-1;function r(t,s,u,c){if(t===s)return t?[[0,t]]:[];if(null!=u){var l=function(t,e,r){var n=\"number\"==typeof r?{index:r,length:0}:r.oldRange,i=\"number\"==typeof r?null:r.newRange,o=t.length,a=e.length;if(0===n.length&&(null===i||0===i.length)){var s=n.index,u=t.slice(0,s),c=t.slice(s),l=i?i.index:null,h=s+a-o;if((null===l||l===h)&&!(h<0||h>a)){var d=e.slice(0,h);if((_=e.slice(h))===c){var p=Math.min(s,h);if((b=u.slice(0,p))===(m=d.slice(0,p)))return f(b,u.slice(p),d.slice(p),c)}}if(null===l||l===s){var g=s,_=(d=e.slice(0,g),e.slice(g));if(d===u){var v=Math.min(o-g,a-g);if((y=c.slice(c.length-v))===(A=_.slice(_.length-v)))return f(u,c.slice(0,c.length-v),_.slice(0,_.length-v),y)}}}if(n.length>0&&i&&0===i.length){var b=t.slice(0,n.index),y=t.slice(n.index+n.length);if(!(a<(p=b.length)+(v=y.length))){var m=e.slice(0,p),A=e.slice(a-v);if(b===m&&y===A)return f(b,t.slice(p,o-v),e.slice(p,a-v),y)}}return null}(t,s,u);if(l)return l}var h=i(t,s),d=t.substring(0,h);h=o(t=t.substring(h),s=s.substring(h));var p=t.substring(t.length-h),g=function(t,a){var s;if(!t)return[[1,a]];if(!a)return[[e,t]];var u=t.length>a.length?t:a,c=t.length>a.length?a:t,l=u.indexOf(c);if(-1!==l)return s=[[1,u.substring(0,l)],[0,c],[1,u.substring(l+c.length)]],t.length>a.length&&(s[0][0]=s[2][0]=e),s;if(1===c.length)return[[e,t],[1,a]];var f=function(t,e){var r=t.length>e.length?t:e,n=t.length>e.length?e:t;if(r.length<4||2*n.length=t.length?[n,a,s,u,f]:null}var s,u,c,l,f,h=a(r,n,Math.ceil(r.length/4)),d=a(r,n,Math.ceil(r.length/2));return h||d?(s=d?h&&h[4].length>d[4].length?h:d:h,t.length>e.length?(u=s[0],c=s[1],l=s[2],f=s[3]):(l=s[0],f=s[1],u=s[2],c=s[3]),[u,c,l,f,s[4]]):null}(t,a);if(f){var h=f[0],d=f[1],p=f[2],g=f[3],_=f[4],v=r(h,p),b=r(d,g);return v.concat([[0,_]],b)}return function(t,r){for(var i=t.length,o=r.length,a=Math.ceil((i+o)/2),s=a,u=2*a,c=new Array(u),l=new Array(u),f=0;fi)g+=2;else if(A>o)p+=2;else if(d&&(w=s+h-y)>=0&&w=(C=i-l[w]))return n(t,r,S,A)}for(var x=-b+_;x<=b-v;x+=2){for(var C,w=s+x,E=(C=x===-b||x!==b&&l[w-1]i)v+=2;else if(E>o)_+=2;else if(!d){var S;if((m=s+h-x)>=0&&m=(C=i-C))return n(t,r,S,A)}}}return[[e,t],[1,r]]}(t,a)}(t=t.substring(0,t.length-h),s=s.substring(0,s.length-h));return d&&g.unshift([0,d]),p&&g.push([0,p]),a(g,c),g}function n(t,e,n,i){var o=t.substring(0,n),a=e.substring(0,i),s=t.substring(n),u=e.substring(i),c=r(o,a),l=r(s,u);return c.concat(l)}function i(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;for(var r=0,n=Math.min(t.length,e.length),i=n,o=0;r=0&&l(t[p][1])){var g=t[p][1].slice(-1);if(t[p][1]=t[p][1].slice(0,-1),h=g+h,d=g+d,!t[p][1]){t.splice(p,1),s--;var _=p-1;t[_]&&1===t[_][0]&&(f++,d=t[_][1]+d,_--),t[_]&&t[_][0]===e&&(u++,h=t[_][1]+h,_--),p=_}}c(t[s][1])&&(g=t[s][1].charAt(0),t[s][1]=t[s][1].slice(1),h+=g,d+=g)}if(s0||d.length>0){h.length>0&&d.length>0&&(0!==(n=i(d,h))&&(p>=0?t[p][1]+=d.substring(0,n):(t.splice(0,0,[0,d.substring(0,n)]),s++),d=d.substring(n),h=h.substring(n)),0!==(n=o(d,h))&&(t[s][1]=d.substring(d.length-n)+t[s][1],d=d.substring(0,d.length-n),h=h.substring(0,h.length-n)));var v=f+u;0===h.length&&0===d.length?(t.splice(s-v,v),s-=v):0===h.length?(t.splice(s-v,v,[1,d]),s=s-v+1):0===d.length?(t.splice(s-v,v,[e,h]),s=s-v+1):(t.splice(s-v,v,[e,h],[1,d]),s=s-v+2)}0!==s&&0===t[s-1][0]?(t[s-1][1]+=t[s][1],t.splice(s,1)):s++,f=0,u=0,h=\"\",d=\"\"}\"\"===t[t.length-1][1]&&t.pop();var b=!1;for(s=1;s=55296&&t<=56319}function u(t){return t>=56320&&t<=57343}function c(t){return u(t.charCodeAt(0))}function l(t){return s(t.charCodeAt(t.length-1))}function f(t,r,n,i){return l(t)||c(i)?null:function(t){for(var e=[],r=0;r0&&e.push(t[r]);return e}([[0,t],[e,r],[1,n],[0,i]])}function h(t,e,n){return r(t,e,n,!0)}h.INSERT=1,h.DELETE=e,h.EQUAL=0,t.exports=h},465:(t,e,r)=>{t=r.nmd(t);var n=\"__lodash_hash_undefined__\",i=9007199254740991,o=\"[object Arguments]\",a=\"[object Boolean]\",s=\"[object Date]\",u=\"[object Function]\",c=\"[object GeneratorFunction]\",l=\"[object Map]\",f=\"[object Number]\",h=\"[object Object]\",d=\"[object Promise]\",p=\"[object RegExp]\",g=\"[object Set]\",_=\"[object String]\",v=\"[object Symbol]\",b=\"[object WeakMap]\",y=\"[object ArrayBuffer]\",m=\"[object DataView]\",A=\"[object Float32Array]\",x=\"[object Float64Array]\",C=\"[object Int8Array]\",w=\"[object Int16Array]\",E=\"[object Int32Array]\",S=\"[object Uint8Array]\",M=\"[object Uint8ClampedArray]\",O=\"[object Uint16Array]\",j=\"[object Uint32Array]\",L=/\\w*$/,k=/^\\[object .+?Constructor\\]$/,T=/^(?:0|[1-9]\\d*)$/,R={};R[o]=R[\"[object Array]\"]=R[y]=R[m]=R[a]=R[s]=R[A]=R[x]=R[C]=R[w]=R[E]=R[l]=R[f]=R[h]=R[p]=R[g]=R[_]=R[v]=R[S]=R[M]=R[O]=R[j]=!0,R[\"[object Error]\"]=R[u]=R[b]=!1;var N=\"object\"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,q=\"object\"==typeof self&&self&&self.Object===Object&&self,D=N||q||Function(\"return this\")(),F=e&&!e.nodeType&&e,I=F&&t&&!t.nodeType&&t,P=I&&I.exports===F;function B(t,e){return t.set(e[0],e[1]),t}function z(t,e){return t.add(e),t}function H(t,e,r,n){var i=-1,o=t?t.length:0;for(n&&o&&(r=t[++i]);++i-1},Mt.prototype.set=function(t,e){var r=this.__data__,n=kt(r,t);return n<0?r.push([t,e]):r[n][1]=e,this},Ot.prototype.clear=function(){this.__data__={hash:new St,map:new(pt||Mt),string:new St}},Ot.prototype.delete=function(t){return qt(this,t).delete(t)},Ot.prototype.get=function(t){return qt(this,t).get(t)},Ot.prototype.has=function(t){return qt(this,t).has(t)},Ot.prototype.set=function(t,e){return qt(this,t).set(t,e),this},jt.prototype.clear=function(){this.__data__=new Mt},jt.prototype.delete=function(t){return this.__data__.delete(t)},jt.prototype.get=function(t){return this.__data__.get(t)},jt.prototype.has=function(t){return this.__data__.has(t)},jt.prototype.set=function(t,e){var r=this.__data__;if(r instanceof Mt){var n=r.__data__;if(!pt||n.length<199)return n.push([t,e]),this;r=this.__data__=new Ot(n)}return r.set(t,e),this};var Ft=lt?$(lt,Object):function(){return[]},It=function(t){return et.call(t)};function Pt(t,e){return!!(e=null==e?i:e)&&(\"number\"==typeof t||T.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=i}(t.length)&&!Vt(t)}var $t=ft||function(){return!1};function Vt(t){var e=Wt(t)?et.call(t):\"\";return e==u||e==c}function Wt(t){var e=typeof t;return!!t&&(\"object\"==e||\"function\"==e)}function Xt(t){return Gt(t)?function(t,e){var r=Ut(t)||function(t){return function(t){return function(t){return!!t&&\"object\"==typeof t}(t)&&Gt(t)}(t)&&tt.call(t,\"callee\")&&(!ut.call(t,\"callee\")||et.call(t)==o)}(t)?function(t,e){for(var r=-1,n=Array(t);++r{t=r.nmd(t);var n=\"__lodash_hash_undefined__\",i=9007199254740991,o=\"[object Arguments]\",a=\"[object Array]\",s=\"[object Boolean]\",u=\"[object Date]\",c=\"[object Error]\",l=\"[object Function]\",f=\"[object Map]\",h=\"[object Number]\",d=\"[object Object]\",p=\"[object Promise]\",g=\"[object RegExp]\",_=\"[object Set]\",v=\"[object String]\",b=\"[object WeakMap]\",y=\"[object ArrayBuffer]\",m=\"[object DataView]\",A=/^\\[object .+?Constructor\\]$/,x=/^(?:0|[1-9]\\d*)$/,C={};C[\"[object Float32Array]\"]=C[\"[object Float64Array]\"]=C[\"[object Int8Array]\"]=C[\"[object Int16Array]\"]=C[\"[object Int32Array]\"]=C[\"[object Uint8Array]\"]=C[\"[object Uint8ClampedArray]\"]=C[\"[object Uint16Array]\"]=C[\"[object Uint32Array]\"]=!0,C[o]=C[a]=C[y]=C[s]=C[m]=C[u]=C[c]=C[l]=C[f]=C[h]=C[d]=C[g]=C[_]=C[v]=C[b]=!1;var w=\"object\"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,E=\"object\"==typeof self&&self&&self.Object===Object&&self,S=w||E||Function(\"return this\")(),M=e&&!e.nodeType&&e,O=M&&t&&!t.nodeType&&t,j=O&&O.exports===M,L=j&&w.process,k=function(){try{return L&&L.binding&&L.binding(\"util\")}catch(t){}}(),T=k&&k.isTypedArray;function R(t,e){for(var r=-1,n=null==t?0:t.length;++rs))return!1;var c=o.get(t);if(c&&o.get(e))return c==e;var l=-1,f=!0,h=2&r?new yt:void 0;for(o.set(t,e),o.set(e,t);++l-1},vt.prototype.set=function(t,e){var r=this.__data__,n=At(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this},bt.prototype.clear=function(){this.size=0,this.__data__={hash:new _t,map:new(it||vt),string:new _t}},bt.prototype.delete=function(t){var e=Mt(this,t).delete(t);return this.size-=e?1:0,e},bt.prototype.get=function(t){return Mt(this,t).get(t)},bt.prototype.has=function(t){return Mt(this,t).has(t)},bt.prototype.set=function(t,e){var r=Mt(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this},yt.prototype.add=yt.prototype.push=function(t){return this.__data__.set(t,n),this},yt.prototype.has=function(t){return this.__data__.has(t)},mt.prototype.clear=function(){this.__data__=new vt,this.size=0},mt.prototype.delete=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r},mt.prototype.get=function(t){return this.__data__.get(t)},mt.prototype.has=function(t){return this.__data__.has(t)},mt.prototype.set=function(t,e){var r=this.__data__;if(r instanceof vt){var n=r.__data__;if(!it||n.length<199)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new bt(n)}return r.set(t,e),this.size=r.size,this};var jt=tt?function(t){return null==t?[]:(t=Object(t),function(e,r){for(var n=-1,i=null==e?0:e.length,o=0,a=[];++n-1&&t%1==0&&t-1&&t%1==0&&t<=i}function Pt(t){var e=typeof t;return null!=t&&(\"object\"==e||\"function\"==e)}function Bt(t){return null!=t&&\"object\"==typeof t}var zt=T?function(t){return function(e){return t(e)}}(T):function(t){return Bt(t)&&It(t.length)&&!!C[xt(t)]};function Ht(t){return null!=(e=t)&&It(e.length)&&!Ft(e)?function(t,e){var r=qt(t),n=!r&&Nt(t),i=!r&&!n&&Dt(t),o=!r&&!n&&!i&&zt(t),a=r||n||i||o,s=a?function(t,e){for(var r=-1,n=Array(t);++r0?n:void 0},t.diff=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),\"object\"!=typeof t&&(t={}),\"object\"!=typeof e&&(e={});var r=Object.keys(t).concat(Object.keys(e)).reduce((function(r,n){return a.default(t[n],e[n])||(r[n]=void 0===e[n]?null:e[n]),r}),{});return Object.keys(r).length>0?r:void 0},t.invert=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),t=t||{};var r=Object.keys(e).reduce((function(r,n){return e[n]!==t[n]&&void 0!==t[n]&&(r[n]=e[n]),r}),{});return Object.keys(t).reduce((function(r,n){return t[n]!==e[n]&&void 0===e[n]&&(r[n]=null),r}),r)},t.transform=function(t,e,r){if(void 0===r&&(r=!1),\"object\"!=typeof t)return e;if(\"object\"==typeof e){if(!r)return e;var n=Object.keys(e).reduce((function(r,n){return void 0===t[n]&&(r[n]=e[n]),r}),{});return Object.keys(n).length>0?n:void 0}}}(i||(i={})),e.default=i},895:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},i=n(r(529)),o=n(r(465)),a=n(r(307)),s=n(r(210)),u=n(r(430)),c=String.fromCharCode(0),l=function(){function t(t){Array.isArray(t)?this.ops=t:null!=t&&Array.isArray(t.ops)?this.ops=t.ops:this.ops=[]}return t.prototype.insert=function(t,e){var r={};return\"string\"==typeof t&&0===t.length?this:(r.insert=t,null!=e&&\"object\"==typeof e&&Object.keys(e).length>0&&(r.attributes=e),this.push(r))},t.prototype.delete=function(t){return t<=0?this:this.push({delete:t})},t.prototype.retain=function(t,e){if(t<=0)return this;var r={retain:t};return null!=e&&\"object\"==typeof e&&Object.keys(e).length>0&&(r.attributes=e),this.push(r)},t.prototype.push=function(t){var e=this.ops.length,r=this.ops[e-1];if(t=o.default(t),\"object\"==typeof r){if(\"number\"==typeof t.delete&&\"number\"==typeof r.delete)return this.ops[e-1]={delete:r.delete+t.delete},this;if(\"number\"==typeof r.delete&&null!=t.insert&&(e-=1,\"object\"!=typeof(r=this.ops[e-1])))return this.ops.unshift(t),this;if(a.default(t.attributes,r.attributes)){if(\"string\"==typeof t.insert&&\"string\"==typeof r.insert)return this.ops[e-1]={insert:r.insert+t.insert},\"object\"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this;if(\"number\"==typeof t.retain&&\"number\"==typeof r.retain)return this.ops[e-1]={retain:r.retain+t.retain},\"object\"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this}}return e===this.ops.length?this.ops.push(t):this.ops.splice(e,0,t),this},t.prototype.chop=function(){var t=this.ops[this.ops.length-1];return t&&t.retain&&!t.attributes&&this.ops.pop(),this},t.prototype.filter=function(t){return this.ops.filter(t)},t.prototype.forEach=function(t){this.ops.forEach(t)},t.prototype.map=function(t){return this.ops.map(t)},t.prototype.partition=function(t){var e=[],r=[];return this.forEach((function(n){(t(n)?e:r).push(n)})),[e,r]},t.prototype.reduce=function(t,e){return this.ops.reduce(t,e)},t.prototype.changeLength=function(){return this.reduce((function(t,e){return e.insert?t+u.default.length(e):e.delete?t-e.delete:t}),0)},t.prototype.length=function(){return this.reduce((function(t,e){return t+u.default.length(e)}),0)},t.prototype.slice=function(e,r){void 0===e&&(e=0),void 0===r&&(r=1/0);for(var n=[],i=u.default.iterator(this.ops),o=0;o0&&n.next(o.retain-c)}for(var l=new t(i);r.hasNext()||n.hasNext();)if(\"insert\"===n.peekType())l.push(n.next());else if(\"delete\"===r.peekType())l.push(r.next());else{var f=Math.min(r.peekLength(),n.peekLength()),h=r.next(f),d=n.next(f);if(\"number\"==typeof d.retain){var p={};\"number\"==typeof h.retain?p.retain=f:p.insert=h.insert;var g=s.default.compose(h.attributes,d.attributes,\"number\"==typeof h.retain);if(g&&(p.attributes=g),l.push(p),!n.hasNext()&&a.default(l.ops[l.ops.length-1],p)){var _=new t(r.rest());return l.concat(_).chop()}}else\"number\"==typeof d.delete&&\"number\"==typeof h.retain&&l.push(d)}return l.chop()},t.prototype.concat=function(e){var r=new t(this.ops.slice());return e.ops.length>0&&(r.push(e.ops[0]),r.ops=r.ops.concat(e.ops.slice(1))),r},t.prototype.diff=function(e,r){if(this.ops===e.ops)return new t;var n=[this,e].map((function(t){return t.map((function(r){if(null!=r.insert)return\"string\"==typeof r.insert?r.insert:c;throw new Error(\"diff() called \"+(t===e?\"on\":\"with\")+\" non-document\")})).join(\"\")})),o=new t,l=i.default(n[0],n[1],r),f=u.default.iterator(this.ops),h=u.default.iterator(e.ops);return l.forEach((function(t){for(var e=t[1].length;e>0;){var r=0;switch(t[0]){case i.default.INSERT:r=Math.min(h.peekLength(),e),o.push(h.next(r));break;case i.default.DELETE:r=Math.min(e,f.peekLength()),f.next(r),o.delete(r);break;case i.default.EQUAL:r=Math.min(f.peekLength(),h.peekLength(),e);var n=f.next(r),u=h.next(r);a.default(n.insert,u.insert)?o.retain(r,s.default.diff(n.attributes,u.attributes)):o.push(u).delete(r)}e-=r}})),o.chop()},t.prototype.eachLine=function(e,r){void 0===r&&(r=\"\\n\");for(var n=u.default.iterator(this.ops),i=new t,o=0;n.hasNext();){if(\"insert\"!==n.peekType())return;var a=n.peek(),s=u.default.length(a)-n.peekLength(),c=\"string\"==typeof a.insert?a.insert.indexOf(r,s)-s:-1;if(c<0)i.push(n.next());else if(c>0)i.push(n.next(c));else{if(!1===e(i,n.next(1).attributes||{},o))return;o+=1,i=new t}}i.length()>0&&e(i,{},o)},t.prototype.invert=function(e){var r=new t;return this.reduce((function(t,n){if(n.insert)r.delete(u.default.length(n));else{if(n.retain&&null==n.attributes)return r.retain(n.retain),t+n.retain;if(n.delete||n.retain&&n.attributes){var i=n.delete||n.retain;return e.slice(t,t+i).forEach((function(t){n.delete?r.push(t):n.retain&&n.attributes&&r.retain(u.default.length(t),s.default.invert(n.attributes,t.attributes))})),t+i}}return t}),0),r.chop()},t.prototype.transform=function(e,r){if(void 0===r&&(r=!1),r=!!r,\"number\"==typeof e)return this.transformPosition(e,r);for(var n=e,i=u.default.iterator(this.ops),o=u.default.iterator(n.ops),a=new t;i.hasNext()||o.hasNext();)if(\"insert\"!==i.peekType()||!r&&\"insert\"===o.peekType())if(\"insert\"===o.peekType())a.push(o.next());else{var c=Math.min(i.peekLength(),o.peekLength()),l=i.next(c),f=o.next(c);if(l.delete)continue;f.delete?a.push(f):a.retain(c,s.default.transform(l.attributes,f.attributes,r))}else a.retain(u.default.length(i.next()));return a.chop()},t.prototype.transformPosition=function(t,e){void 0===e&&(e=!1),e=!!e;for(var r=u.default.iterator(this.ops),n=0;r.hasNext()&&n<=t;){var i=r.peekLength(),o=r.peekType();r.next(),\"delete\"!==o?(\"insert\"===o&&(n=n-r?(t=n-r,this.index+=1,this.offset=0):this.offset+=t,\"number\"==typeof e.delete)return{delete:t};var o={};return e.attributes&&(o.attributes=e.attributes),\"number\"==typeof e.retain?o.retain=t:\"string\"==typeof e.insert?o.insert=e.insert.substr(r,t):o.insert=e.insert,o}return{retain:1/0}},t.prototype.peek=function(){return this.ops[this.index]},t.prototype.peekLength=function(){return this.ops[this.index]?i.default.length(this.ops[this.index])-this.offset:1/0},t.prototype.peekType=function(){return this.ops[this.index]?\"number\"==typeof this.ops[this.index].delete?\"delete\":\"number\"==typeof this.ops[this.index].retain?\"retain\":\"insert\":\"retain\"},t.prototype.rest=function(){if(this.hasNext()){if(0===this.offset)return this.ops.slice(this.index);var t=this.offset,e=this.index,r=this.next(),n=this.ops.slice(this.index);return this.offset=t,this.index=e,[r].concat(n)}return[]},t}();e.default=o},430:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var i,o=n(r(977));!function(t){t.iterator=function(t){return new o.default(t)},t.length=function(t){return\"number\"==typeof t.delete?t.delete:\"number\"==typeof t.retain?t.retain:\"string\"==typeof t.insert?t.insert.length:1}}(i||(i={})),e.default=i},165:function(t,e,r){var n,i;void 0===(i=\"function\"==typeof(n=function(){var t,e={};function r(t,e,r){var n=t.getClientRects();if(2===n.length){var i=t.getBoundingClientRect();return n[e][r]=e.length)return Array.prototype.push.apply(t,e);for(;n1,t.getClientRects||(s.setEnd(o,1),t.getClientRects=t.getBoundingClientRect=2===s.getClientRects().length),!t.getBoundingClientRect){s.setEnd(s.startContainer,s.startOffset);var u=s.getBoundingClientRect();t.getBoundingClientRect=0===u.top&&0===u.left}if(document.body.removeChild(e),!t.getBoundingClientRect){var c=document.createElement(\"p\");c.style.width=\"0px\",c.style.fontSize=\"20px\",c.style.whiteSpace=\"normal\",c.style.wordBreak=\"normal\";var l=document.createTextNode(\"m mm\");c.appendChild(l),document.body.appendChild(c),s.setStart(l,1),s.setEnd(l,2),r(s,1,\"left\")?t.getBoundingClientRect=!0:(s.setStart(l,1),s.setEnd(l,3),r(s,0,\"top\")&&(t.getBoundingClientRect=!0)),document.body.removeChild(c)}var f=window.ActiveXObject&&new Function(\"/*@cc_on return @_jscript_version; @*/\")();t.ieZoom=!!f&&f<=10}return t},e.getClientRects=function(t){var e=this.isBroken();if(e.ieZoom)return n(t.getClientRects());if(!e.getClientRects)return t.getClientRects();var r=[],o=[],a=t.endContainer,s=t.endOffset,u=document.createRange();function c(t){for(var e=0;t=t.previousSibling;)e++;return e}for(;a!==t.commonAncestorContainer;)u.setStart(a,0),u.setEnd(a,s),i(o,u.getClientRects()),s=c(a),a=a.parentNode;return(u=t.cloneRange()).setEnd(a,s),i(r,u.getClientRects()),i(r,o),r},e.getBoundingClientRect=function(t){var e=this.getClientRects(t);if(0===e.length)return null;var r,i=t.getBoundingClientRect(),o=this.isBroken();if(o.ieZoom)return n(i);if(!o.getBoundingClientRect)return i;if(0===i.width&&0===i.height)return e[0];for(var a=0,s=e.length;a{\"use strict\";r.r(e),r.d(e,{default:()=>C});var n=function(){if(\"undefined\"!=typeof Map)return Map;function t(t,e){var r=-1;return t.some((function(t,n){return t[0]===e&&(r=n,!0)})),r}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,\"size\",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var r=t(this.__entries__,e),n=this.__entries__[r];return n&&n[1]},e.prototype.set=function(e,r){var n=t(this.__entries__,e);~n?this.__entries__[n][1]=r:this.__entries__.push([e,r])},e.prototype.delete=function(e){var r=this.__entries__,n=t(r,e);~n&&r.splice(n,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var r=0,n=this.__entries__;r0},t.prototype.connect_=function(){i&&!this.connected_&&(document.addEventListener(\"transitionend\",this.onTransitionEnd_),window.addEventListener(\"resize\",this.refresh),u?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(\"DOMSubtreeModified\",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){i&&this.connected_&&(document.removeEventListener(\"transitionend\",this.onTransitionEnd_),window.removeEventListener(\"resize\",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(\"DOMSubtreeModified\",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,r=void 0===e?\"\":e;s.some((function(t){return!!~r.indexOf(t)}))&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),l=function(t,e){for(var r=0,n=Object.keys(e);r0},t}(),A=\"undefined\"!=typeof WeakMap?new WeakMap:new n,x=function t(e){if(!(this instanceof t))throw new TypeError(\"Cannot call a class as a function.\");if(!arguments.length)throw new TypeError(\"1 argument required, but only 0 present.\");var r=c.getInstance(),n=new m(e,r,this);A.set(this,n)};[\"observe\",\"unobserve\",\"disconnect\"].forEach((function(t){x.prototype[t]=function(){var e;return(e=A.get(this))[t].apply(e,arguments)}}));const C=void 0!==o.ResizeObserver?o.ResizeObserver:x},413:(t,e,r)=>{\"use strict\";r.r(e),r.d(e,{default:()=>v});var n=r(379),i=r.n(n),o=r(795),a=r.n(o),s=r(569),u=r.n(s),c=r(565),l=r.n(c),f=r(216),h=r.n(f),d=r(589),p=r.n(d),g=r(582),_={};_.styleTagTransform=p(),_.setAttributes=l(),_.insert=u().bind(null,\"head\"),_.domAPI=a(),_.insertStyleElement=h(),i()(g.Z,_);const v=g.Z&&g.Z.locals?g.Z.locals:void 0},379:t=>{\"use strict\";var e=[];function r(t){for(var r=-1,n=0;n{\"use strict\";var e={};t.exports=function(t,r){var n=function(t){if(void 0===e[t]){var r=document.querySelector(t);if(window.HTMLIFrameElement&&r instanceof window.HTMLIFrameElement)try{r=r.contentDocument.head}catch(t){r=null}e[t]=r}return e[t]}(t);if(!n)throw new Error(\"Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.\");n.appendChild(r)}},216:t=>{\"use strict\";t.exports=function(t){var e=document.createElement(\"style\");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},565:(t,e,r)=>{\"use strict\";t.exports=function(t){var e=r.nc;e&&t.setAttribute(\"nonce\",e)}},795:t=>{\"use strict\";t.exports=function(t){var e=t.insertStyleElement(t);return{update:function(r){!function(t,e,r){var n=\"\";r.supports&&(n+=\"@supports (\".concat(r.supports,\") {\")),r.media&&(n+=\"@media \".concat(r.media,\" {\"));var i=void 0!==r.layer;i&&(n+=\"@layer\".concat(r.layer.length>0?\" \".concat(r.layer):\"\",\" {\")),n+=r.css,i&&(n+=\"}\"),r.media&&(n+=\"}\"),r.supports&&(n+=\"}\");var o=r.sourceMap;o&&\"undefined\"!=typeof btoa&&(n+=\"\\n/*# sourceMappingURL=data:application/json;base64,\".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o)))),\" */\")),e.styleTagTransform(n,t,e.options)}(e,t,r)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},589:t=>{\"use strict\";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}},607:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0}),e.Cursor=e.default=void 0;var i=n(r(678));e.default=i.default;var o=n(r(353));e.Cursor=o.default,r(413)},353:(t,e,r)=>{\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0});var n=r(207),i=function(){function t(t,e,r){this.id=t,this.name=e,this.color=r,this.toggleNearCursor=this.toggleNearCursor.bind(this),this._toggleOpenedCursor=this._toggleOpenedCursor.bind(this),this._setHoverState=this._setHoverState.bind(this)}return t.prototype.build=function(e){var r=document.createElement(t.CONTAINER_ELEMENT_TAG);r.classList.add(t.CURSOR_CLASS),r.id=\"ql-cursor-\".concat(this.id),r.innerHTML=e.template;var n=r.getElementsByClassName(t.SELECTION_CLASS)[0],i=r.getElementsByClassName(t.CARET_CONTAINER_CLASS)[0],o=i.getElementsByClassName(t.CARET_CLASS)[0],a=r.getElementsByClassName(t.FLAG_CLASS)[0];return a.style.backgroundColor=this.color,o.style.backgroundColor=this.color,r.getElementsByClassName(t.NAME_CLASS)[0].textContent=this.name,this._hideDelay=\"\".concat(e.hideDelayMs,\"ms\"),this._hideSpeedMs=e.hideSpeedMs,this._positionFlag=e.positionFlag,a.style.transitionDelay=this._hideDelay,a.style.transitionDuration=\"\".concat(this._hideSpeedMs,\"ms\"),this._el=r,this._selectionEl=n,this._caretEl=i,this._flagEl=a,i.addEventListener(\"mouseover\",this._setHoverState,{passive:!0}),this._el},t.prototype.show=function(){this._el.classList.remove(t.HIDDEN_CLASS)},t.prototype.hide=function(){this._el.classList.add(t.HIDDEN_CLASS)},t.prototype.remove=function(){this._el.parentNode.removeChild(this._el)},t.prototype.toggleNearCursor=function(e,r){var n=this._getCoordinates(),i=n.left,o=n.right,a=n.top,s=n.bottom,u=e>=i&&e<=o&&r>=a&&r<=s;return this._caretEl.classList.toggle(t.CONTAINER_HOVER_CLASS,u),u},t.prototype.toggleFlag=function(e){var r=this;this._caretEl.classList.toggle(t.CONTAINER_HOVER_CLASS,e)||(this._flagEl.classList.add(t.NO_DELAY_CLASS),setTimeout((function(){return r._flagEl.classList.remove(t.NO_DELAY_CLASS)}),this._hideSpeedMs))},t.prototype.updateCaret=function(t,e){this._caretEl.style.top=\"\".concat(t.top,\"px\"),this._caretEl.style.left=\"\".concat(t.left,\"px\"),this._caretEl.style.height=\"\".concat(t.height,\"px\"),this._positionFlag?this._positionFlag(this._flagEl,t,e):this._updateCaretFlag(t,e)},t.prototype.updateSelection=function(t,e){var r=this;this._clearSelection(),t=t||[],t=Array.from(t),t=this._sanitize(t),(t=this._sortByDomPosition(t)).forEach((function(t){return r._addSelection(t,e)}))},t.prototype._setHoverState=function(){document.addEventListener(\"mousemove\",this._toggleOpenedCursor,{passive:!0})},t.prototype._toggleOpenedCursor=function(e){var r=this.toggleNearCursor(e.clientX,e.clientY);this._caretEl.classList.toggle(t.CONTAINER_NO_POINTER_CLASS,r),r||document.removeEventListener(\"mousemove\",this._toggleOpenedCursor)},t.prototype._getCoordinates=function(){return this._caretEl.getBoundingClientRect()},t.prototype._updateCaretFlag=function(e,r){this._flagEl.style.width=\"\";var n=this._flagEl.getBoundingClientRect();this._flagEl.classList.remove(t.FLAG_FLIPPED_CLASS),e.left>r.width-n.width&&this._flagEl.classList.add(t.FLAG_FLIPPED_CLASS),this._flagEl.style.left=\"\".concat(e.left,\"px\"),this._flagEl.style.top=\"\".concat(e.top,\"px\"),this._flagEl.style.width=\"\".concat(Math.ceil(n.width),\"px\")},t.prototype._clearSelection=function(){this._selectionEl.innerHTML=\"\"},t.prototype._addSelection=function(t,e){var r=this._selectionBlock(t,e);this._selectionEl.appendChild(r)},t.prototype._selectionBlock=function(e,r){var i=document.createElement(t.SELECTION_ELEMENT_TAG);return i.classList.add(t.SELECTION_BLOCK_CLASS),i.style.top=\"\".concat(e.top-r.top,\"px\"),i.style.left=\"\".concat(e.left-r.left,\"px\"),i.style.width=\"\".concat(e.width,\"px\"),i.style.height=\"\".concat(e.height,\"px\"),i.style.backgroundColor=n(this.color).setAlpha(.3).toString(),i},t.prototype._sortByDomPosition=function(t){return t.sort((function(t,e){return t.top===e.top?t.left-e.left:t.top-e.top}))},t.prototype._sanitize=function(t){var e=this,r=new Set;return t.filter((function(t){if(!t.width||!t.height)return!1;var n=e._serialize(t);return!r.has(n)&&(r.add(n),!0)}))},t.prototype._serialize=function(t){return[\"top:\".concat(t.top),\"right:\".concat(t.right),\"bottom:\".concat(t.bottom),\"left:\".concat(t.left)].join(\";\")},t.CONTAINER_ELEMENT_TAG=\"SPAN\",t.SELECTION_ELEMENT_TAG=\"SPAN\",t.CURSOR_CLASS=\"ql-cursor\",t.SELECTION_CLASS=\"ql-cursor-selections\",t.SELECTION_BLOCK_CLASS=\"ql-cursor-selection-block\",t.CARET_CLASS=\"ql-cursor-caret\",t.CARET_CONTAINER_CLASS=\"ql-cursor-caret-container\",t.CONTAINER_HOVER_CLASS=\"hover\",t.CONTAINER_NO_POINTER_CLASS=\"no-pointer\",t.FLAG_CLASS=\"ql-cursor-flag\",t.FLAG_FLIPPED_CLASS=\"flag-flipped\",t.NAME_CLASS=\"ql-cursor-name\",t.HIDDEN_CLASS=\"hidden\",t.NO_DELAY_CLASS=\"no-delay\",t}();e.default=i},678:function(t,e,r){\"use strict\";var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);i&&!(\"get\"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)\"default\"!==r&&Object.prototype.hasOwnProperty.call(t,r)&&n(e,t,r);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var s=a(r(353)),u=o(r(165)),c=a(r(338)),l=a(r(33)),f=r(895),h=function(){function t(t,e){void 0===e&&(e={}),this._cursors={},this._isObserving=!1,this._handleCursorTouch=this._handleCursorTouch.bind(this),this.quill=t,this.options=this._setDefaults(e),this._container=this.quill.addContainer(this.options.containerClass),this._boundsContainer=this.options.boundsContainer||this.quill.container,this._currentSelection=this.quill.getSelection(),this._registerSelectionChangeListeners(),this._registerTextChangeListener(),this._registerDomListeners()}return t.prototype.createCursor=function(t,e,r){var n=this._cursors[t];if(!n){n=new s.default(t,e,r),this._cursors[t]=n;var i=n.build(this.options);this._container.appendChild(i)}return n},t.prototype.moveCursor=function(t,e){var r=this._cursors[t];r&&(r.range=e,this._updateCursor(r))},t.prototype.removeCursor=function(t){var e=this._cursors[t];e&&(e.remove(),delete this._cursors[t])},t.prototype.update=function(){var t=this;this.cursors().forEach((function(e){return t._updateCursor(e)}))},t.prototype.clearCursors=function(){var t=this;this.cursors().forEach((function(e){return t.removeCursor(e.id)}))},t.prototype.toggleFlag=function(t,e){var r=this._cursors[t];r&&r.toggleFlag(e)},t.prototype.cursors=function(){var t=this;return Object.keys(this._cursors).map((function(e){return t._cursors[e]}))},t.prototype._registerSelectionChangeListeners=function(){var t=this;this.quill.on(this.quill.constructor.events.SELECTION_CHANGE,(function(e){t._currentSelection=e}))},t.prototype._registerTextChangeListener=function(){var t=this;this.quill.on(this.quill.constructor.events.TEXT_CHANGE,(function(e){return t._handleTextChange(e)}))},t.prototype._registerDomListeners=function(){var t=this,e=this.quill.container.getElementsByClassName(\"ql-editor\")[0];e.addEventListener(\"scroll\",(function(){return t.update()}),{passive:!0}),e.addEventListener(\"touchstart\",this._handleCursorTouch,{passive:!0})},t.prototype._handleCursorTouch=function(t){var e=this;this.cursors().forEach((function(r){r.toggleNearCursor(t.pageX,t.pageY),setTimeout((function(){return r.toggleFlag(!1)}),e.options.hideDelayMs)}))},t.prototype._registerResizeObserver=function(){var t=this;if(!this._isObserving){var e=this.quill.container.getElementsByClassName(\"ql-editor\")[0],r=new l.default((function(e){if(!e[0].target.isConnected)return r.disconnect(),void(t._isObserving=!1);t.update()}));r.observe(e),this._isObserving=!0}},t.prototype._updateCursor=function(t){if(this._registerResizeObserver(),!t.range)return t.hide();var e=this._indexWithinQuillBounds(t.range.index),r=this._indexWithinQuillBounds(t.range.index+t.range.length),n=this.quill.getLeaf(e),i=this.quill.getLeaf(r);if(!this._leafIsValid(n)||!this._leafIsValid(i))return t.hide();t.show();var o=this._boundsContainer.getBoundingClientRect(),a=this.quill.getBounds(r);t.updateCaret(a,o);var s=this._lineRanges(t,n,i).reduce((function(t,e){return t.concat(Array.from(u.getClientRects(e)))}),[]);t.updateSelection(s,o)},t.prototype._indexWithinQuillBounds=function(t){var e=this.quill.getLength(),r=e?e-1:0;return t=Math.max(t,0),Math.min(t,r)},t.prototype._leafIsValid=function(t){return t&&t[0]&&t[0].domNode&&t[1]>=0},t.prototype._handleTextChange=function(t){var e=this;window.setTimeout((function(){e.options.transformOnTextChange&&e._transformCursors(t),e.options.selectionChangeSource&&(e._emitSelection(),e.update())}))},t.prototype._emitSelection=function(){this.quill.emitter.emit(this.quill.constructor.events.SELECTION_CHANGE,this.quill.getSelection(),this._currentSelection,this.options.selectionChangeSource)},t.prototype._setDefaults=function(e){return(e=Object.assign({},e)).template||(e.template=t.DEFAULTS.template),e.containerClass||(e.containerClass=t.DEFAULTS.containerClass),null!==e.selectionChangeSource&&(e.selectionChangeSource||(e.selectionChangeSource=t.DEFAULTS.selectionChangeSource)),e.hideDelayMs=Number.isInteger(e.hideDelayMs)?e.hideDelayMs:t.DEFAULTS.hideDelayMs,e.hideSpeedMs=Number.isInteger(e.hideSpeedMs)?e.hideSpeedMs:t.DEFAULTS.hideSpeedMs,e.transformOnTextChange=!!e.transformOnTextChange,e},t.prototype._lineRanges=function(t,e,r){var n=this.quill.getLines(t.range);return n.reduce((function(t,i,o){if(!i.children){var a=document.createRange();return a.selectNode(i.domNode),t.concat(a)}var s=0===o?e:i.path(0).pop(),u=s[0],c=s[1],l=o===n.length-1?r:i.path(i.length()-1).pop(),f=l[0],h=l[1],d=document.createRange();return u.domNode.nodeType===Node.TEXT_NODE?d.setStart(u.domNode,c):d.setStartBefore(u.domNode),f.domNode.nodeType===Node.TEXT_NODE?d.setEnd(f.domNode,h):d.setEndAfter(f.domNode),t.concat(d)}),[])},t.prototype._transformCursors=function(t){var e=this;t=new f(t),this.cursors().filter((function(t){return t.range})).forEach((function(r){r.range.index=t.transformPosition(r.range.index),e._updateCursor(r)}))},t.DEFAULTS={template:c.default,containerClass:\"ql-cursors\",selectionChangeSource:\"api\",hideDelayMs:3e3,hideSpeedMs:400},t}();e.default=h},338:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var i=n(r(353)),o='\\n \\n \\n \\n \\n
    \\n \\n
    \\n');e.default=o},207:function(t){t.exports=function(){\"use strict\";const t=/^\\s+/,e=/\\s+$/;function r(n,i){if(i=i||{},(n=n||\"\")instanceof r)return n;if(!(this instanceof r))return new r(n,i);var o=function(r){var n={r:0,g:0,b:0},i=1,o=null,a=null,s=null,u=!1,c=!1;return\"string\"==typeof r&&(r=function(r){r=r.replace(t,\"\").replace(e,\"\").toLowerCase();var n,i=!1;if(y[r])r=y[r],i=!0;else if(\"transparent\"==r)return{r:0,g:0,b:0,a:0,format:\"name\"};return(n=T.rgb.exec(r))?{r:n[1],g:n[2],b:n[3]}:(n=T.rgba.exec(r))?{r:n[1],g:n[2],b:n[3],a:n[4]}:(n=T.hsl.exec(r))?{h:n[1],s:n[2],l:n[3]}:(n=T.hsla.exec(r))?{h:n[1],s:n[2],l:n[3],a:n[4]}:(n=T.hsv.exec(r))?{h:n[1],s:n[2],v:n[3]}:(n=T.hsva.exec(r))?{h:n[1],s:n[2],v:n[3],a:n[4]}:(n=T.hex8.exec(r))?{r:w(n[1]),g:w(n[2]),b:w(n[3]),a:O(n[4]),format:i?\"name\":\"hex8\"}:(n=T.hex6.exec(r))?{r:w(n[1]),g:w(n[2]),b:w(n[3]),format:i?\"name\":\"hex\"}:(n=T.hex4.exec(r))?{r:w(n[1]+\"\"+n[1]),g:w(n[2]+\"\"+n[2]),b:w(n[3]+\"\"+n[3]),a:O(n[4]+\"\"+n[4]),format:i?\"name\":\"hex8\"}:!!(n=T.hex3.exec(r))&&{r:w(n[1]+\"\"+n[1]),g:w(n[2]+\"\"+n[2]),b:w(n[3]+\"\"+n[3]),format:i?\"name\":\"hex\"}}(r)),\"object\"==typeof r&&(R(r.r)&&R(r.g)&&R(r.b)?(l=r.r,f=r.g,h=r.b,n={r:255*x(l,255),g:255*x(f,255),b:255*x(h,255)},u=!0,c=\"%\"===String(r.r).substr(-1)?\"prgb\":\"rgb\"):R(r.h)&&R(r.s)&&R(r.v)?(o=S(r.s),a=S(r.v),n=function(t,e,r){t=6*x(t,360),e=x(e,100),r=x(r,100);var n=Math.floor(t),i=t-n,o=r*(1-e),a=r*(1-i*e),s=r*(1-(1-i)*e),u=n%6;return{r:255*[r,a,o,o,s,r][u],g:255*[s,r,r,a,o,o][u],b:255*[o,o,s,r,r,a][u]}}(r.h,o,a),u=!0,c=\"hsv\"):R(r.h)&&R(r.s)&&R(r.l)&&(o=S(r.s),s=S(r.l),n=function(t,e,r){var n,i,o;function a(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=x(t,360),e=x(e,100),r=x(r,100),0===e)n=i=o=r;else{var s=r<.5?r*(1+e):r+e-r*e,u=2*r-s;n=a(u,s,t+1/3),i=a(u,s,t),o=a(u,s,t-1/3)}return{r:255*n,g:255*i,b:255*o}}(r.h,o,s),u=!0,c=\"hsl\"),r.hasOwnProperty(\"a\")&&(i=r.a)),i=A(i),{ok:u,format:r.format||c,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a:i};var l,f,h}(n);this._originalInput=n,this._r=o.r,this._g=o.g,this._b=o.b,this._a=o.a,this._roundA=Math.round(100*this._a)/100,this._format=i.format||o.format,this._gradientType=i.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=o.ok}function n(t,e,r){t=x(t,255),e=x(e,255),r=x(r,255);var n,i,o=Math.max(t,e,r),a=Math.min(t,e,r),s=(o+a)/2;if(o==a)n=i=0;else{var u=o-a;switch(i=s>.5?u/(2-o-a):u/(o+a),o){case t:n=(e-r)/u+(e>1)+720)%360;--e;)i.h=(i.h+o)%360,a.push(r(i));return a}function b(t,e){e=e||6;for(var n=r(t).toHsv(),i=n.h,o=n.s,a=n.v,s=[],u=1/e;e--;)s.push(r({h:i,s:o,v:a})),a=(a+u)%1;return s}r.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n=this.toRgb();return t=n.r/255,e=n.g/255,r=n.b/255,.2126*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.7152*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))},setAlpha:function(t){return this._a=A(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=i(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=i(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),n=Math.round(100*t.v);return 1==this._a?\"hsv(\"+e+\", \"+r+\"%, \"+n+\"%)\":\"hsva(\"+e+\", \"+r+\"%, \"+n+\"%, \"+this._roundA+\")\"},toHsl:function(){var t=n(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=n(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),i=Math.round(100*t.l);return 1==this._a?\"hsl(\"+e+\", \"+r+\"%, \"+i+\"%)\":\"hsla(\"+e+\", \"+r+\"%, \"+i+\"%, \"+this._roundA+\")\"},toHex:function(t){return o(this._r,this._g,this._b,t)},toHexString:function(t){return\"#\"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[E(Math.round(t).toString(16)),E(Math.round(e).toString(16)),E(Math.round(r).toString(16)),E(M(n))];return i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1)?o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0):o.join(\"\")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return\"#\"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?\"rgb(\"+Math.round(this._r)+\", \"+Math.round(this._g)+\", \"+Math.round(this._b)+\")\":\"rgba(\"+Math.round(this._r)+\", \"+Math.round(this._g)+\", \"+Math.round(this._b)+\", \"+this._roundA+\")\"},toPercentageRgb:function(){return{r:Math.round(100*x(this._r,255))+\"%\",g:Math.round(100*x(this._g,255))+\"%\",b:Math.round(100*x(this._b,255))+\"%\",a:this._a}},toPercentageRgbString:function(){return 1==this._a?\"rgb(\"+Math.round(100*x(this._r,255))+\"%, \"+Math.round(100*x(this._g,255))+\"%, \"+Math.round(100*x(this._b,255))+\"%)\":\"rgba(\"+Math.round(100*x(this._r,255))+\"%, \"+Math.round(100*x(this._g,255))+\"%, \"+Math.round(100*x(this._b,255))+\"%, \"+this._roundA+\")\"},toName:function(){return 0===this._a?\"transparent\":!(this._a<1)&&(m[o(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e=\"#\"+a(this._r,this._g,this._b,this._a),n=e,i=this._gradientType?\"GradientType = 1, \":\"\";if(t){var o=r(t);n=\"#\"+a(o._r,o._g,o._b,o._a)}return\"progid:DXImageTransform.Microsoft.gradient(\"+i+\"startColorstr=\"+e+\",endColorstr=\"+n+\")\"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||\"hex\"!==t&&\"hex6\"!==t&&\"hex3\"!==t&&\"hex4\"!==t&&\"hex8\"!==t&&\"name\"!==t?(\"rgb\"===t&&(r=this.toRgbString()),\"prgb\"===t&&(r=this.toPercentageRgbString()),\"hex\"!==t&&\"hex6\"!==t||(r=this.toHexString()),\"hex3\"===t&&(r=this.toHexString(!0)),\"hex4\"===t&&(r=this.toHex8String(!0)),\"hex8\"===t&&(r=this.toHex8String()),\"name\"===t&&(r=this.toName()),\"hsl\"===t&&(r=this.toHslString()),\"hsv\"===t&&(r=this.toHsvString()),r||this.toHexString()):\"name\"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return r(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(l,arguments)},brighten:function(){return this._applyModification(f,arguments)},darken:function(){return this._applyModification(h,arguments)},desaturate:function(){return this._applyModification(s,arguments)},saturate:function(){return this._applyModification(u,arguments)},greyscale:function(){return this._applyModification(c,arguments)},spin:function(){return this._applyModification(d,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(v,arguments)},complement:function(){return this._applyCombination(p,arguments)},monochromatic:function(){return this._applyCombination(b,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(g,[3])},tetrad:function(){return this._applyCombination(g,[4])}},r.fromRatio=function(t,e){if(\"object\"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&(n[i]=\"a\"===i?t[i]:S(t[i]));t=n}return r(t,e)},r.equals=function(t,e){return!(!t||!e)&&r(t).toRgbString()==r(e).toRgbString()},r.random=function(){return r.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},r.mix=function(t,e,n){n=0===n?0:n||50;var i=r(t).toRgb(),o=r(e).toRgb(),a=n/100;return r({r:(o.r-i.r)*a+i.r,g:(o.g-i.g)*a+i.g,b:(o.b-i.b)*a+i.b,a:(o.a-i.a)*a+i.a})},r.readability=function(t,e){var n=r(t),i=r(e);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},r.isReadable=function(t,e,n){var i,o,a,s,u,c=r.readability(t,e);switch(o=!1,(a=n,\"AA\"!==(s=((a=a||{level:\"AA\",size:\"small\"}).level||\"AA\").toUpperCase())&&\"AAA\"!==s&&(s=\"AA\"),\"small\"!==(u=(a.size||\"small\").toLowerCase())&&\"large\"!==u&&(u=\"small\"),i={level:s,size:u}).level+i.size){case\"AAsmall\":case\"AAAlarge\":o=c>=4.5;break;case\"AAlarge\":o=c>=3;break;case\"AAAsmall\":o=c>=7}return o},r.mostReadable=function(t,e,n){var i,o,a,s,u=null,c=0;o=(n=n||{}).includeFallbackColors,a=n.level,s=n.size;for(var l=0;lc&&(c=i,u=r(e[l]));return r.isReadable(t,u,{level:a,size:s})||!o?u:(n.includeFallbackColors=!1,r.mostReadable(t,[\"#fff\",\"#000\"],n))};var y=r.names={aliceblue:\"f0f8ff\",antiquewhite:\"faebd7\",aqua:\"0ff\",aquamarine:\"7fffd4\",azure:\"f0ffff\",beige:\"f5f5dc\",bisque:\"ffe4c4\",black:\"000\",blanchedalmond:\"ffebcd\",blue:\"00f\",blueviolet:\"8a2be2\",brown:\"a52a2a\",burlywood:\"deb887\",burntsienna:\"ea7e5d\",cadetblue:\"5f9ea0\",chartreuse:\"7fff00\",chocolate:\"d2691e\",coral:\"ff7f50\",cornflowerblue:\"6495ed\",cornsilk:\"fff8dc\",crimson:\"dc143c\",cyan:\"0ff\",darkblue:\"00008b\",darkcyan:\"008b8b\",darkgoldenrod:\"b8860b\",darkgray:\"a9a9a9\",darkgreen:\"006400\",darkgrey:\"a9a9a9\",darkkhaki:\"bdb76b\",darkmagenta:\"8b008b\",darkolivegreen:\"556b2f\",darkorange:\"ff8c00\",darkorchid:\"9932cc\",darkred:\"8b0000\",darksalmon:\"e9967a\",darkseagreen:\"8fbc8f\",darkslateblue:\"483d8b\",darkslategray:\"2f4f4f\",darkslategrey:\"2f4f4f\",darkturquoise:\"00ced1\",darkviolet:\"9400d3\",deeppink:\"ff1493\",deepskyblue:\"00bfff\",dimgray:\"696969\",dimgrey:\"696969\",dodgerblue:\"1e90ff\",firebrick:\"b22222\",floralwhite:\"fffaf0\",forestgreen:\"228b22\",fuchsia:\"f0f\",gainsboro:\"dcdcdc\",ghostwhite:\"f8f8ff\",gold:\"ffd700\",goldenrod:\"daa520\",gray:\"808080\",green:\"008000\",greenyellow:\"adff2f\",grey:\"808080\",honeydew:\"f0fff0\",hotpink:\"ff69b4\",indianred:\"cd5c5c\",indigo:\"4b0082\",ivory:\"fffff0\",khaki:\"f0e68c\",lavender:\"e6e6fa\",lavenderblush:\"fff0f5\",lawngreen:\"7cfc00\",lemonchiffon:\"fffacd\",lightblue:\"add8e6\",lightcoral:\"f08080\",lightcyan:\"e0ffff\",lightgoldenrodyellow:\"fafad2\",lightgray:\"d3d3d3\",lightgreen:\"90ee90\",lightgrey:\"d3d3d3\",lightpink:\"ffb6c1\",lightsalmon:\"ffa07a\",lightseagreen:\"20b2aa\",lightskyblue:\"87cefa\",lightslategray:\"789\",lightslategrey:\"789\",lightsteelblue:\"b0c4de\",lightyellow:\"ffffe0\",lime:\"0f0\",limegreen:\"32cd32\",linen:\"faf0e6\",magenta:\"f0f\",maroon:\"800000\",mediumaquamarine:\"66cdaa\",mediumblue:\"0000cd\",mediumorchid:\"ba55d3\",mediumpurple:\"9370db\",mediumseagreen:\"3cb371\",mediumslateblue:\"7b68ee\",mediumspringgreen:\"00fa9a\",mediumturquoise:\"48d1cc\",mediumvioletred:\"c71585\",midnightblue:\"191970\",mintcream:\"f5fffa\",mistyrose:\"ffe4e1\",moccasin:\"ffe4b5\",navajowhite:\"ffdead\",navy:\"000080\",oldlace:\"fdf5e6\",olive:\"808000\",olivedrab:\"6b8e23\",orange:\"ffa500\",orangered:\"ff4500\",orchid:\"da70d6\",palegoldenrod:\"eee8aa\",palegreen:\"98fb98\",paleturquoise:\"afeeee\",palevioletred:\"db7093\",papayawhip:\"ffefd5\",peachpuff:\"ffdab9\",peru:\"cd853f\",pink:\"ffc0cb\",plum:\"dda0dd\",powderblue:\"b0e0e6\",purple:\"800080\",rebeccapurple:\"663399\",red:\"f00\",rosybrown:\"bc8f8f\",royalblue:\"4169e1\",saddlebrown:\"8b4513\",salmon:\"fa8072\",sandybrown:\"f4a460\",seagreen:\"2e8b57\",seashell:\"fff5ee\",sienna:\"a0522d\",silver:\"c0c0c0\",skyblue:\"87ceeb\",slateblue:\"6a5acd\",slategray:\"708090\",slategrey:\"708090\",snow:\"fffafa\",springgreen:\"00ff7f\",steelblue:\"4682b4\",tan:\"d2b48c\",teal:\"008080\",thistle:\"d8bfd8\",tomato:\"ff6347\",turquoise:\"40e0d0\",violet:\"ee82ee\",wheat:\"f5deb3\",white:\"fff\",whitesmoke:\"f5f5f5\",yellow:\"ff0\",yellowgreen:\"9acd32\"},m=r.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(y);function A(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function x(t,e){(function(t){return\"string\"==typeof t&&-1!=t.indexOf(\".\")&&1===parseFloat(t)})(t)&&(t=\"100%\");var r=function(t){return\"string\"==typeof t&&-1!=t.indexOf(\"%\")}(t);return t=Math.min(e,Math.max(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),Math.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function C(t){return Math.min(1,Math.max(0,t))}function w(t){return parseInt(t,16)}function E(t){return 1==t.length?\"0\"+t:\"\"+t}function S(t){return t<=1&&(t=100*t+\"%\"),t}function M(t){return Math.round(255*parseFloat(t)).toString(16)}function O(t){return w(t)/255}var j,L,k,T=(L=\"[\\\\s|\\\\(]+(\"+(j=\"(?:[-\\\\+]?\\\\d*\\\\.\\\\d+%?)|(?:[-\\\\+]?\\\\d+%?)\")+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")\\\\s*\\\\)?\",k=\"[\\\\s|\\\\(]+(\"+j+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")\\\\s*\\\\)?\",{CSS_UNIT:new RegExp(j),rgb:new RegExp(\"rgb\"+L),rgba:new RegExp(\"rgba\"+k),hsl:new RegExp(\"hsl\"+L),hsla:new RegExp(\"hsla\"+k),hsv:new RegExp(\"hsv\"+L),hsva:new RegExp(\"hsva\"+k),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function R(t){return!!T.CSS_UNIT.exec(t)}return r}()}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={id:n,loaded:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if(\"object\"==typeof globalThis)return globalThis;try{return this||new Function(\"return this\")()}catch(t){if(\"object\"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},r.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),r.nc=void 0;var n=r(607);return n.default})()));", "/**\n * @module bindings/quill\n */\n\nimport * as Y from 'yjs' // eslint-disable-line\n\n/**\n * @typedef {import('y-protocols/awareness').Awareness} Awareness\n\n/**\n * Removes the pending '\\n's if it has no attributes.\n */\nexport const normQuillDelta = delta => {\n if (delta.length > 0) {\n const d = delta[delta.length - 1]\n const insert = d.insert\n if (d.attributes === undefined && insert !== undefined && insert.slice(-1) === '\\n') {\n delta = delta.slice()\n let ins = insert.slice(0, -1)\n while (ins.slice(-1) === '\\n') {\n ins = ins.slice(0, -1)\n }\n delta[delta.length - 1] = { insert: ins }\n if (ins.length === 0) {\n delta.pop()\n }\n return delta\n }\n }\n return delta\n}\n\n/**\n * @param {any} quillCursors\n */\nconst updateCursor = (quillCursors, aw, clientId, doc, type) => {\n try {\n if (aw && aw.cursor && clientId !== doc.clientID) {\n const user = aw.user || {}\n const color = user.color || '#ffa500'\n const name = user.name || `User: ${clientId}`\n quillCursors.createCursor(clientId.toString(), name, color)\n const anchor = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(aw.cursor.anchor), doc)\n const head = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(aw.cursor.head), doc)\n if (anchor && head && anchor.type === type) {\n quillCursors.moveCursor(clientId.toString(), { index: anchor.index, length: head.index - anchor.index })\n }\n } else {\n quillCursors.removeCursor(clientId.toString())\n }\n } catch (err) {\n console.error(err)\n }\n}\n\nexport class QuillBinding {\n /**\n * @param {Y.Text} type\n * @param {any} quill\n * @param {Awareness} [awareness]\n */\n constructor (type, quill, awareness) {\n const doc = /** @type {Y.Doc} */ (type.doc)\n this.type = type\n this.doc = doc\n this.quill = quill\n const quillCursors = quill.getModule('cursors') || null\n this.quillCursors = quillCursors\n // This object contains all attributes used in the quill instance\n this._negatedUsedFormats = {}\n this.awareness = awareness\n this._awarenessChange = ({ added, removed, updated }) => {\n const states = /** @type {Awareness} */ (awareness).getStates()\n added.forEach(id => {\n updateCursor(quillCursors, states.get(id), id, doc, type)\n })\n updated.forEach(id => {\n updateCursor(quillCursors, states.get(id), id, doc, type)\n })\n removed.forEach(id => {\n quillCursors.removeCursor(id.toString())\n })\n }\n /**\n * @param {Y.YTextEvent} event\n */\n this._typeObserver = event => {\n if (event.transaction.origin !== this) {\n const eventDelta = event.delta\n // We always explicitly set attributes, otherwise concurrent edits may\n // result in quill assuming that a text insertion shall inherit existing\n // attributes.\n const delta = []\n for (let i = 0; i < eventDelta.length; i++) {\n const d = eventDelta[i]\n if (d.insert !== undefined) {\n delta.push(Object.assign({}, d, { attributes: Object.assign({}, this._negatedUsedFormats, d.attributes || {}) }))\n } else {\n delta.push(d)\n }\n }\n quill.updateContents(delta, this)\n }\n }\n type.observe(this._typeObserver)\n this._quillObserver = (eventType, delta, state, origin) => {\n if (delta && delta.ops) {\n // update content\n const ops = delta.ops\n ops.forEach(op => {\n if (op.attributes !== undefined) {\n for (const key in op.attributes) {\n if (this._negatedUsedFormats[key] === undefined) {\n this._negatedUsedFormats[key] = false\n }\n }\n }\n })\n if (origin !== this) {\n doc.transact(() => {\n type.applyDelta(ops)\n }, this)\n }\n }\n // always check selection\n if (awareness && quillCursors) {\n const sel = quill.getSelection()\n const aw = /** @type {any} */ (awareness.getLocalState())\n if (sel === null) {\n if (awareness.getLocalState() !== null) {\n awareness.setLocalStateField('cursor', /** @type {any} */ (null))\n }\n } else {\n const anchor = Y.createRelativePositionFromTypeIndex(type, sel.index)\n const head = Y.createRelativePositionFromTypeIndex(type, sel.index + sel.length)\n if (!aw || !aw.cursor || !Y.compareRelativePositions(anchor, aw.cursor.anchor) || !Y.compareRelativePositions(head, aw.cursor.head)) {\n awareness.setLocalStateField('cursor', {\n anchor,\n head\n })\n }\n }\n // update all remote cursor locations\n awareness.getStates().forEach((aw, clientId) => {\n updateCursor(quillCursors, aw, clientId, doc, type)\n })\n }\n }\n quill.on('editor-change', this._quillObserver)\n // This indirectly initializes _negatedUsedFormats.\n // Make sure that this call this after the _quillObserver is set.\n quill.setContents(type.toDelta(), this)\n // init remote cursors\n if (quillCursors !== null && awareness) {\n awareness.getStates().forEach((aw, clientId) => {\n updateCursor(quillCursors, aw, clientId, doc, type)\n })\n awareness.on('change', this._awarenessChange)\n }\n }\n\n destroy () {\n this.type.unobserve(this._typeObserver)\n this.quill.off('editor-change', this._quillObserver)\n if (this.awareness) {\n this.awareness.off('change', this._awarenessChange)\n }\n }\n}\n", "// Generated by js_of_ocaml\n//# buildInfo:effects=false, kind=exe, use-js-string=true, version=5.8.2+5.8.2\n(function(a){typeof\nglobalThis!==\"object\"&&(this?b():(a.defineProperty(a.prototype,\"_T_\",{configurable:true,get:b}),_T_));function\nb(){var\nb=this||self;b.globalThis=b;delete\na.prototype._T_}}(Object));(function(a){window.yjs=require(\"yjs\");window.WebrtcProvider=require(\"y-webrtc\").WebrtcProvider;window.IndexeddbPersistence=require(\"y-indexeddb\").IndexeddbPersistence}(globalThis));(function(a){require(\"quill/dist/quill.core.css\");require(\"quill/dist/quill.bubble.css\");require(\"quill/dist/quill.snow.css\");window.Quill=require(\"quill\").default;window.QuillCursors=require(\"quill-cursors\")}(globalThis));(function(a){window.QuillBinding=require(\"y-quill\").QuillBinding}(globalThis));(function(p){\"use strict\";var\nv=3850876,aE=\" \",ad=\"0\",fY=\"compare: functional value\",fX=\"mkdir\",cu=1000,jF=\"delete\",X=\"vendor/lwd/lib/lwd/lwd_seq.pp.ml\",kq=\"@[\",kp=\"window\",kP=\"console\",dO=\"int_of_string\",fE=\"fs\",j9=\"%u\",ko=\"/static/\",jE=\"%i\",kO=\"%ni\",aX=0xff,fW=749039939,kn=\"Assert_failure\",aG=737455525,j8=\"camlinternalMod.ml\",jD=\"0x\",j7=0x7ff0,kN=218,jC=0xdfff,j6=\"End_of_file\",km=\"OCAMLRUNPARAM\",jB=\": closedir failed\",kl=253,kM=\"Out_of_memory\",jA=\"Not_found\",f3=\"Failure\",dN=\"Unix.Unix_error\",jz=\"style\",j5=\"^\",bW=\"text\",kL=\"length\",fQ=\"ENOTDIR\",kk=\"Lwd_seq.rank: node is marked\",bv=936573133,jy=\"%Li\",jw=\"flex\",jx=\"Invalid_argument\",dG=254,bV=\"+\",dI=\"Set.bal\",kK=\", characters \",aV=0xffffff,j4=858694086,kj=120,ki=1027,ct=1024,dM=\"Map.bal\",ba=246,j3=\"Pervasives.do_at_exit\",kh=389604418,j2=65536,jv=\"submit\",c=\"vendor/brr_lwd_ui/examples/yjs/main.ml\",fP=0xf,T=16620,ju=\", \",dF=512,fO=-588596599,kI=\"Match_failure\",kJ=\"closedir\",js=\"%li\",jt=1026,kH=-32,jr=157,jq=\"b\",fD=\"nan\",e=\"\",fC=\"rmdir\",fV=\"Fatal error: exception \",j1=\"infinity\",K=\"camlinternalFormat.ml\",j0=\"fd \",kF=\"append\",kG=\": \",jp=174,q=248,jZ=\"em\",jY=\"data\",kE=0xe0,kg=24029,jX=0xf0,jW=\"Sys_error\",ao=0x80,fN=\"vendor/brr_lwd_ui/bindings/yjs/doc.ml\",kf=\"ENOTEMPTY\",kD=\"EEXIST\",fU=1255,jV=1073741823,dE=\"value\",fB=\" : flags Open_text and Open_binary are not compatible\",kC=\"px\",fM=\"e\",kB=459,fA=\": Not a directory\",fL=\"ENOENT\",ke=\"Stack_overflow\",fK=-605101559,S=15681,jU=\"Array\",kA=\"Undefined_recursive_module\",kz=2147483647,aF=0x8000,cs=\"string\",dH=\"table\",jT=0x800,kd=-48,jn=\"error\",jo=\" : is a directory\",jR=\"@{\",jS=\"Division_by_zero\",jm=\"classList\",a$=\".\",jQ=\"(Program not linked with -g, cannot print stack backtrace)\\n\",cq=\"name\",bb=0x3f,ky=492,a_=737456202,fJ=\" : file already exists\",bu=128,dL=\": No such file or directory\",jO=\"vendor/lwd/lib/brr-lwd/elwd.ml\",jP=255,dD=\"lwd-to-remove\",cv=256,jl=\"checked\",cr=-976970511,fI=100,jN=\"id\",fz=\"index out of bounds\",kc=-937474657,aH=\"/\",fy=504440814,dC=252,kx=\"height: \",jk=\"lwdui-virtual-table-row\",fx=\"%d\",kw=383,jj=\": file descriptor already closed\",bs=\"-\",fw=\"EBADF\",jM=\"changes\",aW=951901561,jL=102,fH=-97,kv=\"Printexc.handle_uncaught_exception\",ji=12520,f2=\" : flags Open_rdonly and Open_wronly are not compatible\",a=\"vendor/lwd/lib/lwd/lwd_table.ml\",fT=756711075,kb=\"Fatal error: exception %s\\n\",fG=4100401,ku=\"class\",jh=\"\\xe2\\x9d\\x8c\",aD=250,jK=199,dK=\"bool\",f0=82908052,f1=\"kind\",bt=611392745,fF=\"cell\",kt=\">\",jJ=\"([^/]+)\",ka=\"input\",fS=\"jsError\",jg=103,dB='\"',aI=0xffff,fZ=127,fR=737308346,jf=0xdc00,jI=\"documentElement\",ks=\"Sys_blocked_io\",b=\"vendor/lwd/lib/lwd/lwd.ml\",j$=\"not implemented\",je=\"buffer.ml\",jH=\"Form submitted:\",kr=\"_\",fv=\"target\",jG=-101336657,j_=\"rem\",dJ=\"_bigarr02\";function\nzh(a,b,c,d,e){if(d<=b)for(var\nf=1;f<=e;f++)c[d+f]=a[b+f];else\nfor(var\nf=e;f>=1;f--)c[d+f]=a[b+f];return 0}function\nzi(a,b,c){var\nd=new\nArray(c+1);d[0]=0;for(var\ne=1,f=b+1;e<=c;e++,f++)d[e]=a[f];return d}function\ncE(a,b,c){var\nd=String.fromCharCode;if(b==0&&c<=4096&&c==a.length)return d.apply(null,a);var\nf=e;for(;0=c.l||c.t==2&&e>=c.c.length)){c.c=a.t==4?cE(a.c,b,e):b==0&&a.c.length==e?a.c:a.c.substr(b,e);c.t=c.c.length==c.l?0:2}else if(c.t==2&&d==c.c.length){c.c+=a.t==4?cE(a.c,b,e):b==0&&a.c.length==e?a.c:a.c.substr(b,e);c.t=c.c.length==c.l?0:2}else{if(c.t!=4)dS(c);var\ng=a.c,h=c.c;if(a.t==4)if(d<=b)for(var\nf=0;f=0;f--)h[d+f]=g[b+f];else{var\ni=Math.min(e,g.length-b);for(var\nf=0;f>=1;if(a==0)return d;b+=b;c++;if(c==9)b.slice(0,1)}}function\ncz(a){if(a.t==2)a.c+=b1(a.l-a.c.length,\"\\0\");else\na.c=cE(a.c,0,a.c.length);a.t=0}function\ngn(a){if(a.length<24){for(var\nb=0;bfZ)return false;return true}else\nreturn!/[^\\x00-\\x7f]/.test(a)}function\nll(a){for(var\nk=e,d=e,h,g,i,b,c=0,j=a.length;cdF){d.substr(0,1);k+=d;d=e;k+=a.slice(c,f)}else\nd+=a.slice(c,f);if(f==j)break;c=f}b=1;if(++c=0xd7ff&&b<0xe000)b=2}else{b=3;if(++c0x10ffff)b=3}}}}}if(b<4){c-=b;d+=\"\\ufffd\"}else if(b>aI)d+=String.fromCharCode(0xd7c0+(b>>10),jf+(b&0x3FF));else\nd+=String.fromCharCode(b);if(d.length>ct){d.substr(0,1);k+=d;d=e}}return k+d}function\naY(a,b,c){this.t=a;this.c=b;this.l=c}aY.prototype.toString=function(){switch(this.t){case\n9:return this.c;default:cz(this);case\n0:if(gn(this.c)){this.t=9;return this.c}this.t=8;case\n8:return this.c}};aY.prototype.toUtf16=function(){var\na=this.toString();if(this.t==9)return a;return ll(a)};aY.prototype.slice=function(){var\na=this.t==4?this.c.slice():this.c;return new\naY(this.t,a,this.l)};function\nkX(a){return new\naY(0,a,a.length)}function\naJ(a){return a}function\nbd(a){return kX(aJ(a))}function\ncy(a,b,c,d,e){aZ(bd(a),b,c,d,e);return 0}function\nln(a){var\nb=p.process;if(b&&b.env&&b.env[a]!=undefined)return b.env[a];if(p.jsoo_static_env&&p.jsoo_static_env[a])return p.jsoo_static_env[a]}var\ngk=0;(function(){var\nc=ln(km);if(c!==undefined){var\nb=c.split(\",\");for(var\na=0;a=a.c.length)return 0;case\n0:return a.c.charCodeAt(b);case\n4:return a.c[b]}}function\nzn(a,b){if(b>>>0>=a.l)f5();return bY(a,b)}function\nA(a,b,c){c&=aX;if(a.t!=4){if(b==a.c.length){a.c+=String.fromCharCode(c);if(b+1==a.l)a.t=0;return 0}dS(a)}a.c[b]=c;return 0}function\na0(a,b,c){if(b>>>0>=a.l)f5();return A(a,b,c)}function\nbx(a){return a.toArray()}function\nzo(a,b,c){if(b>>>0>=a.l-7)f5();var\ne=bx(c);for(var\nd=0;d<8;d++)A(a,b+7-d,e[d]);return 0}function\nbe(d,c){var\nf=d.l>=0?d.l:d.l=d.length,e=c.length,b=f-e;if(b==0)return d.apply(null,c);else if(b<0){var\na=d.apply(null,c.slice(0,f));if(typeof\na!==\"function\")return a;return be(a,c.slice(f))}else{switch(b){case\n1:{var\na=function(a){var\nf=new\nArray(e+1);for(var\nb=0;b>>0>=a.length-1)cx();return a}function\nzp(a){if(isFinite(a)){if(Math.abs(a)>=2.2250738585072014e-308)return 0;if(a!=0)return 1;return 2}return isNaN(a)?4:3}function\nk9(a){return 0}var\nAk=Math.log2&&Math.log2(1.1235582092889474E+307)==1020;function\nAj(a){if(Ak)return Math.floor(Math.log2(a));var\nb=0;if(a==0)return-Infinity;if(a>=1)while(a>=2){a/=2;b++}else\nwhile(a<1){a*=2;b--}return b}function\nga(a){var\nb=new\nFloat32Array(1);b[0]=a;var\nc=new\nInt32Array(b.buffer);return c[0]|0}var\nk4=Math.pow(2,-24);function\nlf(a){throw a}function\ngj(){lf(U.Division_by_zero)}function\nd(a,b,c){this.lo=a&aV;this.mi=b&aV;this.hi=c&aI}d.prototype.caml_custom=\"_j\";d.prototype.copy=function(){return new\nd(this.lo,this.mi,this.hi)};d.prototype.ucompare=function(a){if(this.hi>a.hi)return 1;if(this.hia.mi)return 1;if(this.mia.lo)return 1;if(this.loc)return 1;if(ba.mi)return 1;if(this.mia.lo)return 1;if(this.lo>24),c=-this.hi+(b>>24);return new\nd(a,b,c)};d.prototype.add=function(a){var\nb=this.lo+a.lo,c=this.mi+a.mi+(b>>24),e=this.hi+a.hi+(c>>24);return new\nd(b,c,e)};d.prototype.sub=function(a){var\nb=this.lo-a.lo,c=this.mi-a.mi+(b>>24),e=this.hi-a.hi+(c>>24);return new\nd(b,c,e)};d.prototype.mul=function(a){var\nb=this.lo*a.lo,c=(b*k4|0)+this.mi*a.lo+this.lo*a.mi,e=(c*k4|0)+this.hi*a.lo+this.mi*a.mi+this.lo*a.hi;return new\nd(b,c,e)};d.prototype.isZero=function(){return(this.lo|this.mi|this.hi)==0};d.prototype.isNeg=function(){return this.hi<<16<0};d.prototype.and=function(a){return new\nd(this.lo&a.lo,this.mi&a.mi,this.hi&a.hi)};d.prototype.or=function(a){return new\nd(this.lo|a.lo,this.mi|a.mi,this.hi|a.hi)};d.prototype.xor=function(a){return new\nd(this.lo^a.lo,this.mi^a.mi,this.hi^a.hi)};d.prototype.shift_left=function(a){a=a&63;if(a==0)return this;if(a<24)return new\nd(this.lo<>24-a,this.hi<>24-a);if(a<48)return new\nd(0,this.lo<>48-a);return new\nd(0,0,this.lo<>a|this.mi<<24-a,this.mi>>a|this.hi<<24-a,this.hi>>a);if(a<48)return new\nd(this.mi>>a-24|this.hi<<48-a,this.hi>>a-24,0);return new\nd(this.hi>>a-48,0,0)};d.prototype.shift_right=function(a){a=a&63;if(a==0)return this;var\nc=this.hi<<16>>16;if(a<24)return new\nd(this.lo>>a|this.mi<<24-a,this.mi>>a|c<<24-a,this.hi<<16>>a>>>16);var\nb=this.hi<<16>>31;if(a<48)return new\nd(this.mi>>a-24|this.hi<<48-a,this.hi<<16>>a-24>>16,b&aI);return new\nd(this.hi<<16>>a-32,b,b)};d.prototype.lsl1=function(){this.hi=this.hi<<1|this.mi>>23;this.mi=(this.mi<<1|this.lo>>23)&aV;this.lo=this.lo<<1&aV};d.prototype.lsr1=function(){this.lo=(this.lo>>>1|this.mi<<23)&aV;this.mi=(this.mi>>>1|this.hi<<23)&aV;this.hi=this.hi>>>1};d.prototype.udivmod=function(a){var\ne=0,c=this.copy(),b=a.copy(),f=new\nd(0,0,0);while(c.ucompare(b)>0){e++;b.lsl1()}while(e>=0){e--;f.lsl1();if(c.ucompare(b)>=0){f.lo++;c=c.sub(b)}b.lsr1()}return{quotient:f,modulus:c}};d.prototype.div=function(a){var\nb=this;if(a.isZero())gj();var\nd=b.hi^a.hi;if(b.hi&aF)b=b.neg();if(a.hi&aF)a=a.neg();var\nc=b.udivmod(a).quotient;if(d&aF)c=c.neg();return c};d.prototype.mod=function(a){var\nb=this;if(a.isZero())gj();var\nd=b.hi;if(b.hi&aF)b=b.neg();if(a.hi&aF)a=a.neg();var\nc=b.udivmod(a).modulus;if(d&aF)c=c.neg();return c};d.prototype.toInt=function(){return this.lo|this.mi<<24};d.prototype.toFloat=function(){return(this.hi<<16)*Math.pow(2,32)+this.mi*Math.pow(2,24)+this.lo};d.prototype.toArray=function(){return[this.hi>>8,this.hi&aX,this.mi>>16,this.mi>>8&aX,this.mi&aX,this.lo>>16,this.lo>>8&aX,this.lo&aX]};d.prototype.lo32=function(){return this.lo|(this.mi&aX)<<24};d.prototype.hi32=function(){return this.mi>>>8&aI|this.hi<<16};function\ndV(a,b,c){return new\nd(a,b,c)}function\ndU(a){if(!isFinite(a)){if(isNaN(a))return dV(1,0,j7);return a>0?dV(0,0,j7):dV(0,0,0xfff0)}var\nf=a==0&&1/a==-Infinity?aF:a>=0?0:aF;if(f)a=-a;var\nb=Aj(a)+1023;if(b<=0){b=0;a/=Math.pow(2,-jt)}else{a/=Math.pow(2,b-ki);if(a<16){a*=2;b-=1}if(b==0)a/=2}var\nd=Math.pow(2,24),c=a|0;a=(a-c)*d;var\ne=a|0;a=(a-e)*d;var\ng=a|0;c=c&fP|f|b<<4;return dV(g,e,c)}function\nkW(a,b,c){a.write(32,b.dims.length);a.write(32,b.kind|b.layout<<8);if(b.caml_custom==dJ)for(var\nd=0;d>4;if(d==2047)return(f|g|c&fP)==0?c&aF?-Infinity:Infinity:NaN;var\ne=Math.pow(2,-24),b=(f*e+g)*e+(c&fP);if(d>0){b+=16;b*=Math.pow(2,d-ki)}else\nb*=Math.pow(2,-jt);if(c&aF)b=-b;return b}function\nf4(a){var\nd=a.length,c=1;for(var\nb=0;b>>24&aX|(b&aI)<<8,b>>>16&aI)}function\ngd(a){return a.hi32()}function\nge(a){return a.lo32()}var\nzk=dJ;function\nbc(a,b,c,d){this.kind=a;this.layout=b;this.dims=c;this.data=d}bc.prototype.caml_custom=zk;bc.prototype.offset=function(a){var\nc=0;if(typeof\na===\"number\")a=[a];if(!(a\ninstanceof\nArray))G(\"bigarray.js: invalid offset\");if(this.dims.length!=a.length)G(\"Bigarray.get/set: bad number of dimensions\");if(this.layout==0)for(var\nb=0;b=this.dims[b])cx();c=c*this.dims[b]+a[b]}else\nfor(var\nb=this.dims.length-1;b>=0;b--){if(a[b]<1||a[b]>this.dims[b])cx();c=c*this.dims[b]+(a[b]-1)}return c};bc.prototype.get=function(a){switch(this.kind){case\n7:var\nd=this.data[a*2+0],b=this.data[a*2+1];return zI(d,b);case\n10:case\n11:var\ne=this.data[a*2+0],c=this.data[a*2+1];return[dG,e,c];default:return this.data[a]}};bc.prototype.set=function(a,b){switch(this.kind){case\n7:this.data[a*2+0]=ge(b);this.data[a*2+1]=gd(b);break;case\n10:case\n11:this.data[a*2+0]=b[1];this.data[a*2+1]=b[2];break;default:this.data[a]=b;break}return 0};bc.prototype.fill=function(a){switch(this.kind){case\n7:var\nc=ge(a),e=gd(a);if(c==e)this.data.fill(c);else\nfor(var\nb=0;be)return 1;if(d!=e){if(!b)return NaN;if(d==d)return 1;if(e==e)return-1}}break;case\n7:for(var\nc=0;ca.data[c+1])return 1;if(this.data[c]>>>0>>0)return-1;if(this.data[c]>>>0>a.data[c]>>>0)return 1}break;case\n2:case\n3:case\n4:case\n5:case\n6:case\n8:case\n9:case\n12:for(var\nc=0;ca.data[c])return 1}break}return 0};function\nbX(a,b,c,d){this.kind=a;this.layout=b;this.dims=c;this.data=d}bX.prototype=new\nbc();bX.prototype.offset=function(a){if(typeof\na!==\"number\")if(a\ninstanceof\nArray&&a.length==1)a=a[0];else\nG(\"Ml_Bigarray_c_1_1.offset\");if(a<0||a>=this.dims[0])cx();return a};bX.prototype.get=function(a){return this.data[a]};bX.prototype.set=function(a,b){this.data[a]=b;return 0};bX.prototype.fill=function(a){this.data.fill(a);return 0};function\nkS(a,b,c,d){var\ne=kU(a);if(f4(c)*e!=d.length)G(\"length doesn't match dims\");if(b==0&&c.length==1&&e==1)return new\nbX(a,b,c,d);return new\nbc(a,b,c,d)}function\naj(a){if(!U.Failure)U.Failure=[q,ak(f3),-3];gi(U.Failure,a)}function\nkT(a,b,c){var\nk=a.read32s();if(k<0||k>16)aj(\"input_value: wrong number of bigarray dimensions\");var\nr=a.read32s(),l=r&aX,q=r>>8&1,j=[];if(c==dJ)for(var\nd=0;d>>32-15;b=cC(b,0x1b873593);a^=b;a=a<<13|a>>>32-13;return(a+(a<<2)|0)+(0xe6546b64|0)|0}function\nzC(a,b){a=V(a,ge(b));a=V(a,gd(b));return a}function\nf_(a,b){return zC(a,dU(b))}function\nkV(a){var\nc=f4(a.dims),d=0;switch(a.kind){case\n2:case\n3:case\n12:if(c>cv)c=cv;var\ne=0,b=0;for(b=0;b+4<=a.data.length;b+=4){e=a.data[b+0]|a.data[b+1]<<8|a.data[b+2]<<16|a.data[b+3]<<24;d=V(d,e)}e=0;switch(c&3){case\n3:e=a.data[b+2]<<16;case\n2:e|=a.data[b+1]<<8;case\n1:e|=a.data[b+0];d=V(d,e)}break;case\n4:case\n5:if(c>bu)c=bu;var\ne=0,b=0;for(b=0;b+2<=a.data.length;b+=2){e=a.data[b+0]|a.data[b+1]<<16;d=V(d,e)}if((c&1)!=0)d=V(d,a.data[b]);break;case\n6:if(c>64)c=64;for(var\nb=0;b64)c=64;for(var\nb=0;b32)c=32;c*=2;for(var\nb=0;b64)c=64;for(var\nb=0;b32)c=32;for(var\nb=0;b0?f(b,a,d):f(a,b,d);if(d&&e!=e)return c;if(+e!=+e)return+e;if((e|0)!=0)return e|0}return c}function\ndY(a){return typeof\na===\"string\"&&!/[^\\x00-\\xff]/.test(a)}function\ndX(a){return a\ninstanceof\naY}function\nkZ(a){if(typeof\na===\"number\")return cu;else if(dX(a))return dC;else if(dY(a))return 1252;else if(a\ninstanceof\nArray&&a[0]===a[0]>>>0&&a[0]<=jP){var\nb=a[0]|0;return b==dG?0:b}else if(a\ninstanceof\nString)return ji;else if(typeof\na==\"string\")return ji;else if(a\ninstanceof\nNumber)return cu;else if(a&&a.caml_custom)return fU;else if(a&&a.compare)return 1256;else if(typeof\na==\"function\")return 1247;else if(typeof\na==\"symbol\")return 1251;return 1001}function\nk7(a,b){if(ab?1:0}function\nzm(a,b){a.t&6&&cz(a);b.t&6&&cz(b);return a.cb.c?1:0}function\ndR(a,b,c){var\nf=[];for(;;){if(!(c&&a===b)){var\ne=kZ(a);if(e==aD){a=a[1];continue}var\ng=kZ(b);if(g==aD){b=b[1];continue}if(e!==g){if(e==cu){if(g==fU)return kY(a,b,-1,c);return-1}if(g==cu){if(e==fU)return kY(b,a,1,c);return 1}return eb)return 1;if(a!=b){if(!c)return NaN;if(a==a)return 1;if(b==b)return-1}break;case\n1001:if(ab)return 1;if(a!=b){if(!c)return NaN;if(a==a)return 1;if(b==b)return-1}break;case\n1251:if(a!==b){if(!c)return NaN;return 1}break;case\n1252:var\na=aJ(a),b=aJ(b);if(a!==b){if(ab)return 1}break;case\n12520:var\na=a.toString(),b=b.toString();if(a!==b){if(ab)return 1}break;case\n246:case\n254:default:if(k9(e)){G(\"compare: continuation value\");break}if(a.length!=b.length)return a.length1)f.push(a,b,1);break}}if(f.length==0)return 0;var\nh=f.pop();b=f.pop();a=f.pop();if(h+10)if(b==0&&(c>=a.l||a.t==2&&c>=a.c.length))if(d==0){a.c=e;a.t=2}else{a.c=b1(c,String.fromCharCode(d));a.t=c==a.l?0:2}else{if(a.t!=4)dS(a);for(c+=b;b0&&b===b)return b;a=a.replace(/_/g,e);b=+a;if(a.length>0&&b===b||/^[+-]?nan$/i.test(a))return b;var\nc=/^ *([+-]?)0x([0-9a-f]+)\\.?([0-9a-f]*)(p([+-]?[0-9]+))?/i.exec(a);if(c){var\nd=c[3].replace(/0+$/,e),g=parseInt(c[1]+c[2]+d,16),f=(c[5]|0)-4*d.length;b=g*Math.pow(2,f);return b}if(/^\\+?inf(inity)?$/i.test(a))return Infinity;if(/^-inf(inity)?$/i.test(a))return-Infinity;aj(\"float_of_string\")}function\ngh(a){a=aJ(a);var\ne=a.length;if(e>31)G(\"format_int: format too long\");var\nb={justify:bV,signstyle:bs,filler:aE,alternate:false,base:0,signedconv:false,width:0,uppercase:false,sign:1,prec:-1,conv:\"f\"};for(var\nd=0;d=0&&c<=9){b.width=b.width*10+c;d++}d--;break;case\".\":b.prec=0;d++;while(c=a.charCodeAt(d)-48,c>=0&&c<=9){b.prec=b.prec*10+c;d++}d--;case\"d\":case\"i\":b.signedconv=true;case\"u\":b.base=10;break;case\"x\":b.base=16;break;case\"X\":b.base=16;b.uppercase=true;break;case\"o\":b.base=8;break;case\"e\":case\"f\":case\"g\":b.signedconv=true;b.conv=c;break;case\"E\":case\"F\":case\"G\":b.signedconv=true;b.uppercase=true;b.conv=c.toLowerCase();break}}return b}function\nf8(a,b){if(a.uppercase)b=b.toUpperCase();var\nf=b.length;if(a.signedconv&&(a.sign<0||a.signstyle!=bs))f++;if(a.alternate){if(a.base==8)f+=1;if(a.base==16)f+=2}var\nc=e;if(a.justify==bV&&a.filler==aE)for(var\nd=f;d20){c-=20;a/=Math.pow(10,c);a+=new\nArray(c+1).join(ad);if(b>0)a=a+a$+new\nArray(b+1).join(ad);return a}else\nreturn a.toFixed(b)}}var\nc,f=gh(a),e=f.prec<0?6:f.prec;if(b<0||b==0&&1/b==-Infinity){f.sign=-1;b=-b}if(isNaN(b)){c=fD;f.filler=aE}else if(!isFinite(b)){c=\"inf\";f.filler=aE}else\nswitch(f.conv){case\"e\":var\nc=b.toExponential(e),d=c.length;if(c.charAt(d-3)==fM)c=c.slice(0,d-1)+ad+c.slice(d-1);break;case\"f\":c=j(b,e);break;case\"g\":e=e?e:1;c=b.toExponential(e-1);var\ni=c.indexOf(fM),h=+c.slice(i+1);if(h<-4||b>=1e21||b.toFixed(0).length>e){var\nd=i-1;while(c.charAt(d)==ad)d--;if(c.charAt(d)==a$)d--;c=c.slice(0,d+1)+c.slice(i);d=c.length;if(c.charAt(d-3)==fM)c=c.slice(0,d-1)+ad+c.slice(d-1);break}else{var\ng=e;if(h<0){g-=h+1;c=b.toFixed(g)}else\nwhile(c=b.toFixed(g),c.length>e+1)g--;if(g){var\nd=c.length-1;while(c.charAt(d)==ad)d--;if(c.charAt(d)==a$)d--;c=c.slice(0,d+1)}}break}return f8(f,c)}function\ndT(a,b){if(aJ(a)==fx)return ak(e+b);var\nc=gh(a);if(b<0)if(c.signedconv){c.sign=-1;b=-b}else\nb>>>=0;var\nd=b.toString(c.base);if(c.prec>=0){c.filler=aE;var\nf=c.prec-d.length;if(f>0)d=b1(f,ad)+d}return f8(c,d)}var\nz_=0;function\nae(){return z_++}function\nH(a){if(gn(a))return a;return ll(a)}function\ncF(){return typeof\np.process!==\"undefined\"&&typeof\np.process.versions!==\"undefined\"&&typeof\np.process.versions.node!==\"undefined\"}function\nAl(){function\na(a){if(a.charAt(0)===aH)return[e,a.substring(1)];return}function\nb(a){var\nh=/^([a-zA-Z]:|[\\\\/]{2}[^\\\\/]+[\\\\/]+[^\\\\/]+)?([\\\\/])?([\\s\\S]*?)$/,b=h.exec(a),c=b[1]||e,f=Boolean(c&&c.charAt(1)!==\":\");if(Boolean(b[2]||f)){var\nd=b[1]||e,g=b[2]||e;return[d,a.substring(d.length+g.length)]}return}return cF()&&p.process&&p.process.platform?p.process.platform===\"win32\"?b:a:a}var\ngo=Al();function\nlj(a){return a.slice(-1)!==aH?a+aH:a}if(cF()&&p.process&&p.process.cwd)var\ncA=p.process.cwd().replace(/\\\\/g,aH);else\nvar\ncA=\"/static\";cA=lj(cA);function\nzX(a){a=H(a);if(!go(a))a=cA+a;var\ne=go(a),d=e[1].split(aH),b=[];for(var\nc=0;c1)b.pop();break;case\".\":break;case\"\":break;default:b.push(d[c]);break}b.unshift(e[0]);b.orig=a;return b}function\nAi(a){for(var\ng=e,c=g,b,i,d=0,h=a.length;ddF){c.substr(0,1);g+=c;c=e;g+=a.slice(d,f)}else\nc+=a.slice(d,f);if(f==h)break;d=f}if(b>6);c+=String.fromCharCode(ao|b&bb)}else if(b<0xd800||b>=jC)c+=String.fromCharCode(kE|b>>12,ao|b>>6&bb,ao|b&bb);else if(b>=0xdbff||d+1==h||(i=a.charCodeAt(d+1))jC)c+=\"\\xef\\xbf\\xbd\";else{d++;b=(b<<10)+i-0x35fdc00;c+=String.fromCharCode(jX|b>>18,ao|b>>12&bb,ao|b>>6&bb,ao|b&bb)}if(c.length>ct){c.substr(0,1);g+=c;c=e}}return g+c}function\nas(a){return gn(a)?ak(a):ak(Ai(a))}var\nAm=[\"E2BIG\",\"EACCES\",\"EAGAIN\",fw,\"EBUSY\",\"ECHILD\",\"EDEADLK\",\"EDOM\",kD,\"EFAULT\",\"EFBIG\",\"EINTR\",\"EINVAL\",\"EIO\",\"EISDIR\",\"EMFILE\",\"EMLINK\",\"ENAMETOOLONG\",\"ENFILE\",\"ENODEV\",fL,\"ENOEXEC\",\"ENOLCK\",\"ENOMEM\",\"ENOSPC\",\"ENOSYS\",fQ,kf,\"ENOTTY\",\"ENXIO\",\"EPERM\",\"EPIPE\",\"ERANGE\",\"EROFS\",\"ESPIPE\",\"ESRCH\",\"EXDEV\",\"EWOULDBLOCK\",\"EINPROGRESS\",\"EALREADY\",\"ENOTSOCK\",\"EDESTADDRREQ\",\"EMSGSIZE\",\"EPROTOTYPE\",\"ENOPROTOOPT\",\"EPROTONOSUPPORT\",\"ESOCKTNOSUPPORT\",\"EOPNOTSUPP\",\"EPFNOSUPPORT\",\"EAFNOSUPPORT\",\"EADDRINUSE\",\"EADDRNOTAVAIL\",\"ENETDOWN\",\"ENETUNREACH\",\"ENETRESET\",\"ECONNABORTED\",\"ECONNRESET\",\"ENOBUFS\",\"EISCONN\",\"ENOTCONN\",\"ESHUTDOWN\",\"ETOOMANYREFS\",\"ETIMEDOUT\",\"ECONNREFUSED\",\"EHOSTDOWN\",\"EHOSTUNREACH\",\"ELOOP\",\"EOVERFLOW\"];function\na2(a,b,c,d){var\nf=Am.indexOf(a);if(f<0){if(d==null)d=-9999;f=[0,d]}var\ng=[f,as(b||e),as(c||e)];return g}var\nld={};function\nbg(a){return ld[a]}function\na1(a,b){throw g([0,a].concat(b))}function\nf6(a){if(!(a\ninstanceof\nUint8Array))a=new\nUint8Array(a);return new\naY(4,a,a.length)}function\nm(a){gi(U.Sys_error,a)}function\nlg(a){m(a+dL)}function\ngm(a){if(a.t!=4)dS(a);return a.c}function\naq(a){return a.l}function\nkQ(){}function\nY(a){this.data=a}Y.prototype=new\nkQ();Y.prototype.constructor=Y;Y.prototype.truncate=function(a){var\nb=this.data;this.data=F(a|0);aZ(b,0,this.data,0,a)};Y.prototype.length=function(){return aq(this.data)};Y.prototype.write=function(a,b,c,d){var\ne=this.length();if(a+d>=e){var\nf=F(a+d),g=this.data;this.data=f;aZ(g,0,this.data,0,e)}aZ(f6(b),c,this.data,a,d);return 0};Y.prototype.read=function(a,b,c,d){var\ne=this.length();if(a+d>=e)d=e-a;if(d){var\nf=F(d|0);aZ(this.data,a,f,0,d);b.set(gm(f),c)}return d};function\nbw(a,b,c){this.file=b;this.name=a;this.flags=c}bw.prototype.err_closed=function(){m(this.name+jj)};bw.prototype.length=function(){if(this.file)return this.file.length();this.err_closed()};bw.prototype.write=function(a,b,c,d){if(this.file)return this.file.write(a,b,c,d);this.err_closed()};bw.prototype.read=function(a,b,c,d){if(this.file)return this.file.read(a,b,c,d);this.err_closed()};bw.prototype.close=function(){this.file=undefined};function\nN(a,b){this.content={};this.root=a;this.lookupFun=b}N.prototype.nm=function(a){return this.root+a};N.prototype.create_dir_if_needed=function(a){var\nd=a.split(aH),c=e;for(var\nb=0;b>>16;a=cC(a,0x85ebca6b|0);a^=a>>>13;a=cC(a,0xc2b2ae35|0);a^=a>>>16;return a}function\nzy(a,b,c,d){var\nj,k,l,h,g,f,e,i,m;h=b;if(h<0||h>cv)h=cv;g=a;f=c;j=[d];k=0;l=1;while(k0){e=j[k++];if(e&&e.caml_custom){if(cB[e.caml_custom]&&cB[e.caml_custom].hash){var\nn=cB[e.caml_custom].hash(e);f=V(f,n);g--}}else if(e\ninstanceof\nArray&&e[0]===(e[0]|0))switch(e[0]){case\n248:f=V(f,e[2]);g--;break;case\n250:j[--k]=e[1];break;default:if(k9(e[0]))break;var\no=e.length-1<<10|e[0];f=V(f,o);for(i=1,m=e.length;i=h)break;j[l++]=e[i]}break}else if(dX(e)){f=zz(f,e);g--}else if(dY(e)){f=zD(f,e);g--}else if(typeof\ne===\"string\"){f=f$(f,e);g--}else if(e===(e|0)){f=V(f,e+e+1);g--}else if(typeof\ne===\"number\"){f=f_(f,e);g--}}f=zB(f);return f&0x3FFFFFFF}function\nzE(a,b,c){if(!isFinite(a)){if(isNaN(a))return as(fD);return as(a>0?j1:\"-infinity\")}var\nk=a==0&&1/a==-Infinity?1:a>=0?0:1;if(k)a=-a;var\nf=0;if(a==0);else if(a<1)while(a<1&&f>-1022){a*=2;f--}else\nwhile(a>=2){a/=2;f++}var\nl=f<0?e:bV,g=e;if(k)g=bs;else\nswitch(c){case\n43:g=bV;break;case\n32:g=aE;break;default:break}if(b>=0&&b<13){var\ni=Math.pow(2,b*4);a=Math.round(a*i)/i}var\nd=a.toString(16);if(b>=0){var\nj=d.indexOf(a$);if(j<0)d+=a$+b1(b,ad);else{var\nh=j+1+b;if(d.length>24&aV,a>>31&aI)}function\nzP(a){return a.toInt()}function\nzL(a){return+a.isNeg()}function\nzO(a){return a.neg()}function\nzJ(a,b){var\nc=gh(a);if(c.signedconv&&zL(b)){c.sign=-1;b=zO(b)}var\nd=e,i=dW(c.base),h=\"0123456789abcdef\";do{var\ng=b.udivmod(i);b=g.quotient;d=h.charAt(zP(g.modulus))+d}while(!zM(b));if(c.prec>=0){c.filler=aE;var\nf=c.prec-d.length;if(f>0)d=b1(f,ad)+d}return f8(c,d)}function\nk5(a,b){return a.or(b)}function\nk6(a,b){return a.shift_left(b)}function\ngf(a,b){return a.shift_right_unsigned(b)}function\nz$(a){var\nb=0,e=n(a),c=10,d=1;if(e>0)switch(_(a,b)){case\n45:b++;d=-1;break;case\n43:b++;d=1;break}if(b+1=48&&a<=57)return a-48;if(a>=65&&a<=90)return a-55;if(a>=97&&a<=122)return a-87;return-1}function\nk8(a){var\nh=z$(a),d=h[0],i=h[1],e=h[2],g=n(a),j=-1>>>0,f=d=e)aj(dO);var\nb=c;for(d++;d=e)break;b=e*b+c;if(b>j)aj(dO)}if(d!=g)aj(dO);b=i*b;if(e==10&&(b|0)!=b)aj(dO);return b|0}function\nk_(a){return a.slice(1)}function\ndZ(a,b,c){return a[H(b)].apply(a,k_(c))}function\nzS(a,b){switch(b.length){case\n1:return new\na;case\n2:return new\na(b[1]);case\n3:return new\na(b[1],b[2]);case\n4:return new\na(b[1],b[2],b[3]);case\n5:return new\na(b[1],b[2],b[3],b[4]);case\n6:return new\na(b[1],b[2],b[3],b[4],b[5]);case\n7:return new\na(b[1],b[2],b[3],b[4],b[5],b[6]);case\n8:return new\na(b[1],b[2],b[3],b[4],b[5],b[6],b[7])}function\nc(){return a.apply(this,k_(b))}c.prototype=a.prototype;return new\nc}function\nk$(a){var\nc={};for(var\nb=1;b>>32-e,c)}function\ng(a,b,c,d,e,f,g){return l(b&c|~b&d,a,b,e,f,g)}function\nh(a,b,c,d,e,f,g){return l(b&d|c&~d,a,b,e,f,g)}function\ni(a,b,c,d,e,f,g){return l(b^c^d,a,b,e,f,g)}function\nj(a,b,c,d,e,f,g){return l(c^(b|~d),a,b,e,f,g)}return function(a,b){var\nc=a[0],d=a[1],e=a[2],f=a[3];c=g(c,d,e,f,b[0],7,0xD76AA478);f=g(f,c,d,e,b[1],12,0xE8C7B756);e=g(e,f,c,d,b[2],17,0x242070DB);d=g(d,e,f,c,b[3],22,0xC1BDCEEE);c=g(c,d,e,f,b[4],7,0xF57C0FAF);f=g(f,c,d,e,b[5],12,0x4787C62A);e=g(e,f,c,d,b[6],17,0xA8304613);d=g(d,e,f,c,b[7],22,0xFD469501);c=g(c,d,e,f,b[8],7,0x698098D8);f=g(f,c,d,e,b[9],12,0x8B44F7AF);e=g(e,f,c,d,b[10],17,0xFFFF5BB1);d=g(d,e,f,c,b[11],22,0x895CD7BE);c=g(c,d,e,f,b[12],7,0x6B901122);f=g(f,c,d,e,b[13],12,0xFD987193);e=g(e,f,c,d,b[14],17,0xA679438E);d=g(d,e,f,c,b[15],22,0x49B40821);c=h(c,d,e,f,b[1],5,0xF61E2562);f=h(f,c,d,e,b[6],9,0xC040B340);e=h(e,f,c,d,b[11],14,0x265E5A51);d=h(d,e,f,c,b[0],20,0xE9B6C7AA);c=h(c,d,e,f,b[5],5,0xD62F105D);f=h(f,c,d,e,b[10],9,0x02441453);e=h(e,f,c,d,b[15],14,0xD8A1E681);d=h(d,e,f,c,b[4],20,0xE7D3FBC8);c=h(c,d,e,f,b[9],5,0x21E1CDE6);f=h(f,c,d,e,b[14],9,0xC33707D6);e=h(e,f,c,d,b[3],14,0xF4D50D87);d=h(d,e,f,c,b[8],20,0x455A14ED);c=h(c,d,e,f,b[13],5,0xA9E3E905);f=h(f,c,d,e,b[2],9,0xFCEFA3F8);e=h(e,f,c,d,b[7],14,0x676F02D9);d=h(d,e,f,c,b[12],20,0x8D2A4C8A);c=i(c,d,e,f,b[5],4,0xFFFA3942);f=i(f,c,d,e,b[8],11,0x8771F681);e=i(e,f,c,d,b[11],16,0x6D9D6122);d=i(d,e,f,c,b[14],23,0xFDE5380C);c=i(c,d,e,f,b[1],4,0xA4BEEA44);f=i(f,c,d,e,b[4],11,0x4BDECFA9);e=i(e,f,c,d,b[7],16,0xF6BB4B60);d=i(d,e,f,c,b[10],23,0xBEBFBC70);c=i(c,d,e,f,b[13],4,0x289B7EC6);f=i(f,c,d,e,b[0],11,0xEAA127FA);e=i(e,f,c,d,b[3],16,0xD4EF3085);d=i(d,e,f,c,b[6],23,0x04881D05);c=i(c,d,e,f,b[9],4,0xD9D4D039);f=i(f,c,d,e,b[12],11,0xE6DB99E5);e=i(e,f,c,d,b[15],16,0x1FA27CF8);d=i(d,e,f,c,b[2],23,0xC4AC5665);c=j(c,d,e,f,b[0],6,0xF4292244);f=j(f,c,d,e,b[7],10,0x432AFF97);e=j(e,f,c,d,b[14],15,0xAB9423A7);d=j(d,e,f,c,b[5],21,0xFC93A039);c=j(c,d,e,f,b[12],6,0x655B59C3);f=j(f,c,d,e,b[3],10,0x8F0CCC92);e=j(e,f,c,d,b[10],15,0xFFEFF47D);d=j(d,e,f,c,b[1],21,0x85845DD1);c=j(c,d,e,f,b[8],6,0x6FA87E4F);f=j(f,c,d,e,b[15],10,0xFE2CE6E0);e=j(e,f,c,d,b[6],15,0xA3014314);d=j(d,e,f,c,b[13],21,0x4E0811A1);c=j(c,d,e,f,b[4],6,0xF7537E82);f=j(f,c,d,e,b[11],10,0xBD3AF235);e=j(e,f,c,d,b[2],15,0x2AD7D2BB);d=j(d,e,f,c,b[9],21,0xEB86D391);a[0]=k(c,a[0]);a[1]=k(d,a[1]);a[2]=k(e,a[2]);a[3]=k(f,a[3])}}();function\nzg(a,b,c){var\ne=a.len&bb,d=0;a.len+=c;if(e){var\nf=64-e;if(c=64){a.b8.set(b.subarray(d,d+64),0);dP(a.w,a.b32);c-=64;d+=64}if(c)a.b8.set(b.subarray(d,d+c),0)}function\nze(a){var\nc=a.len&bb;a.b8[c]=ao;c++;if(c>56){for(var\nb=c;b<64;b++)a.b8[b]=0;dP(a.w,a.b32);for(var\nb=0;b<56;b++)a.b8[b]=0}else\nfor(var\nb=c;b<56;b++)a.b8[b]=0;a.b32[14]=a.len<<3;a.b32[15]=a.len>>29&0x1FFFFFFF;dP(a.w,a.b32);var\ne=new\nUint8Array(16);for(var\nd=0;d<4;d++)for(var\nb=0;b<4;b++)e[d*4+b]=a.w[d]>>8*b&0xFF;return e}function\nAe(a){return ak(cE(a,0,a.length))}function\nzY(a,b,c){var\nd=zf(),e=gm(a);zg(d,e.subarray(b,b+c),c);return Ae(ze(d))}function\nzZ(a,b,c){return zY(bd(a),b,c)}function\nz1(){return 0}var\nbf=new\nArray();function\nla(a){return bf[a]}function\nbz(a){var\nb=la(a);if(!b.opened)m(\"Cannot flush a closed channel\");if(!b.buffer||b.buffer_curr==0)return 0;if(b.output)b.output(cE(b.buffer,0,b.buffer_curr));else\nb.file.write(b.offset,b.buffer,0,b.buffer_curr);b.offset+=b.buffer_curr;b.buffer_curr=0;return 0}function\nAg(a,b){if(b.name)try{var\nd=require(fE),c=d.openSync(b.name,\"rs\");return new\nav(c,b)}catch(f){}return new\nav(a,b)}var\nd2=new\nArray(3);function\ncw(a,b){Y.call(this,F(0));this.log=function(a){return 0};if(a==1&&typeof\nconsole.log==\"function\")this.log=console.log;else if(a==2&&typeof\nconsole.error==\"function\")this.log=console.error;else if(typeof\nconsole.log==\"function\")this.log=console.log;this.flags=b}cw.prototype.length=function(){return 0};cw.prototype.write=function(a,b,c,d){if(this.log){if(d>0&&c>=0&&c+d<=b.length&&b[c+d-1]==10)d--;var\ne=F(d);aZ(f6(b),c,e,0,d);this.log(e.toUtf16());return 0}m(this.fd+jj)};cw.prototype.read=function(a,b,c,d){m(this.fd+\": file descriptor is write only\")};cw.prototype.close=function(){this.log=undefined};function\nd3(a,b){if(b==undefined)b=d2.length;d2[b]=a;return b|0}function\nAo(a,b,c){var\nd={};while(b){switch(b[1]){case\n0:d.rdonly=1;break;case\n1:d.wronly=1;break;case\n2:d.append=1;break;case\n3:d.create=1;break;case\n4:d.truncate=1;break;case\n5:d.excl=1;break;case\n6:d.binary=1;break;case\n7:d.text=1;break;case\n8:d.nonblock=1;break}b=b[2]}if(d.rdonly&&d.wronly)m(aJ(a)+f2);if(d.text&&d.binary)m(aJ(a)+fB);var\ne=lo(a),f=e.device.open(e.rest,d);return d3(f,undefined)}(function(){function\na(a,b){return cF()?Ag(a,b):new\ncw(a,b)}d3(a(0,{rdonly:1,altname:\"/dev/stdin\",isCharacterDevice:true}),0);d3(a(1,{buffered:2,wronly:1,isCharacterDevice:true}),1);d3(a(2,{buffered:2,wronly:1,isCharacterDevice:true}),2)}());function\nz2(a){var\nb=d2[a];if(b.flags.wronly)m(j0+a+\" is writeonly\");var\nd=null,c={file:b,offset:b.flags.append?b.length():0,fd:a,opened:true,out:false,buffer_curr:0,buffer_max:0,buffer:new\nUint8Array(j2),refill:d};bf[c.fd]=c;return c.fd}function\nlb(a){var\nb=d2[a];if(b.flags.rdonly)m(j0+a+\" is readonly\");var\nd=b.flags.buffered!==undefined?b.flags.buffered:1,c={file:b,offset:b.flags.append?b.length():0,fd:a,opened:true,out:true,buffer_curr:0,buffer:new\nUint8Array(j2),buffered:d};bf[c.fd]=c;return c.fd}function\nz3(){var\nb=0;for(var\na=0;ae.buffer.length){var\ng=new\nUint8Array(e.buffer_curr+b.length);g.set(e.buffer);e.buffer=g}switch(e.buffered){case\n0:e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;bz(a);break;case\n1:e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;if(e.buffer_curr>=e.buffer.length)bz(a);break;case\n2:var\nf=b.lastIndexOf(10);if(f<0){e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;if(e.buffer_curr>=e.buffer.length)bz(a)}else{e.buffer.set(b.subarray(0,f+1),e.buffer_curr);e.buffer_curr+=f+1;bz(a);e.buffer.set(b.subarray(f+1),e.buffer_curr);e.buffer_curr+=b.length-f-1}break}return 0}function\nz4(a,b,c,d){var\nb=gm(b);return z5(a,b,c,d)}function\ngg(a,b,c,d){return z4(a,bd(b),c,d)}function\nlc(a,b){var\nc=ak(String.fromCharCode(b));gg(a,c,0,1);return 0}function\nz6(a,b){if(b==0)gj();return a%b}function\ncD(a,b){return+(dR(a,b,false)!=0)}function\nz8(a,b){var\nd=new\nArray(b+1);d[0]=a;for(var\nc=1;c<=b;c++)d[c]=0;return d}function\nz9(a,b){a[0]=aD;a[1]=b;return 0}function\naw(a){if(a\ninstanceof\nArray&&a[0]==a[0]>>>0)return a[0];else if(dX(a))return dC;else if(dY(a))return dC;else if(a\ninstanceof\nFunction||typeof\na==\"function\")return 247;else if(a&&a.caml_custom)return jP;else\nreturn cu}function\nzl(a){var\nc={};if(a)for(var\nb=1;b=0)a=e;else\naj(\"caml_register_global: cannot locate \"+d)}}U[a+1]=b;if(c)U[c]=b}function\ngl(a,b){ld[aJ(a)]=b;return 0}function\nAd(){G(fz)}function\ny(a,b){if(b>>>0>=n(a))Ad();return _(a,b)}function\nd1(a){a.t&6&&cz(a);return ak(a.c)}function\nAf(){return 0x7FFFFFFF/4|0}function\nAa(){lf(U.Not_found)}function\nli(a){var\nb=ln(H(a));if(b===undefined)Aa();return as(b)}function\nAh(){if(p.crypto)if(p.crypto.getRandomValues){var\na=p.crypto.getRandomValues(new\nInt32Array(4));return[0,a[0],a[1],a[2],a[3]]}else if(p.crypto.randomBytes){var\na=new\nInt32Array(p.crypto.randomBytes(16).buffer);return[0,a[0],a[1],a[2],a[3]]}var\nb=new\nDate().getTime(),c=b^0xffffffff*Math.random();return[0,c]}function\nbA(a){var\nb=1;while(a&&a.joo_tramp){a=a.joo_tramp.apply(null,a.joo_args);b++}return a}function\nr(a,b){return{joo_tramp:a,joo_args:b}}function\nlk(a,b){if(b.fun){a.fun=b.fun;return 0}if(typeof\nb===\"function\"){a.fun=b;return 0}var\nc=b.length;while(c--)a[c]=b[c];return 0}function\nL(a){{if(a\ninstanceof\nArray)return a;var\nb;if(p.RangeError&&a\ninstanceof\np.RangeError&&a.message&&a.message.match(/maximum call stack/i))b=U.Stack_overflow;else if(p.InternalError&&a\ninstanceof\np.InternalError&&a.message&&a.message.match(/too much recursion/i))b=U.Stack_overflow;else if(a\ninstanceof\np.Error&&bg(fS))b=[0,bg(fS),a];else\nb=[0,U.Failure,as(String(a))];if(a\ninstanceof\np.Error)b.js_error=a;return b}}function\nzR(a){switch(a[2]){case-8:case-11:case-12:return 1;default:return 0}}function\nzv(a){var\nb=e;if(a[0]==0){b+=a[1][1];if(a.length==3&&a[2][0]==0&&zR(a[1]))var\nf=a[2],g=1;else\nvar\ng=2,f=a;b+=\"(\";for(var\nd=g;dg)b+=ju;var\nc=f[d];if(typeof\nc==\"number\")b+=c.toString();else if(c\ninstanceof\naY)b+=dB+c.toString()+dB;else if(typeof\nc==\"string\")b+=dB+c.toString()+dB;else\nb+=kr}b+=\")\"}else if(a[0]==q)b+=a[1];return b}function\nk1(a){if(a\ninstanceof\nArray&&(a[0]==0||a[0]==q)){var\nc=bg(kv);if(c)dQ(c,[a,false]);else{var\nd=zv(a),b=bg(j3);if(b)dQ(b,[0]);console.error(fV+d);if(a.js_error)throw a.js_error}}else\nthrow a}function\nAc(){var\nc=p.process;if(c&&c.on)c.on(\"uncaughtException\",function(a,b){k1(a);c.exit(2)});else if(p.addEventListener)p.addEventListener(jn,function(a){if(a.error)k1(a.error)})}Ac();function\nh(a,b){return(a.l>=0?a.l:a.l=a.length)==1?a(b):be(a,[b])}function\ni(a,b,c){return(a.l>=0?a.l:a.l=a.length)==2?a(b,c):be(a,[b,c])}function\nx(a,b,c,d){return(a.l>=0?a.l:a.l=a.length)==3?a(b,c,d):be(a,[b,c,d])}function\nfu(a,b,c,d,e,f){return(a.l>=0?a.l:a.l=a.length)==5?a(b,c,d,e,f):be(a,[b,c,d,e,f])}function\nzd(a,b,c,d,e,f,g,h){return(a.l>=0?a.l:a.l=a.length)==7?a(b,c,d,e,f,g,h):be(a,[b,c,d,e,f,g,h])}var\nAn=undefined;zw();var\nd6=[q,kM,-1],gr=[q,jW,-2],b3=[q,f3,-3],cH=[q,jx,-4],ax=[q,jA,-7],gp=[q,kI,-8],gq=[q,ke,-9],f=[q,kn,-11],b4=[q,kA,-12],zc=[4,0,0,0,[12,45,[4,0,0,0,0]]],eq=[0,[11,'File \"',[2,0,[11,'\", line ',[4,0,0,0,[11,kK,[4,0,0,0,[12,45,[4,0,0,0,[11,kG,[2,0,0]]]]]]]]]],'File \"%s\", line %d, characters %d-%d: %s'],i1=f1,br=\"content\",i7=\"columns\",i8=\"rows\",fo=jN,fp=f1,i9=cq,i_=\"page_content\";ar(11,b4,kA);ar(10,f,kn);ar(9,[q,ks,-10],ks);ar(8,gq,ke);ar(7,gp,kI);ar(6,ax,jA);ar(5,[q,jS,-6],jS);ar(4,[q,j6,-5],j6);ar(3,cH,jx);ar(2,b3,f3);ar(1,gr,jW);ar(0,d6,kM);var\nly=\"output_substring\",lu=a$,lr=\"true\",ls=\"false\",lC=\"CamlinternalLazy.Undefined\",lG=\"option is None\",lK=\"\\\\\\\\\",lL=\"\\\\'\",lM=\"\\\\b\",lN=\"\\\\t\",lO=\"\\\\n\",lP=\"\\\\r\",lX=\"List.init\",lU=\"hd\",l9=\"String.blit / Bytes.blit_string\",l8=\"Bytes.blit\",l7=\"String.sub / Bytes.sub\",mg=\"String.contains_from / Bytes.contains_from\",mn=\"Array.blit\",mm=\"Array.sub\",mk=\"Array.init\",mu=[0,\"set.ml\",570,18],mq=dI,mr=dI,ms=dI,mt=dI,mB=\"Map.remove_min_elt\",mx=dM,my=dM,mz=dM,mA=dM,mC=\"Stdlib.Stack.Empty\",mG=\"Stdlib.Queue.Empty\",mS=\"Buffer.add_substring/add_subbytes\",mP=\"Buffer.add: cannot grow buffer\",mO=[0,je,93,2],mN=[0,je,94,2],mL=\"Buffer.sub\",m3=\"%c\",m4=\"%s\",m5=jE,m6=js,m7=kO,m8=jy,m9=\"%f\",m_=\"%B\",m$=\"%{\",na=\"%}\",nb=\"%(\",nc=\"%)\",nd=\"%a\",ne=\"%t\",nf=\"%?\",ng=\"%r\",nh=\"%_r\",ni=[0,K,850,23],nt=[0,K,814,21],nl=[0,K,815,21],nu=[0,K,818,21],nm=[0,K,819,21],nv=[0,K,822,19],nn=[0,K,823,19],nw=[0,K,826,22],no=[0,K,827,22],nx=[0,K,831,30],np=[0,K,832,30],nr=[0,K,836,26],nj=[0,K,837,26],ns=[0,K,846,28],nk=[0,K,847,28],nq=[0,K,851,23],oJ=[0,K,1558,4],oK=\"Printf: bad conversion %[\",oL=[0,K,1626,39],oM=[0,K,1649,31],oN=[0,K,1650,31],oO=\"Printf: bad conversion %_\",oP=jR,oQ=kq,oR=jR,oS=kq,oW=[0,[11,\"invalid box description \",[3,0,0]],\"invalid box description %S\"],oV=[0,0,4],oE=fD,oC=\"neg_infinity\",oD=j1,oB=a$,ow=[0,jg],ok=\"%+nd\",ol=\"% nd\",on=\"%+ni\",oo=\"% ni\",op=\"%nx\",oq=\"%#nx\",or=\"%nX\",os=\"%#nX\",ot=\"%no\",ou=\"%#no\",oj=\"%nd\",om=kO,ov=\"%nu\",n8=\"%+ld\",n9=\"% ld\",n$=\"%+li\",oa=\"% li\",ob=\"%lx\",oc=\"%#lx\",od=\"%lX\",oe=\"%#lX\",of=\"%lo\",og=\"%#lo\",n7=\"%ld\",n_=js,oh=\"%lu\",nU=\"%+Ld\",nV=\"% Ld\",nX=\"%+Li\",nY=\"% Li\",nZ=\"%Lx\",n0=\"%#Lx\",n1=\"%LX\",n2=\"%#LX\",n3=\"%Lo\",n4=\"%#Lo\",nT=\"%Ld\",nW=jy,n5=\"%Lu\",nG=\"%+d\",nH=\"% d\",nJ=\"%+i\",nK=\"% i\",nL=\"%x\",nM=\"%#x\",nN=\"%X\",nO=\"%#X\",nP=\"%o\",nQ=\"%#o\",nF=fx,nI=jE,nR=j9,mV=\"@]\",mW=\"@}\",mX=\"@?\",mY=\"@\\n\",mZ=\"@.\",m0=\"@@\",m1=\"@%\",m2=\"@\",ny=\"CamlinternalFormat.Type_mismatch\",o1=e,o2=[0,[11,ju,[2,0,[2,0,0]]],\", %s%s\"],py=[0,[11,fV,[2,0,[12,10,0]]],kb],pz=[0,[11,\"Fatal error in uncaught exception handler: exception \",[2,0,[12,10,0]]],\"Fatal error in uncaught exception handler: exception %s\\n\"],px=\"Fatal error: out of memory in uncaught exception handler\",pu=[0,[11,fV,[2,0,[12,10,0]]],kb],po=[0,[2,0,[12,10,0]],\"%s\\n\"],pp=[0,[11,jQ,0],jQ],pf=\"Raised at\",pg=\"Re-raised at\",ph=\"Raised by primitive operation at\",pi=\"Called from\",pj=\" (inlined)\",pl=e,pk=[0,[2,0,[12,32,[2,0,[11,' in file \"',[2,0,[12,34,[2,0,[11,\", line \",[4,0,0,0,[11,kK,zc]]]]]]]]]],'%s %s in file \"%s\"%s, line %d, characters %d-%d'],pm=[0,[2,0,[11,\" unknown location\",0]],\"%s unknown location\"],o_=\"Out of memory\",o$=\"Stack overflow\",pa=\"Pattern matching failed\",pb=\"Assertion failed\",pc=\"Undefined recursive module\",o4=[0,[12,40,[2,0,[2,0,[12,41,0]]]],\"(%s%s)\"],o5=e,o6=e,o7=[0,[12,40,[2,0,[12,41,0]]],\"(%s)\"],o0=[0,[4,0,0,0,0],fx],oY=[0,[3,0,0],\"%S\"],oZ=kr,pr=[0,e,\"(Cannot print locations:\\n bytecode executable program file not found)\",\"(Cannot print locations:\\n bytecode executable program file appears to be corrupt)\",\"(Cannot print locations:\\n bytecode executable program file has wrong magic number)\",\"(Cannot print locations:\\n bytecode executable program file cannot be opened;\\n -- too many open files. Try running with OCAMLRUNPARAM=b=2)\"],pD=\"Fun.Finally_raised: \",pB=\"Stdlib.Fun.Finally_raised\",pH=\"x\",pO=\"Hashtbl: unsupported hash table format\",pK=e,qz=[3,0,3],qA=a$,qt=kt,qu=\"<\\/\",qv=e,qp=kt,qq=\"<\",qr=e,qn=\"\\n\",qi=e,qj=e,qk=e,ql=e,p6=[0,e],p1=e,p2=e,p3=e,p4=e,pX=[0,e,0,e],pT=\"Stdlib.Format.String_tag\",qM=[0,j8,72,5],qN=[0,j8,81,2],qO=\"CamlinternalMod.update_mod: not a module\",qK=\"CamlinternalMod.init_mod: not a module\",qP=\"Jsoo_runtime.Error.Exn\",qQ=fS,qU=[0,b,jr,10],qW=[0,b,179,10],qY=[0,b,191,10],q1=[0,b,kN,17],q_=[0,b,367,16],q$=[0,b,368,18],ra=[0,b,372,15],rb=[0,b,377,15],rc=[0,b,kw,15],rd=[0,b,386,10],re=[0,b,362,16],rf=[0,b,517,12],rg=[0,b,kB,14],rr=[0,b,686,27],rq=[0,b,651,27],rk=[0,b,560,16],rh=[0,b,550,23],ri=[0,b,544,14],q9=[0,b,334,9],q5=[0,b,309,9],q4=[0,b,305,9],q3=[0,[11,\"Lwd: unsafe mutation (variable invalidated during evaluation) at\\n\",[15,0]],\"Lwd: unsafe mutation (variable invalidated during evaluation) at\\n%a\"],q0=[0,b,jK,14],qX=[0,b,186,14],qV=[0,b,169,14],qT=[0,b,152,14],rl=\"Lwd.Release_failure\",ry=[0,a,64,12],rI=[0,a,bu,21],rR=[0,a,205,18],rQ=[0,a,kN,9],rT=[0,a,224,18],rS=[0,a,237,9],rU=[0,a,240,21],rV=[0,a,aD,21],rW=[0,a,260,21],rY=[0,a,296,14],sl=[0,a,553,18],sm=[0,a,557,12],sn=[0,a,546,14],sk=[0,a,538,21],si=[0,a,531,14],sg=[0,a,523,14],se=[0,a,ky,29],sd=[0,a,499,29],sc=[0,a,462,21],r9=[0,a,420,10],r_=[0,a,423,15],r$=[0,a,435,10],sa=[0,a,457,2],r4=[0,a,371,24],r5=[0,a,391,16],r6=[0,a,394,2],r1=[0,a,315,18],r0=[0,a,317,9],rN=[0,a,193,4],rM=[0,a,jK,21],rK=[0,a,jp,4],rL=[0,a,177,14],rF=[0,a,113,14],rD=[0,a,jL,14],rB=[0,a,93,14],rz=[0,a,82,21],rx=[0,a,39,4],rw=[0,a,45,21],ru=[0,a,32,14],sQ=[0,X,571,12],sB=[0,X,321,37],sC=[0,X,322,37],sE=[0,X,346,10],sF=[0,X,357,42],sD=[0,X,337,37],sH=[0,X,375,10],sI=[0,X,kw,42],sG=[0,X,338,37],sL=[0,X,425,16],sO=[0,X,513,50],sM=[0,X,480,6],sK=[0,X,395,14],st=[0,X,jp,57],su=[0,X,182,57],sv=[0,X,238,11],so=kk,sp=kk,tF=\"debug\",tE=\"warn\",tC=jn,tA=\"log\",tJ=\"isSecureContext\",t0=[0,jO,233,16],tY=[0,jO,201,16],tT=[0,0,0],tR=[0,0,0],uv=e,uu=e,uk=[0,[0,S,kc],0],ul=[0,[0,S,f0],[0,aG,0]],um=[0,[0,S,fO],[0,aG,0]],un=[0,[0,S,fG],[0,aG,0]],uo=[0,[0,S,fK],[0,aG,0]],up=[0,[0,S,fT],[0,aG,0]],uq=[0,[0,S,fW],[0,aG,0]],ur=[0,[0,S,fR],[0,aG,0]],us=[0,[0,S,kc],[0,aG,0]],ub=[0,[0,S,f0],0],uc=[0,[0,S,fO],0],ud=[0,jG,0],ue=[0,[0,S,fG],0],uf=[0,[0,S,fK],0],ug=[0,[0,S,fT],0],uh=[0,[0,S,fW],0],ui=[0,aG,0],uj=[0,[0,S,fR],0],t$=[0,[11,\"\\x1b[\",[4,0,0,0,[12,109,0]]],\"\\x1b[%dm\"],ua=\"CCFormat.ANSI_codes.No_such_style\",uw=\"CCFormat.Style\",uR=[0,0],uS=\"CCFQueue.Empty\",uT=[0,0],u3=\"content-box\",u4=\"border-box\",u5=\"device-pixel-content-box\",vg=j$,vd=[0,[8,[0,0,0],0,0,[11,kC,0]],\"%fpx\"],ve=[0,[8,[0,0,0],0,0,[11,j_,0]],\"%frem\"],vf=[0,[8,[0,0,0],0,0,[11,jZ,0]],\"%fem\"],va=kC,vb=j_,vc=jZ,vj=\"Common.Utils.Forward_ref.Not_set\",vl=\"Common.Utils.Forward_ref.Already_set\",vp=[1,[0,3854881,\"Failed to unmarshal data\"]],vt=[1,-358247754],vr=[0,[11,\"Multiple persitent var are using the key \",[2,0,0]],\"Multiple persitent var are using the key %s\"],vD=\"TODO not implemented\",vJ=[0,80,[0,\"lwdui-controlled-scroll-wrapper\"]],vK=[0,80,\"lwdui-controlled-scroll-controls\"],vL=\"Show playing\",vP=jv,vN=e,vO=bW,vS=[0,80,bW],vQ=[0,[2,0,[11,\"--id\",0]],\"%s--id\"],vT=[0,[2,0,[11,\"-id\",0]],\"%s-id\"],vU=[0,80,\"checkbox\"],v6=[0,[11,kx,[2,0,0]],\"height: %s\"],v2=[0,[2,0,[12,32,[2,0,0]]],\"%s %s\"],v0=\"grid-template-columns\",v1=[0,[2,0,[11,kG,[2,0,[12,59,0]]]],\"%s: %s;\"],v3=e,v7=[1,4.],wa=[0,80,jk],v_=[0,[11,\"height: calc(\",[2,0,[11,\" * \",[4,3,0,0,[11,\");\",0]]]]],\"height: calc(%s * %i);\"],v$=[0,[11,kx,[2,0,[11,\" !important;\",0]]],\"height: %s !important;\"],wb=[0,80,[0,\"lwdui-lazy-table-content\"]],wc=[0,80,[0,\"lwdui-lazy-table-content-wrapper\"]],wd=[0,\"lwdui-lazy-table\",0],wu=[0,[3,0,[11,\" is not a valid action\",0]],\"%S is not a valid action\"],wm=\"retain\",wn=\"insert\",wo=jF,wp=[0,fN,72,22],wh=[0,[0,0,0,0,0,0,0]],wi=[0,fN,49,6],wj=[0,[0,0,[0,[0,0]],0,0,0,0,0,0]],wk=[0,fN,jr,6],wq=[0,[0,0,0,0,0,0,0]],wv=[0,[0,0,[0,[0,0]],0,0,0,0,0,0]],wK=[0,[11,\"stun:\",[2,0,0]],\"stun:%s\"],wI=\"signaling\",wJ=[0,\"stun.l.google.com:19302\",[0,\"stun2.l.google.com:19302\",[0,\"stun3.l.google.com:19302\",[0,\"stun4.l.google.com:19302\",0]]]],wL=\"peerOpts\",wP=\"bubble\",wR=\"snow\",wQ=\"cursors\",w3=[0,[11,\"vector length is \",[4,0,0,0,[11,\", but data array has length \",[4,0,0,0,[11,\" (racy access?)\",0]]]]],\"vector length is %d, but data array has length %d (racy access?)\"],w1=[0,[11,\"index \",[4,0,0,0,[11,\" is out of range [0, \",[4,0,0,0,[12,41,0]]]]],\"index %d is out of range [0, %d)\"],wX=[0,[11,\"invalid segment (ofs = \",[4,0,0,0,[11,\", len = \",[4,0,0,0,[11,\") in a sequence of length \",[4,0,0,0,0]]]]]],\"invalid segment (ofs = %d, len = %d) in a sequence of length %d\"],xe=\"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\",y5=\"tbl\",y6=[0,\"Create new table:\",0],y1=j$,y2=[0,80,[0,dH]],y3=[0,80,[0,jw]],yW=\"Found\",yX=jh,yY=\"1fr\",yZ=\"a\",yV=[2,5.],yT=[0,c,776,19],yS=[0,80,\"Add row\"],yL=[0,1],yK=\"Add map with id \",yM=[0,1],yP=e,yQ=e,yN=[0,a_,1],yO=[0,a_,0],yR=[0,c,757,18],yH=[0,c,705,25],yG=e,yI=[0,c,697,23],yE=jH,yF=\"Form valid:\",yx=[0,0,0],yy=[0,80,\"Add column\"],yz=[0,[0,cs,\"String\"],[0,[0,dK,\"Checkbox\"],[0,[0,bW,\"Richtext\"],0]]],yA=[0,f1,cs,0],yB=[0,0],yC=[0,\"demo\"],yD=[0,1],yu=\"DELETE ROW\",yv=jh,yt=[0,c,617,17],yp=[0,1],yq=[0,1],yr=[0,80,[0,fF]],yl=e,ym=e,yn=[0,80,[0,fF]],yg=jH,yh=\" -> \",yf=[0,0],yd=[0,0],ye=[0,80,\"Update\"],x$=e,ya=e,yb=[0,80,[0,\"cell-edit-btn\"]],yc=\"\\xe2\\x9c\\x8f\\xef\\xb8\\x8f\",yi=[0,80,[0,\"cell-edit-overlay\"]],yj=[0,80,[0,fF]],xW=\"GET\",xV=[0,c,419,17],xU=[0,c,434,11],xZ=[0,c,449,19],xY=[0,c,kB,13],xX=[0,c,439,13],x0=[0,c,466,11],x6=[0,c,484,19],x5=[0,c,479,19],x1=[0,c,472,13],x3=[0,c,488,15],x4=[0,c,ky,15],x2=[0,c,493,11],x8=e,x9=[0,c,505,17],x7=[0,c,508,11],xP=cq,xQ=jY,xJ=\"New column kind:\",xH=[0,c,294,13],xD=dK,xE=bW,xF=dH,xG=cs,xz=\"Old value:\",xA=\"Action: delete\",xB=\"Key:\",xC=[0,c,219,15],xy=\"On_change\",xx=[0,c,144,22],xv=\"[blit v(%i) %i %i v'(%i)]\",xs=[0,c,87,18],xp=\"PEERS\",xn=\"STATUS\",xl=[0,\"SYNCED!\",0],xh=\"modules/cursors\",xi=[0,[0,\"wss://p2p.u31.fr\",0]],xj=\"testroom5267564\",xk=\"zedoc\",xm=\"synced\",xo=\"status\",xq=\"peers\",xM=cq,xN=jY,y7=[0,80,\"Add table\"],y_=[0,80,[0,jw]];function\nz(a){if(typeof\na===\"number\")return 0;switch(a[0]){case\n0:return[0,z(a[1])];case\n1:return[1,z(a[1])];case\n2:return[2,z(a[1])];case\n3:return[3,z(a[1])];case\n4:return[4,z(a[1])];case\n5:return[5,z(a[1])];case\n6:return[6,z(a[1])];case\n7:return[7,z(a[1])];case\n8:var\nc=a[1];return[8,c,z(a[2])];case\n9:var\nb=a[1];return[9,b,b,z(a[3])];case\n10:return[10,z(a[1])];case\n11:return[11,z(a[1])];case\n12:return[12,z(a[1])];case\n13:return[13,z(a[1])];default:return[14,z(a[1])]}}function\nW(a,b){if(typeof\na===\"number\")return b;switch(a[0]){case\n0:return[0,W(a[1],b)];case\n1:return[1,W(a[1],b)];case\n2:return[2,W(a[1],b)];case\n3:return[3,W(a[1],b)];case\n4:return[4,W(a[1],b)];case\n5:return[5,W(a[1],b)];case\n6:return[6,W(a[1],b)];case\n7:return[7,W(a[1],b)];case\n8:var\nc=a[1];return[8,c,W(a[2],b)];case\n9:var\nd=a[2],e=a[1];return[9,e,d,W(a[3],b)];case\n10:return[10,W(a[1],b)];case\n11:return[11,W(a[1],b)];case\n12:return[12,W(a[1],b)];case\n13:return[13,W(a[1],b)];default:return[14,W(a[1],b)]}}function\nw(a,b){if(typeof\na===\"number\")return b;switch(a[0]){case\n0:return[0,w(a[1],b)];case\n1:return[1,w(a[1],b)];case\n2:var\nc=a[1];return[2,c,w(a[2],b)];case\n3:var\nd=a[1];return[3,d,w(a[2],b)];case\n4:var\ne=a[3],f=a[2],g=a[1];return[4,g,f,e,w(a[4],b)];case\n5:var\nh=a[3],i=a[2],j=a[1];return[5,j,i,h,w(a[4],b)];case\n6:var\nk=a[3],l=a[2],m=a[1];return[6,m,l,k,w(a[4],b)];case\n7:var\nn=a[3],o=a[2],p=a[1];return[7,p,o,n,w(a[4],b)];case\n8:var\nq=a[3],r=a[2],s=a[1];return[8,s,r,q,w(a[4],b)];case\n9:var\nt=a[1];return[9,t,w(a[2],b)];case\n10:return[10,w(a[1],b)];case\n11:var\nu=a[1];return[11,u,w(a[2],b)];case\n12:var\nv=a[1];return[12,v,w(a[2],b)];case\n13:var\nx=a[2],y=a[1];return[13,y,x,w(a[3],b)];case\n14:var\nz=a[2],A=a[1];return[14,A,z,w(a[3],b)];case\n15:return[15,w(a[1],b)];case\n16:return[16,w(a[1],b)];case\n17:var\nB=a[1];return[17,B,w(a[2],b)];case\n18:var\nC=a[1];return[18,C,w(a[2],b)];case\n19:return[19,w(a[1],b)];case\n20:var\nD=a[2],E=a[1];return[20,E,D,w(a[3],b)];case\n21:var\nF=a[1];return[21,F,w(a[2],b)];case\n22:return[22,w(a[1],b)];case\n23:var\nG=a[1];return[23,G,w(a[2],b)];default:var\nH=a[2],I=a[1];return[24,I,H,w(a[3],b)]}}function\nd4(a){return[0,a]}function\ncG(a){return a[1]}function\nd5(a,b,c){return a[1]===b?(a[1]=c,1):0}function\naK(a){throw g([0,b3,a],1)}function\nt(a){throw g([0,cH,a],1)}function\ncI(a){return 0<=a?a:-a|0}var\ngs=kz;function\nay(a,b){return a+b}function\nlt(b){var\ne=n(b);return function(a){var\nc=a;for(;;){if(e<=c)return ay(b,lu);var\nd=y(b,c);a:{if(48<=d){if(58>d)break a}else if(45===d)break a;return b}c=c+1|0}}(0)}function\ngt(a,b){if(!a)return b;var\nc=a[1];return[0,c,gt(a[2],b)]}z2(0);var\nlw=lb(1),at=lb(2);function\nb5(a,b){gg(a,b,0,n(b));return}function\ngu(a){b5(at,a);lc(at,10);return bz(at)}var\nd7=d4(function(a){return function(a){var\nb=a;for(;;){if(!b)return 0;var\nd=b[2],e=b[1];try{bz(e)}catch(f){var\nc=L(f);if(c[1]!==gr)throw g(c,0)}b=d}}(z3(0))});function\nd8(a){return h(cG(d7),0)}gl(j3,d8);function\nlp(a){return a^-1}function\nlq(a){return a?lr:ls}function\nlv(a){return lt(f9(\"%.12g\",a))}function\nlx(a,b,c,d){if(0<=c&&0<=d&&(n(b)-d|0)>=c)return gg(a,b,c,d);return t(ly)}function\nlz(c){for(;;){var\nd=d4(1),a=cG(d7);let\ne=d,f=a;var\nb=1-d5(d7,a,function(a){if(d5(e,1,0))h(c,0);return h(f,0)});if(!b)return b}}function\ncJ(a){return bz(a)}function\nlA(a,b){lc(a,b);return}var\nd9=Af(0),b6=(4*d9|0)-1|0;function\nlB(a){return 1-(typeof\na===\"number\"?1:0)}var\nlD=[q,lC,ae(0)];function\nlE(a){throw g(lD,1)}function\ncK(a){var\nd=a[1];a[1]=lE;try{var\nc=h(d,0);z9(a,c);return c}catch(f){var\nb=L(f);a[1]=function(a){throw g(b,0)};throw g(b,0)}}function\nlF(a){var\nb=aw(a);if(b!==aD&&b!==ba&&b!==kl)return a;return zU(a)}function\ncL(a){return a?a[1]:t(lG)}function\ngv(a){return a?1:0}function\nlH(a,b){return b?[0,h(a,b[1])]:0}function\nlI(a,b){return a===b?1:0}function\nlJ(a){a:{if(40<=a){if(92===a)return lK;if(fZ>a)break a}else{if(32<=a){if(39<=a)return lL;break a}if(14>a)switch(a){case\n8:return lM;case\n9:return lN;case\n10:return lO;case\n13:return lP}}var\nb=F(4);A(b,0,92);A(b,1,48+(a/fI|0)|0);A(b,2,48+((a/10|0)%10|0)|0);A(b,3,48+(a%10|0)|0);return d1(b)}var\nc=F(1);A(c,0,a);return d1(c)}function\nlQ(a){return 25>>0?a:a+kH|0}function\nlR(a,b){var\nd=a,c=b;for(;;){if(!c)return d;d=d+1|0;c=c[2]}}function\ngw(a){return lR(0,a)}function\nbB(a,b){var\nc=a,d=b;for(;;){if(!c)return d;var\ne=[0,c[1],d];c=c[2];d=e}}function\na3(a){return bB(a,0)}function\ngx(a,b,c){if(b<=a)return 0;var\nd=h(c,a);return[0,d,gx(a+1|0,b,c)]}function\nlS(a,b){return[0,a,b]}function\nlT(a){return a?a[1]:aK(lU)}function\nlV(a,b,c,d){var\nf=a,e=b;for(;;){if(c<=e)return f;f=[0,h(d,e),f];e=e+1|0}}function\nd_(a){if(!a)return 0;var\nb=a[1];return gt(b,d_(a[2]))}function\ncM(a,b){if(!b)return 0;var\nc=b[2],d=h(a,b[1]);return[0,d,cM(a,c)]}function\na4(a,b){var\nc=b;for(;;){if(!c)return 0;var\nd=c[2];h(a,c[1]);c=d}}function\ngy(a,b,c){var\ne=b,d=c;for(;;){if(!d)return e;var\nf=d[2];e=i(a,e,d[1]);d=f}}function\nlW(a,b){return 0<=a?50>1,s=p(r,b),D=s[1],t=p(a-r|0,s[2]),E=t[2];return[0,B(D,t[1],0),E]}function\np(a,b){if(2===a){if(b){var\nj=b[2];if(j){var\nk=j[1],g=b[1],B=j[2],q=i(d,g,k),C=0===q?[0,g,0]:0>1,s=h(r,b),D=s[1],t=h(a-r|0,s[2]),E=t[2];return[0,A(D,t[1],0),E]}var\na=gw(b);return 2<=a?h(a,b)[1]:b}function\ngz(a,b){return b<=a?a:b}function\ngA(a){return e+a}function\nl3(a,b){return k7(a,b)}function\nl4(a,b){return a<=b?a:b}function\nbh(a,b){var\nc=F(a);zt(c,0,a,b);return c}var\nl5=F(0);function\ngB(a){var\nb=aq(a),c=F(b);aZ(a,0,c,0,b);return c}function\nd$(a,b,c){if(0<=b&&0<=c&&(aq(a)-c|0)>=b){var\nd=F(c);aZ(a,b,d,0,c);return d}return t(l7)}function\nea(a,b,c){return d1(d$(a,b,c))}function\ngC(a,b,c,d,e){if(0<=e&&0<=b&&(aq(a)-e|0)>=b&&0<=d&&(aq(c)-e|0)>=d){aZ(a,b,c,d,e);return}return t(l8)}function\naL(a,b,c,d,e){if(0<=e&&0<=b&&(n(a)-e|0)>=b&&0<=d&&(aq(c)-e|0)>=d){cy(a,b,c,d,e);return}return t(l9)}function\ngD(a){var\nb=a-9|0;a:{if(4>>0){if(23!==b)break a}else if(2===b)break a;return 1}return 0}function\nma(a,b){var\nd=aq(b);if(0===d)return b;var\ne=F(d),f=d-1|0,g=0;if(f>=0){var\nc=g;for(;;){A(e,c,h(a,bY(b,c)));var\ni=c+1|0;if(f===c)break;c=i}}return e}function\ngE(a,b,c){zo(a,b,zG(c));return}function\ngF(a,b,c){a0(a,b,c);return}function\ngG(a,b){return zn(a,b)}function\ncN(a){return bd(a)}function\n$(a){return d1(a)}function\nl6(a){return gB(bd(a))}function\nl_(a){var\nd=aq(a),b=[0,0];for(;;){if(b[1]>=d)break;if(!gD(bY(a,b[1])))break;b[1]++}var\nc=[0,d-1|0];for(;;){if(b[1]<=c[1]&&gD(bY(a,c[1]))){c[1]--;continue}return b[1]<=c[1]?d$(a,b[1],(c[1]-b[1]|0)+1|0):l5}}function\nl$(a){var\nb=[0,0],j=aq(a)-1|0,l=0;if(j>=0){var\ng=l;for(;;){var\ne=bY(a,g);a:{b:{c:{if(32<=e){var\nh=e-34|0;if(58>>0){if(93<=h)break c}else if(56>>0)break b;var\ni=1;break a}if(11<=e){if(13===e)break b}else if(8<=e)break b}var\ni=4;break a}var\ni=2}b[1]=b[1]+i|0;var\no=g+1|0;if(j===g)break;g=o}}if(b[1]===aq(a))return gB(a);var\nc=F(b[1]);b[1]=0;var\nk=aq(a)-1|0,m=0;if(k>=0){var\nf=m;for(;;){var\nd=bY(a,f);a:{b:{c:{if(35<=d){if(92!==d){if(fZ<=d)break c;break b}}else{if(32>d){if(14<=d)break c;switch(d){case\n8:A(c,b[1],92);b[1]++;A(c,b[1],98);break a;case\n9:A(c,b[1],92);b[1]++;A(c,b[1],116);break a;case\n10:A(c,b[1],92);b[1]++;A(c,b[1],110);break a;case\n13:A(c,b[1],92);b[1]++;A(c,b[1],114);break a;default:break c}}if(34>d)break b}A(c,b[1],92);b[1]++;A(c,b[1],d);break a}A(c,b[1],92);b[1]++;A(c,b[1],48+(d/fI|0)|0);b[1]++;A(c,b[1],48+((d/10|0)%10|0)|0);b[1]++;A(c,b[1],48+(d%10|0)|0);break a}A(c,b[1],d)}b[1]++;var\nn=f+1|0;if(k===f)break;f=n}}return c}function\nmb(a){return ma(lQ,a)}function\ncO(a,b){return $(bh(a,b))}function\neb(a,b,c){return $(d$(cN(a),b,c))}function\ngH(a){var\nb=a-9|0;a:{if(4>>0){if(23!==b)break a}else if(2===b)break a;return 1}return 0}function\nme(a,b,c,d){var\ne=c;for(;;){if(b<=e)throw g(ax,1);if(_(a,e)===d)return e;e=e+1|0}}function\nmf(a,b,c){var\nd=n(a);if(0<=b&&d>=b)try{me(a,d,b,c);var\nf=1;return f}catch(f){var\ne=L(f);if(e===ax)return 0;throw g(e,0)}return t(mg)}function\nec(a,b){return lh(a,b)}function\nmc(a){if(a==e)return a;if(!gH(_(a,0))&&!gH(_(a,n(a)-1|0)))return a;return $(l_(cN(a)))}function\nmd(a){return function(a,b,c){var\nd=c;for(;;){if(b<=d)return a;var\ne=_(a,d)+kH|0;a:{if(59>>0){if(33>>0)break a}else if(2===e)break a;d=d+1|0;continue}return $(l$(cN(a)))}}(a,n(a),0)}function\nmh(a,b){return mf(a,0,b)}function\nmi(a){return $(mb(cN(a)))}function\nmj(a,b){return a==b?1:0}function\ngI(a,b){if(0===a)return[0];if(0>a)return t(mk);var\nd=ap(a,h(b,0)),e=a-1|0,f=1;if(e>=1){var\nc=f;for(;;){d[1+c]=h(b,c);var\ng=c+1|0;if(e===c)break;c=g}}return d}function\ncP(a,b,c,d,e){if(0<=e&&0<=b&&(a.length-1-e|0)>=b&&0<=d&&(c.length-1-e|0)>=d)return zh(a,b,c,d,e);return t(mn)}function\ngJ(a,b){var\nd=b.length-2|0,e=0;if(d>=0){var\nc=e;for(;;){h(a,b[1+c]);var\nf=c+1|0;if(d===c)break;c=f}}return 0}function\ngK(a,b){var\nd=b.length-1;if(0===d)return[0];var\ne=ap(d,h(a,b[1])),f=d-1|0,g=1;if(f>=1){var\nc=g;for(;;){e[1+c]=h(a,b[1+c]);var\ni=c+1|0;if(f===c)break;c=i}}return e}function\nmo(a,b){var\nd=a,c=b;for(;;){if(!c)return d;d=d+1|0;c=c[2]}}function\ngL(a){if(!a)return[0];var\nb=a[2],c=a[1],e=ap(mo(0,a),c);return function(a,b){var\nd=a,c=b;for(;;){if(!c)return e;var\nf=c[2];e[1+d]=c[1];d=d+1|0;c=f}}(1,b)}function\nml(a,b,c){if(0<=b&&0<=c&&(a.length-1-c|0)>=b)return zi(a,b,c);return t(mm)}function\nmp(k){function\nj(a){return a?a[4]:0}function\nd(a,b,c){var\nd=a?a[4]:0,e=c?c[4]:0,f=e<=d?d+1|0:e+1|0;return[0,a,b,c,f]}function\nl(a,b,c){var\ng=a?a[4]:0,h=c?c[4]:0;if((h+2|0)=h){var\nw=h<=g?g+1|0:h+1|0;return[0,a,b,c,w]}if(!c)return t(mt);var\nk=c[3],m=c[2],f=c[1],r=j(f);if(r<=j(k))return d(d(a,b,f),m,k);if(!f)return t(ms);var\ns=f[2],u=f[1],v=d(f[3],m,k);return d(d(a,b,u),s,v)}function\nc(a,b){if(!b)return[0,0,a,0,1];var\nd=b[3],e=b[2],f=b[1],g=i(k[1],a,e);if(0===g)return b;if(0<=g){var\nh=c(a,d);return d===h?b:l(f,e,h)}var\nj=c(a,f);return f===j?b:l(j,e,d)}function\nb(a){return[0,0,a,0,1]}var\nm=0;function\ne(a,b){var\nc=b;for(;;){if(!c)return;var\nd=c[3],f=c[2];e(a,c[1]);h(a,f);c=d}}function\nn(a,b){var\nd=a,c=b;for(;;){if(!c)return d;var\ne=c[2],f=c[1];d=[0,e,n(d,c[3])];c=f}}function\no(a,b,c){var\nd=c;for(;;){if(!d)return;var\ne=d[3],f=d[1];d=h(b,d[2])?e:f}}function\np(a){function\nc(a,b){if(3>=a>>>0)switch(a){case\n0:return[0,0,b];case\n1:if(b)return[0,[0,0,b[1],0,1],b[2]];break;case\n2:if(b){var\nh=b[2];if(h)return[0,[0,[0,0,b[1],0,1],h[1],0,2],h[2]]}break;default:if(b){var\ni=b[2];if(i){var\nj=i[2];if(j)return[0,[0,[0,0,b[1],0,1],i[1],[0,0,j[1],0,1],2],j[2]]}}}var\nk=a/2|0,l=c(k,b),e=l[2],n=l[1];if(!e)throw g([0,f,mu],1);var\no=e[1],m=c((a-k|0)-1|0,e[2]),p=m[2];return[0,d(n,o,m[1]),p]}return c(gw(a),a)[1]}return[0,,,,c,,,,,,,,,,,,,m,,,,,,,,,,,,,,e,,,,,,,,function(a){return n(0,a)},,,,,,,,,,,function(a,b){var\nc=b;for(;;){if(!c)return;var\nd=c[2],e=c[3],f=c[1];if(h(a,d))return o(d,a,e);c=f}},,,,,,,function(a){if(!a)return m;var\nf=a[2],d=a[1];if(!f)return b(d);var\ng=f[2],e=f[1];if(!g)return c(e,b(d));var\nh=g[2],i=g[1];if(!h)return c(i,c(e,b(d)));var\nj=h[2],l=h[1];if(!j)return c(l,c(i,c(e,b(d))));if(j[2])return p(l2(k[1],a));var\nn=j[1];return c(n,c(l,c(i,c(e,b(d)))))}]}function\nmv(a){var\nb=mp(a);return[0,b[17],,,b[4],,,,,,,,,,b[31],,,,,,,,,b[39],,,,,,,,,,,,,b[50],b[57]]}function\nmw(f){function\nh(a){return a?a[5]:0}function\ne(a,b,c,d){var\ne=h(a),f=h(d),g=f<=e?e+1|0:f+1|0;return[0,a,b,c,d,g]}function\nd(a,b,c,d){var\ni=a?a[5]:0,j=d?d[5]:0;if((j+2|0)=j){var\nB=j<=i?i+1|0:j+1|0;return[0,a,b,c,d,B]}if(!d)return t(mA);var\nl=d[4],o=d[3],p=d[2],g=d[1],w=h(g);if(w<=h(l))return e(e(a,b,c,g),p,o,l);if(!g)return t(mz);var\nx=g[3],y=g[2],z=g[1],A=e(g[4],p,o,l);return e(e(a,b,c,z),y,x,A)}function\nj(a,b,c){if(!c)return[0,0,a,b,0,1];var\ne=c[4],h=c[3],k=c[2],g=c[1],o=c[5],l=i(f[1],a,k);if(0===l)return h===b?c:[0,g,a,b,e,o];if(0<=l){var\nm=j(a,b,e);return e===m?c:d(g,k,h,m)}var\nn=j(a,b,g);return g===n?c:d(n,k,h,e)}function\nn(a){var\nb=a;for(;;){if(!b)throw g(ax,1);var\nc=b[1];if(!c)return[0,b[2],b[3]];b=c}}function\nc(a){if(!a)return t(mB);var\nb=a[1];if(!b)return a[4];var\ne=a[4],f=a[3],g=a[2];return d(c(b),g,f,e)}function\no(a,b){if(!a)return b;if(!b)return a;var\ne=n(b),f=e[2],g=e[1];return d(a,g,f,c(b))}function\nk(a,b){if(!b)return 0;var\nc=b[4],h=b[3],g=b[2],e=b[1],j=i(f[1],a,g);if(0===j)return o(e,c);if(0<=j){var\nl=k(a,c);return c===l?b:d(e,g,h,l)}var\nm=k(a,e);return e===m?b:d(m,g,h,c)}function\nl(a,b){var\nc=b;for(;;){if(!c)return 0;var\nd=c[4],e=c[3],f=c[2];l(a,c[1]);i(a,f,e);c=d}}function\nm(a,b,c){var\nd=b,e=c;for(;;){if(!d)return e;var\nf=d[4],g=d[3],h=d[2],i=x(a,h,g,m(a,d[1],e));d=f;e=i}}return[0,,,,,0,,j,function(a,b){var\nc=b;for(;;){if(!c)throw g(ax,1);var\ne=c[4],h=c[3],j=c[1],d=i(f[1],a,c[2]);if(0===d)return h;var\nk=0<=d?e:j;c=k}},,,,,,,,,function(a,b){var\nc=b;for(;;){if(!c)return 0;var\ne=c[4],g=c[3],h=c[1],d=i(f[1],a,c[2]);if(0===d)return[0,g];var\nj=0<=d?e:h;c=j}},,,,,,,k,,l,,,m]}function\ned(a){var\nb=mw(a);return[0,b[5],,,b[7],,,b[24],,,,,b[26],b[29],,,,,,,,,,,,,,,b[8],b[17]]}var\nee=[q,mC,ae(0)];function\nbC(a){return[0,0,0]}function\nb7(a){a[1]=0;a[2]=0;return}function\na5(a,b){b[1]=[0,a,b[1]];b[2]=b[2]+1|0;return 0}function\nbD(a){var\nb=a[1];if(!b)return 0;var\nc=b[1];a[1]=b[2];a[2]=a[2]-1|0;return[0,c]}function\nbE(a){var\nb=a[1];return b?[0,b[1]]:0}function\nmD(a){var\nb=a[1];if(!b)throw g(ee,1);a[1]=b[2];a[2]=a[2]-1|0;return}function\nmE(a){if(a[1])return;throw g(ee,1)}function\nmF(a,b){return a4(a,b[1])}var\nmH=[q,mG,ae(0)];function\nef(a){return[0,0,0,0]}function\neg(a){a[1]=0;a[2]=0;a[3]=0;return}function\neh(a,b){var\nc=[0,a,0],d=b[3];return d?(b[1]=b[1]+1|0,d[2]=c,b[3]=c,0):(b[1]=1,b[2]=c,b[3]=c,0)}function\ngM(a){var\nb=a[2];if(!b)throw g(mH,1);var\nc=b[1];if(b[2]){var\nd=b[2];a[1]=a[1]-1|0;a[2]=d;return c}eg(a);return c}function\nei(a){return 0===a[1]?1:0}function\nmI(a){var\nb=a[2];return b?[0,b[1]]:0}function\nmJ(a){var\nb=a[2];if(!b)return 0;var\nc=b[1];if(b[2]){var\nd=b[2];a[1]=a[1]-1|0;a[2]=d;return[0,c]}eg(a);return[0,c]}function\nb8(a){var\nb=1<=a?a:1,c=b6=(d+b|0))break;c[1]=2*c[1]|0}if(b6a[3])throw g([0,f,mO],1);if((d+b|0)<=a[3])return;throw g([0,f,mN],1)}function\nb9(a,b){var\nc=n(b),d=a[2]+c|0;if(a[3]=b)return ea(a[1],b,c);return t(mL)}function\nmM(a){return a[2]}function\nmQ(a,b){var\nc=a[2];if(a[3]<=c)ej(a,1);A(a[1],c,b);a[2]=c+1|0;return}function\nmR(a,b,c,d){var\ne=c<0?1:0;if(e)var\nf=e;else\nvar\nh=d<0?1:0,f=h||((n(b)-d|0)e){if(32!==e){if(43>e)break a;switch(e-43|0){case\n5:c:if(c<(d+2|0)&&1=(d+1|0))break a;var\nf=bh(d+1|0,48);a0(f,0,e);aL(b,1,f,(d-c|0)+2|0,c-1|0);return $(f)}if(71<=e){if(5>>0)break a}else if(65>e)break a}if(ca)return b;var\nh=[0,0],i=n(b)-1|0,o=0;if(i>=0){var\nd=o;for(;;){if(9>=_(b,d)+kd>>>0)h[1]++;var\nr=d+1|0;if(i===d)break;d=r}}var\nj=h[1],k=F(n(b)+((j-1|0)/3|0)|0),l=[0,0];function\ne(a){a0(k,l[1],a);l[1]++;return}var\nf=[0,((j-1|0)%3|0)+1|0],m=n(b)-1|0,p=0;if(m>=0){var\nc=p;for(;;){var\ng=_(b,c);if(9>>0)e(g);else{if(0===f[1]){e(95);f[1]=3}f[1]--;e(g)}var\nq=c+1|0;if(m===c)break;c=q}}return $(k)}function\nox(a,b){return cS(a,dT(nE(a),b))}function\noy(a,b){return cS(a,dT(n6(a),b))}function\noz(a,b){return cS(a,dT(oi(a),b))}function\noA(a,b){return cS(a,zJ(nS(a),b))}function\naM(d,b,c){function\na(a){switch(d[1]){case\n0:var\ne=45;break;case\n1:var\ne=43;break;default:var\ne=32}return zE(c,b,e)}function\ne(a){var\nb=zp(c);return 3===b?c<0.?oC:oD:4<=b?oE:a}function\nf(b){var\ne=n(b);return function(a){var\nc=a;for(;;){if(c===e)return 0;var\nd=y(b,c)-46|0;a:{if(23>>0){if(55===d)break a}else if(21>>0)break a;c=c+1|0;continue}return 1}}(0)?b:ay(b,oB)}switch(d[2]){case\n5:return e(f(f9(gR(d,b),c)));case\n6:return a(0);case\n7:return mi(a(0));case\n8:return e(a(0));default:return f9(gR(d,b),c)}}function\noF(a){var\nb=lJ(a),c=n(b),d=bh(c+2|0,39);cy(b,0,d,1,c);return $(d)}function\noG(a){var\nb=gN(16);el(b,a);return gP(b)}function\nco(a,b,c,d){var\nk=b,j=c,e=d;for(;;){if(typeof\ne===\"number\")return h(k,j);switch(e[0]){case\n0:var\nt=e[1];return function(a){return o(k,[5,j,a],t)};case\n1:var\nu=e[1];return function(a){return o(k,[4,j,oF(a)],u)};case\n2:return em(k,j,e[2],e[1],function(a){return a});case\n3:return em(k,j,e[2],e[1],nD);case\n4:return cT(k,j,e[4],e[2],e[3],ox,e[1]);case\n5:return cT(k,j,e[4],e[2],e[3],oy,e[1]);case\n6:return cT(k,j,e[4],e[2],e[3],oz,e[1]);case\n7:return cT(k,j,e[4],e[2],e[3],oA,e[1]);case\n8:return oH(k,j,e[4],e[2],e[3],e[1]);case\n9:return em(k,j,e[2],e[1],lq);case\n10:j=[7,j];e=e[1];break;case\n11:j=[2,j,e[1]];e=e[2];break;case\n12:j=[3,j,e[1]];e=e[2];break;case\n13:var\nv=e[3],x=oG(e[2]);return function(a){return o(k,[4,j,x],v)};case\n14:var\ny=e[3],z=e[2];return function(a){return o(k,j,w(nC(a[1],z),y))};case\n15:var\nA=e[1];return function(c,b){return o(k,[6,j,function(a){return i(c,a,b)}],A)};case\n16:var\nB=e[1];return function(a){return o(k,[6,j,a],B)};case\n17:j=[0,j,e[1]];e=e[2];break;case\n18:var\nl=e[1];if(0===l[0]){let\nb=j,c=k,d=e[2];k=function(a){return o(c,[1,b,[0,a]],d)};j=0;e=l[1][1]}else{let\nb=j,c=k,d=e[2];k=function(a){return o(c,[1,b,[1,a]],d)};j=0;e=l[1][1]}break;case\n19:throw g([0,f,oJ],1);case\n20:var\nC=e[3],D=[8,j,oK];return function(a){return o(k,D,C)};case\n21:var\nE=e[2];return function(a){return o(k,[4,j,dT(j9,a)],E)};case\n22:var\nF=e[1];return function(a){return o(k,[5,j,a],F)};case\n23:var\nm=e[2],n=e[1];return a<50?ja(a+1|0,k,j,n,m):r(ja,[0,k,j,n,m]);default:var\np=e[3],q=e[1],s=h(e[2],0);return a<50?fq(a+1|0,k,j,p,q,s):r(fq,[0,k,j,p,q,s])}}}function\no(a,b,c){return bA(co(0,a,b,c))}function\nja(a,b,c,d,e){if(typeof\nd===\"number\")switch(d){case\n0:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n1:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n2:throw g([0,f,oL],1);default:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e])}switch(d[0]){case\n0:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n1:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n2:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n3:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n4:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n5:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n6:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n7:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n8:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n9:var\nh=d[2];return a<50?fr(a+1|0,b,c,h,e):r(fr,[0,b,c,h,e]);case\n10:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);default:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e])}}function\nfr(a,h,c,d,e){if(typeof\nd===\"number\")return a<50?s(a+1|0,h,c,e):r(s,[0,h,c,e]);switch(d[0]){case\n0:var\nb=d[1];return function(a){return af(h,c,b,e)};case\n1:var\ni=d[1];return function(a){return af(h,c,i,e)};case\n2:var\nj=d[1];return function(a){return af(h,c,j,e)};case\n3:var\nk=d[1];return function(a){return af(h,c,k,e)};case\n4:var\nl=d[1];return function(a){return af(h,c,l,e)};case\n5:var\nm=d[1];return function(a){return af(h,c,m,e)};case\n6:var\nn=d[1];return function(a){return af(h,c,n,e)};case\n7:var\no=d[1];return function(a){return af(h,c,o,e)};case\n8:var\np=d[2];return function(a){return af(h,c,p,e)};case\n9:var\nq=d[3],t=d[2],u=I(D(d[1]),t);return function(a){return af(h,c,W(u,q),e)};case\n10:var\nv=d[1];return function(a,b){return af(h,c,v,e)};case\n11:var\nw=d[1];return function(a){return af(h,c,w,e)};case\n12:var\nx=d[1];return function(a){return af(h,c,x,e)};case\n13:throw g([0,f,oM],1);default:throw g([0,f,oN],1)}}function\naf(a,b,c,d){return bA(fr(0,a,b,c,d))}function\ns(a,b,c,d){var\ne=[8,c,oO];return a<50?co(a+1|0,b,e,d):r(co,[0,b,e,d])}function\nem(g,f,c,d,e){if(typeof\nd===\"number\")return function(a){return o(g,[4,f,h(e,a)],c)};if(0===d[0]){var\nb=d[2],i=d[1];return function(a){return o(g,[4,f,ab(i,b,h(e,a))],c)}}var\nj=d[1];return function(a,b){return o(g,[4,f,ab(j,a,h(e,b))],c)}}function\ncT(k,j,h,d,e,f,g){if(typeof\nd===\"number\"){if(typeof\ne===\"number\")return e?function(a,b){return o(k,[4,j,bG(a,i(f,g,b))],h)}:function(a){return o(k,[4,j,i(f,g,a)],h)};var\nb=e[1];return function(a){return o(k,[4,j,bG(b,i(f,g,a))],h)}}if(0===d[0]){var\nc=d[2],l=d[1];if(typeof\ne===\"number\")return e?function(a,b){return o(k,[4,j,ab(l,c,bG(a,i(f,g,b)))],h)}:function(a){return o(k,[4,j,ab(l,c,i(f,g,a))],h)};var\nn=e[1];return function(a){return o(k,[4,j,ab(l,c,bG(n,i(f,g,a)))],h)}}var\nm=d[1];if(typeof\ne===\"number\")return e?function(a,b,c){return o(k,[4,j,ab(m,a,bG(b,i(f,g,c)))],h)}:function(a,b){return o(k,[4,j,ab(m,a,i(f,g,b))],h)};var\np=e[1];return function(a,b){return o(k,[4,j,ab(m,a,bG(p,i(f,g,b)))],h)}}function\noH(i,h,g,d,e,f){if(typeof\nd===\"number\"){if(typeof\ne===\"number\")return e?function(a,b){return o(i,[4,h,aM(f,a,b)],g)}:function(a){return o(i,[4,h,aM(f,ek(f),a)],g)};var\nb=e[1];return function(a){return o(i,[4,h,aM(f,b,a)],g)}}if(0===d[0]){var\nc=d[2],j=d[1];if(typeof\ne===\"number\")return e?function(a,b){return o(i,[4,h,ab(j,c,aM(f,a,b))],g)}:function(a){return o(i,[4,h,ab(j,c,aM(f,ek(f),a))],g)};var\nl=e[1];return function(a){return o(i,[4,h,ab(j,c,aM(f,l,a))],g)}}var\nk=d[1];if(typeof\ne===\"number\")return e?function(a,b,c){return o(i,[4,h,ab(k,a,aM(f,b,c))],g)}:function(a,b){return o(i,[4,h,ab(k,a,aM(f,ek(f),b))],g)};var\nm=e[1];return function(a,b){return o(i,[4,h,ab(k,a,aM(f,m,b))],g)}}function\nfq(a,b,c,d,e,f){if(e){var\ni=e[1];return function(a){return oI(b,c,d,i,h(f,a))}}var\ng=[4,c,f];return a<50?co(a+1|0,b,g,d):r(co,[0,b,g,d])}function\noI(a,b,c,d,e){return bA(fq(0,a,b,c,d,e))}function\naN(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;switch(c[0]){case\n0:var\nf=c[1],g=gQ(c[2]);aN(a,f);return b5(a,g);case\n1:var\nd=c[2],e=c[1];if(0===d[0]){var\ni=d[1];aN(a,e);b5(a,oP);c=i}else{var\nj=d[1];aN(a,e);b5(a,oQ);c=j}break;case\n6:var\nm=c[2];aN(a,c[1]);return h(m,a);case\n7:aN(a,c[1]);return cJ(a);case\n8:var\nn=c[2];aN(a,c[1]);return t(n);case\n2:case\n4:var\nk=c[2];aN(a,c[1]);return b5(a,k);default:var\nl=c[2];aN(a,c[1]);return lA(a,l)}}}function\naO(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;switch(c[0]){case\n0:var\nf=c[1],g=gQ(c[2]);aO(a,f);return b9(a,g);case\n1:var\nd=c[2],e=c[1];if(0===d[0]){var\ni=d[1];aO(a,e);b9(a,oR);c=i}else{var\nj=d[1];aO(a,e);b9(a,oS);c=j}break;case\n6:var\nm=c[2];aO(a,c[1]);return b9(a,h(m,0));case\n7:c=c[1];break;case\n8:var\nn=c[2];aO(a,c[1]);return t(n);case\n2:case\n4:var\nk=c[2];aO(a,c[1]);return b9(a,k);default:var\nl=c[2];aO(a,c[1]);return mQ(a,l)}}}function\noT(a){var\nc=a[1],b=b8(cv);return o(function(a){aO(b,a);return aK(cQ(b))},0,c)}function\noU(c){if(c==e)return oV;var\nf=n(c);function\nj(a){return h(oT(oW),c)}function\nk(a){var\nb=a;for(;;){if(b===f)return b;var\nd=y(c,b);if(9!==d&&32!==d)return b;b=b+1|0}}var\ni=k(0),o=function(a,b){var\nd=b;for(;;){if(d===f)return d;if(25>>0)return d;d=d+1|0}}(i,i),a=eb(c,i,o-i|0),d=k(o),l=function(a,b){var\nd=b;for(;;){if(d===f)return d;var\ne=y(c,d);a:{if(48<=e){if(58>e)break a}else if(45===e)break a;return d}d=d+1|0}}(d,d);if(d===l)var\nm=0;else\ntry{var\nr=k8(eb(c,d,l-d|0)),m=r}catch(f){var\np=L(f);if(p[1]!==b3)throw g(p,0);var\nq=j(0),m=q}if(k(l)!==f)j(0);a:{if(a!==e&&a!==jq){if(a===\"h\"){var\nb=0;break a}if(a===\"hov\"){var\nb=3;break a}if(a===\"hv\"){var\nb=2;break a}if(a!==\"v\"){var\nb=j(0);break a}var\nb=1;break a}var\nb=4}return[0,m,b]}function\noX(d,b,c){return o(function(a){aN(b,a);return h(d,b)},0,c[1])}function\ncU(a,b){return oX(function(a){return 0},a,b)}function\nen(a){return cU(at,a)}function\neo(c,b){return o(function(a){var\nb=b8(64);aO(b,a);return h(c,cQ(b))},0,b[1])}function\nB(a){return eo(function(a){return a},a)}var\nep=d4(0);function\ner(a,b){var\nc=a[1+b];return lB(c)?aw(c)===dC?h(B(oY),c):aw(c)===kl?lv(c):oZ:h(B(o0),c)}function\ngS(a,b){if(a.length-1<=b)return o1;var\nc=gS(a,b+1|0),d=er(a,b);return i(B(o2),d,c)}function\no3(a){var\nb=a.length-1;if(2>=b>>>0)switch(b){case\n0:return o5;case\n1:return o6;default:var\ne=er(a,1);return h(B(o7),e)}var\nc=gS(a,2),d=er(a,1);return i(B(o4),d,c)}function\no8(d){return function(a){var\nb=a;for(;;){if(!b)return 0;var\ne=b[2],f=b[1];a:{try{var\nc=h(f,d)}catch(f){break a}if(c)return[0,c[1]]}b=e}}(cG(ep))}function\no9(a){if(a===d6)return o_;if(a===gq)return o$;if(a[1]===gp){var\nb=a[2],e=b[3],i=b[2],j=b[1];return fu(B(eq),j,i,e,e+5|0,pa)}if(a[1]===f){var\nc=a[2],g=c[3],k=c[2],l=c[1];return fu(B(eq),l,k,g,g+6|0,pb)}if(a[1]===b4){var\nd=a[2],h=d[3],m=d[2],n=d[1];return fu(B(eq),n,m,h,h+6|0,pc)}if(0!==aw(a))return a[1];var\no=a[1][1];return ay(o,o3(a))}function\ncV(a){var\nb=o8(a);return b?b[1]:o9(a)}function\npd(a){var\nb=[0,zq(a)];return b}function\npe(c,b){function\na(a){return a?0===c?pf:pg:0===c?ph:pi}if(0===b[0]){var\nd=b[5],e=b[4],f=b[3],g=b[6]?pj:pl,i=b[2],j=b[7],k=a(b[1]);return[0,zd(B(pk),k,j,i,g,f,e,d)]}if(b[1])return 0;var\nl=a(0);return[0,h(B(pm),l)]}function\npn(a,b){if(!b)return cU(a,pp);var\nd=b[1],e=d.length-2|0,g=0;if(e>=0){var\nc=g;for(;;){var\nf=pe(c,j(d,c)[1+c]);if(f){var\ni=f[1];h(cU(a,po),i)}var\nk=c+1|0;if(e===c)break;c=k}}return 0}function\ncW(a,b){return pn(a,pd(b))}var\nps=pr.slice();function\npt(a,b){var\ne=cV(a);h(en(pu),e);cW(at,b);var\nc=z1(0);if(c<0){var\nd=cI(c);gu(j(ps,d)[1+d])}return cJ(at)}var\npv=[0];function\ngT(a){var\nb=k2(0);return b}function\npw(a,b){try{var\nd=b?pv:gT(0);try{d8(0)}catch(f){}try{var\nf=pt(a,d),e=f}catch(f){var\ni=L(f),j=gT(0),k=cV(a);h(en(py),k);cW(at,d);var\nl=cV(i);h(en(pz),l);cW(at,j);var\ne=cJ(at)}return e}catch(f){var\nc=L(f);if(c===d6)return gu(px);throw g(c,0)}}gl(kv,function(a,b){try{var\nc=pw(a,b);return c}catch(f){return 0}});function\npq(a){for(;;){var\nb=cG(ep),c=1-d5(ep,b,[0,a,b]);if(!c)return c}}function\npA(a){return k2(a)}var\npC=[q,pB,ae(0)];pq(function(a){return a[1]===pC?[0,ay(pD,cV(a[2]))]:0});function\npE(a){return zZ(a,0,n(a))}function\npF(a){return[0,ap(55,0),0]}function\npG(a,b){function\nl(a,b){return pE(ay(a,gA(b)))}function\nm(a){var\nb=y(a,3)<<24,c=y(a,2)<<16,d=y(a,1)<<8;return((y(a,0)+d|0)+c|0)+b|0}var\ng=0===b.length-1?[0,0]:b,h=g.length-1,c=0;for(;;){j(a[1],c)[1+c]=c;var\ns=c+1|0;if(54===c)break;c=s}var\nf=[0,pH],i=54+gz(55,h)|0,n=0;if(i>=0){var\nd=n;for(;;){var\ne=d%55|0,k=z6(d,h),o=j(g,k)[1+k];f[1]=l(f[1],o);var\np=m(f[1]),q=(j(a[1],e)[1+e]^p)&jV;j(a[1],e)[1+e]=q;var\nr=d+1|0;if(i===d)break;d=r}}a[2]=0;return}function\npI(a){var\nb=pF(0);pG(b,a);return b}function\ngU(a){return pI(Ah(0))}function\ncX(a){a[2]=(a[2]+1|0)%55|0;var\nb=a[2],c=j(a[1],b)[1+b],d=(a[2]+24|0)%55|0,e=(j(a[1],d)[1+d]+(c^(c>>>25|0)&31)|0)&jV,f=a[2];j(a[1],f)[1+f]=e;return e}function\ngV(a){var\nb=gf(dW(cX(a)),9),c=gf(dW(cX(a)),9);return k5(b,k5(k6(c,21),k6(gf(dW(cX(a)),8),42)))}function\npJ(a){var\nb=a.length-1<4?1:0,c=b||(a[4]<0?1:0);return c}try{var\nzb=li(km),gZ=zb}catch(f){var\ngW=L(f);if(gW!==ax)throw g(gW,0);try{var\nza=li(\"CAMLRUNPARAM\"),gY=za}catch(f){var\ngX=L(f);if(gX!==ax)throw g(gX,0);var\ngY=pK}var\ngZ=gY}var\ncY=[ba,function(a){return gU(0)}],pL=mh(gZ,82);function\npM(a,b){var\nc=a;for(;;){if(b<=c)return c;if(d9<(c*2|0))return c;c=c*2|0}}function\nes(a,b){var\nf=a?a[1]:pL,c=pM(16,b);if(f)var\nd=aw(cY),g=aD===d?cY[1]:ba===d?cK(cY):cY,e=cX(g);else\nvar\ne=0;return[0,0,ap(c,0),e,c]}function\npN(m,b,c,d){var\ng=d.length-1,f=ap(g,0),i=c.length-2|0;function\nn(a){var\nc=a;for(;;){if(!c)return;var\ni=c[1],l=c[2],n=c[3],g=b?c:[0,i,l,0],e=h(m,i),k=j(f,e)[1+e];if(k)k[3]=g;else\nj(d,e)[1+e]=g;j(f,e)[1+e]=g;c=n}}var\no=0;if(i>=0){var\ne=o;for(;;){n(j(c,e)[1+e]);var\nr=e+1|0;if(i===e)break;e=r}}if(b){var\nk=g-1|0,p=0;if(k>=0){var\na=p;for(;;){var\nl=j(f,a)[1+a];if(l)l[3]=0;var\nq=a+1|0;if(k===a)break;a=q}}}return}function\ng0(a,b){var\nc=b[2],d=(c.length-1)*2|0,e=d>>0)return;return g7(a,d)}function\npZ(a){var\nb=mJ(a[28]);if(!b)return;var\nc=b[1],d=c[1];a[12]=a[12]-c[3]|0;var\ne=al(d);a[9]=a[9]+e|0;return}function\np0(a,b,c){if(typeof\nc===\"number\")switch(c){case\n0:var\nj=bE(a[3]);if(!j)return;var\nk=j[1][1],l=function(a,b){if(!b)return[0,a,0];var\nc=b[1],d=b[2];return zV(a,c)?[0,a,b]:[0,c,l(a,d)]};k[1]=l(a[6]-a[9]|0,k[1]);return;case\n1:bD(a[2]);return;case\n2:bD(a[3]);return;case\n3:var\nm=bE(a[2]);return m?g7(a,m[1][2]):c0(a);case\n4:var\no=a[10]!==(a[6]-a[9]|0)?1:0;return o?pZ(a):o;default:var\np=bD(a[5]);if(p)return et(a,h(a[25],p[1]));return}switch(c[0]){case\n0:return g6(a,b,c[1]);case\n1:var\nd=c[2],f=c[1],q=d[1],z=d[2],r=bE(a[2]);if(!r)return;var\ns=r[1],e=s[2];switch(s[1]){case\n0:return bI(a,f);case\n1:return bi(a,d,e);case\n2:return bi(a,d,e);case\n3:return a[9]<(b+n(q)|0)?bi(a,d,e):bI(a,f);case\n4:return a[11]?bI(a,f):a[9]<(b+n(q)|0)?bi(a,d,e):((a[6]-e|0)+z|0)=a[14]){a[13]=g5;g8(a);if(b)c0(a);return qb(a)}hb(a,0)}}function\new(a,b,c){var\nd=a[14]=c)return x(a[17],hf,0,c);x(a[17],hf,0,80);c=c-80|0}}function\nqo(a){return a[1]===b$?ay(qq,ay(a[2],qp)):qr}function\nqs(a){return a[1]===b$?ay(qu,ay(a[2],qt)):qv}function\nqw(a){return 0}function\nqx(a){return 0}function\nqy(a,b,c,d,e){var\ng=ef(0),h=[0,g3,qz,0];eh(h,g);var\nf=bC(0);eu(f);a5([0,1,h],f);var\ni=78,j=bC(0),k=bC(0),l=bC(0);return[0,f,bC(0),l,k,j,i,10,68,i,0,1,1,1,1,gs,qA,a,b,c,d,e,0,0,qo,qs,qw,qx,g]}function\nhh(a,b){var\nc=qy(a,b,function(a){return 0},function(a){return 0},function(a){return 0});c[19]=function(a){return qm(c,a)};c[20]=function(a){return hg(c,a)};c[21]=function(a){return hg(c,a)};return c}function\nhi(d){return hh(function(a,b,c){return lx(d,a,b,c)},function(a){return cJ(d)})}function\nex(d){return hh(function(a,b,c){return mR(d,a,b,c)},function(a){return 0})}var\nqB=dF,qC=function(a){return b8(qB)}(0),qD=hi(lw),qE=hi(at);ex(qC);function\np8(a,b){if(a[22]){a5(b,a[4]);h(a[26],b)}var\nc=a[23];return c?ca(a,[0,cZ,[5,b],0]):c}function\nqd(a,b){return he(a,n(b),b)}function\nqe(a,b){hd(a,1);return h(a[18],0)}function\nqf(a,b){var\nc=a[14]=0){var\nc=g;for(;;){qJ(e,c,a,j(b,c)[1+c]);var\nh=c+1|0;if(f===c)break;c=h}}return e}function\nhl(a,b){if(typeof\nb!==\"number\"&&0===b[0])return hk(a,b[1]);return aK(qK)}function\nqL(a,b,c,d){if(typeof\nc!==\"number\"){if(0===c[0])return hm(c[1],a[1+b],d);return}if(2!==c){a[1+b]=d;return}if(0===aw(d)&&4===d.length-1){var\ne=0,h=a[1+b];for(;;){h[1+e]=d[1+e];var\ni=e+1|0;if(3===e)return;e=i}}throw g([0,f,qM],1)}function\nhm(a,b,c){if(0===aw(c)&&a.length-1<=c.length-1){var\ne=a.length-2|0,h=0;if(e>=0){var\nd=h;for(;;){var\ni=c[1+d];qL(b,d,j(a,d)[1+d],i);var\nk=d+1|0;if(e===d)break;d=k}}return}throw g([0,f,qN],1)}function\nhn(a,b,c){if(typeof\na!==\"number\"&&0===a[0])return hm(a[1],b,c);return aK(qO)}var\ney=[q,qP,ae(0)];qH(qQ,[0,ey,[0]]);(function(a){throw a});function\nez(a){return[0,a]}function\nQ(a){return[0,a]}function\nc2(a){return 0===a[0]?[0,a[1]]:0}var\nbK=[0,function(a){return a}(0)];function\nbL(a){return[1,0,0,0,a]}function\nl(a,b){return 0===a[0]?[0,h(b,a[1])]:bL([0,a,b])}function\ncc(a,b,c){if(0===a[0]){var\nd=a[1];if(0===b[0])return[0,i(c,d,b[1])]}return bL([1,a,b,c])}function\nho(a){return 0===a[0]?a[1]:bL([4,a,0])}function\nhp(a,b,c){switch(c[0]){case\n0:throw g([0,f,qT],1);case\n1:c[3]=[0,b,a,c[3]];return;default:c[2]=[0,b,a,c[2]];return}}function\neA(a,b){if(!b)throw g([0,f,qU],1);if(b[2]===a)return[0,b[1],b[3]];var\nc=eA(a,b[3]),d=c[1];b[3]=c[2];return[0,d,b]}function\ncd(a,b){switch(b[0]){case\n0:throw g([0,f,qV],1);case\n1:var\nc=eA(a,b[3]),e=c[1];b[3]=c[2];return e;default:var\nd=eA(a,b[2]),h=d[1];b[2]=d[2];return h}}function\nhq(a,b,c,d){var\ne=d;for(;;){if(!e)throw g([0,f,qW],1);if(e[1]===b&&e[2]===a){e[1]=c;return}e=e[3]}}function\neB(a,b,c,d){switch(d[0]){case\n0:throw g([0,f,qX],1);case\n1:return hq(a,b,c,d[3]);default:return hq(a,b,c,d[2])}}function\nhr(a,b){var\nc=b;for(;;){if(!c)throw g([0,f,qY],1);if(c[2]===a)return c[1];c=c[3]}}function\nqZ(a,b){switch(b[0]){case\n0:throw g([0,f,q0],1);case\n1:return hr(a,b[3]);default:return hr(a,b[2])}}function\naU(a,b,c,d){switch(d[0]){case\n0:throw g([0,f,q1],1);case\n1:var\nj=d[1];if(typeof\nj===\"number\"&&!j){if(!c)return;if(b[1])return;b[1]=1;return}var\nk=d[4];if(7===k[0]){var\nn=k[2];if(1===n[0]){var\no=n[1];if(typeof\no===\"number\"){if(!o&&c){if(b[1])return;b[1]=1;return}}else if(c)return}}var\nl=d[1];a:{if(typeof\nl===\"number\"&&l){var\ne=1;break a}var\ne=c}d[1]=0;var\nm=d[2];return a<50?jb(a+1|0,b,e,m):r(jb,[0,b,e,m]);default:var\ni=d[1];d[1]=0;if(typeof\ni===\"number\"){if(!i)return;b[1]=2;return}var\np=i[1];if(c)b[1]=2;return h(d[3],p)}}function\na6(a,b,c){return bA(aU(0,a,b,c))}function\njb(a,b,c,d){if(typeof\nd===\"number\")return;switch(d[0]){case\n0:var\nf=d[1];return a<50?aU(a+1|0,b,c,f):r(aU,[0,b,c,f]);case\n1:var\ng=d[2];a6(b,c,d[1]);return a<50?aU(a+1|0,b,c,g):r(aU,[0,b,c,g]);case\n2:var\nh=d[3],l=d[2];a6(b,c,d[1]);a6(b,c,l);return a<50?aU(a+1|0,b,c,h):r(aU,[0,b,c,h]);case\n3:var\ni=d[4],m=d[3],n=d[2];a6(b,c,d[1]);a6(b,c,n);a6(b,c,m);return a<50?aU(a+1|0,b,c,i):r(aU,[0,b,c,i]);default:var\no=d[1];d[1]=0;var\nk=o-1|0,p=0;if(k>=0){var\ne=p;for(;;){a6(b,c,j(d[3],e)[1+e]);var\nq=e+1|0;if(k===e)break;e=q}}return}}function\nq2(a){return i(cU(at,q3),cW,zx(20))}function\nc3(a,b){var\nc=[0,0];a6(c,a,b);var\nd=2<=c[1]?1:0;return d?q2(0):d}function\nam(a){return bL([5,a])}function\naP(a){return a}function\nac(a,b){if(1===a[0]){var\nc=a[4];if(5===c[0]){c[1]=b;return c3(0,a)}}throw g([0,f,q4],1)}function\nbM(a){if(1===a[0]){var\nb=a[4];if(5===b[0])return b[1]}throw g([0,f,q5],1)}function\nbN(a,b,c){var\nk=a,h=b,d=c;for(;;)switch(d[0]){case\n0:return k;case\n1:var\ne=d[2];if(typeof\ne===\"number\")throw g([0,f,q_],1);switch(e[0]){case\n0:if(e[1]!==h)throw g([0,f,q$],1);var\no=0;break;case\n1:var\nB=e[2],C=e[1];if(C===h)var\nD=[0,B];else{if(B!==h)throw g([0,f,ra],1);var\nD=[0,C]}var\no=D;break;case\n2:var\nu=e[3],v=e[2],w=e[1];if(w===h)var\nx=[1,v,u];else if(v===h)var\nx=[1,w,u];else{if(u!==h)throw g([0,f,rb],1);var\nx=[1,w,v]}var\no=x;break;case\n3:var\np=e[4],q=e[3],r=e[2],s=e[1];if(s===h)var\nt=[2,r,q,p];else if(r===h)var\nt=[2,s,q,p];else if(q===h)var\nt=[2,s,r,p];else{if(p!==h)throw g([0,f,rc],1);var\nt=[2,s,r,q]}var\no=t;break;default:var\nn=cd(d,h);if(j(e[3],n)[1+n]!==h)throw g([0,f,rd],1);var\nm=e[2]-1|0;e[2]=m;if(n>>2|0))var\nU=ml(e[3],0,K>>>1|0),M=[4,e[1],e[2],U];else\nvar\nM=e;var\nJ=M}var\no=J}d[2]=o;if(typeof\no!==\"number\")return k;var\ny=d[1];d[1]=1;var\nl=d[4];switch(l[0]){case\n0:h=d;d=l[1];break;case\n1:var\nN=l[2];k=bN(k,d,l[1]);h=d;d=N;break;case\n2:var\nO=l[2];k=bN(k,d,l[1]);h=d;d=O;break;case\n3:var\nP=l[2];k=bN(k,d,l[1]);h=d;d=P;break;case\n4:var\nz=l[2],A=bN(k,d,l[1]);if(!z)return A;var\nQ=z[1];l[2]=0;k=A;h=d;d=Q;break;case\n5:return k;case\n6:if(typeof\ny===\"number\")return k;var\nR=y[1];try{i(l[2],d,R);return k}catch(f){var\nS=L(f);return[0,[0,S,pA(0)],k]}default:var\nT=l[1];k=bN(k,d,l[2]);h=d;d=T}break;default:throw g([0,f,re],1)}}function\na7(a,b){var\ne=a,c=b;for(;;)switch(c[0]){case\n0:return;case\n1:var\nn=typeof\nc[2]===\"number\"?1:0,d=c[2];if(typeof\nd===\"number\")var\nk=[0,e];else\nswitch(d[0]){case\n0:var\nk=[1,e,d[1]];break;case\n1:var\nk=[2,e,d[1],d[2]];break;case\n2:var\nk=[3,e,d[1],d[2],d[3]];break;case\n3:var\no=[0,d[1],d[2],d[3],d[4],e,bK,bK,bK],l=0;for(;;){hp(c,l,j(o,l)[1+l]);var\nw=l+1|0;if(4===l)break;l=w}var\nk=[4,5,5,o];break;default:var\ni=d[2];if(i>>1|0)}function\nhz(a,b,c){if(typeof\na!==\"number\"){if(0!==a[0]){if(a[2]!==b)throw g([0,f,rN],1);a[2]=c;return}if(a[2]===b){a[2]=c;return}if(a[4]===b){a[4]=c;return}}throw g([0,f,rM],1)}function\nft(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[4];if(typeof\nd!==\"number\"&&1!==d[0]){var\nh=c[5],e=d[2];if(typeof\ne===\"number\")var\ni=0;else{if(0!==e[0])throw g([0,f,rR],1);e[5]=c;var\ni=e}d[2]=c;c[4]=i;c[5]=d;d[5]=h;hz(h,c,d);eI(b,c);return a<50?cp(a+1|0,b,d):r(cp,[0,b,d])}}throw g([0,f,rQ],1)}function\nrO(a,b){return bA(ft(0,a,b))}function\nfs(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[2];if(typeof\nd!==\"number\"&&1!==d[0]){var\nh=c[5],e=d[4];if(typeof\ne===\"number\")var\ni=0;else{if(0!==e[0])throw g([0,f,rT],1);e[5]=c;var\ni=e}d[4]=c;c[2]=i;c[5]=d;d[5]=h;hz(h,c,d);eI(b,c);return a<50?cp(a+1|0,b,d):r(cp,[0,b,d])}}throw g([0,f,rS],1)}function\nrP(a,b){return bA(fs(0,a,b))}function\njd(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[4];a:if(typeof\nd!==\"number\"&&0===d[0]){var\ne=bP(d[2]);if(eH(bP(d[4]),e)){rP(b,d);break a}}return a<50?ft(a+1|0,b,c):r(ft,[0,b,c])}throw g([0,f,rU],1)}function\njc(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[2];a:if(typeof\nd!==\"number\"&&0===d[0]){var\ne=bP(d[4]);if(eH(bP(d[2]),e)){rO(b,d);break a}}return a<50?fs(a+1|0,b,c):r(fs,[0,b,c])}throw g([0,f,rV],1)}function\ncp(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=bP(c[2]),e=bP(c[4]);return d>>2|0}function\naz(a,b){if(typeof\na===\"number\")var\nc=b;else{if(typeof\nb!==\"number\"){var\nd=c8(b);return[1,(hE(c8(a),d)+1|0)<<2,a,b]}var\nc=a}return c}function\nhF(a){return typeof\na===\"number\"?0:0===a[0]?[0,a[2]]:[1,a[2],a[3]]}var\neJ=1,eK=2,sq=3;function\nhG(a){return-1===a?1:0}function\neL(a){return-1!==a?1:0}function\nbQ(a){return(a&3)===3?1:0}function\nhH(a){return(a&3)===1?1:0}function\nhI(a){return(a&3)===2?1:0}function\nhJ(a){return a|3}function\nsr(a){return a>>>2|0}function\nhK(a){return a<<2|2}function\nch(a){return a&lp(sq)}function\nhL(a){return a[2]}function\nhM(a){return a[3]}function\nhN(a){return[0,0,0,0]}function\nc9(a){a[1]=a[1]+1|0;return}function\nc_(a){a[2]=a[2]+1|0;return}function\nc$(a){a[3]=a[3]+1|0;return}function\neM(a,b,c){var\nd=c;for(;;){if(typeof\nd===\"number\")return;if(0===d[0]){var\ne=d[1],i=(e&3)!==3?1:0,l=i?0!==(e&3)?1:0:i;if(l){if(0!==(e&b))throw g([0,f,st],1);c9(a);c$(a);d[1]=e|3}return}var\nh=d[1],j=(h&3)!==3?1:0,k=j?0!==(h&3)?1:0:j;if(!k)return k;if(0!==(h&b))throw g([0,f,su],1);c9(a);c$(a);d[1]=h|3;eM(a,b,d[2]);d=d[3]}}function\nda(a,b,c,d){if(typeof\nd===\"number\")return;if(0===d[0]){var\ne=d[1];if(0===(e&c)){c9(a);if(0===(e&3))d[1]=e|c;else{d[1]=-1;c$(a);c_(a)}}var\ng=-1!==e?1:0,h=g?(e&3)===3?1:0:g;return h?(d[1]=-1,c_(a)):h}var\nf=d[1];if(0===(f&c)){c9(a);if(0===(f&3)){d[1]=f|c;eh(d,b)}else{d[1]=-1;c$(a);c_(a);eM(a,c,d[2]);eM(a,c,d[3])}}var\ni=-1!==f?1:0,j=i?(f&3)===3?1:0:i;return j?(d[1]=-1,c_(a)):j}function\neN(a,b,c){var\nd=gM(b);if(typeof\nd!==\"number\"&&1===d[0]){var\ne=(d[1]&3)===c?1:0;return e?(da(a,b,c,d[2]),da(a,b,c,d[3])):e}throw g([0,f,sv],1)}function\nhO(a,b,c){for(;;){if(ei(b))return;eN(a,b,c)}}function\nsw(a,b,c,d){for(;;){if(ei(c))return hO(b,d,eK);if(ei(d))return hO(a,c,eJ);eN(a,c,eJ);eN(b,d,eK)}}function\neO(a){var\nb=a[6];a[6]=b+1|0;return b}function\neP(a){var\nb=a;for(;;){if(typeof\nb===\"number\")return;if(0===b[0]){var\nc=b[1];if(typeof\nc!==\"number\"&&0===c[0]){var\ne=c[1],i=eL(e),l=i?bQ(e):i;if(l)c[1]=ch(e);return}throw g([0,f,sB],1)}var\nd=b[1];if(typeof\nd!==\"number\"&&1===d[0]){var\nh=d[1],m=b[4],n=b[3],j=eL(h),k=j?bQ(h):j;if(!k)return k;d[1]=ch(h);eP(n);b=m;continue}throw g([0,f,sC],1)}}function\nhP(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;if(0===c[0]){var\nd=c[1];if(typeof\nd!==\"number\"&&0===d[0]){var\ne=d[1],u=c[2];if(!hH(e)){if(hG(e)){var\nk=eO(a);j(a[4],k)[1+k]=d;j(a[5],k)[1+k]=[0,c,0];d[1]=hK(k);return}if(hI(e)){var\nn=sr(e),v=[0,c,j(a[5],n)[1+n]];j(a[5],n)[1+n]=v;return}var\nq=bQ(e);if(q)throw g([0,f,sF],1);return q}var\nm=a[2];if(-1a[3])throw g([0,f,sE],1)}d[1]=ch(e);return}throw g([0,f,sD],1)}var\nh=c[1];if(typeof\nh!==\"number\"&&1===h[0]){var\nr=c[4],s=c[3],i=h[1],w=c[2];if(hG(i)){var\nl=eO(a);j(a[4],l)[1+l]=h;j(a[5],l)[1+l]=[0,c,0];h[1]=hK(l);eP(s);return eP(r)}if(!hH(i)){if(hI(i)){var\no=i>>>2|0,x=[0,c,j(a[5],o)[1+o]];j(a[5],o)[1+o]=x;return}var\nt=bQ(i);if(t)throw g([0,f,sI],1);return t}if(-1a[3])throw g([0,f,sH],1)}h[1]=ch(i);hP(a,s);c=r;continue}throw g([0,f,sG],1)}}function\nci(a,b){if(typeof\nb===\"number\")return 0;if(0!==b[0]){var\ni=b[1];if(-1===i){var\nl=eO(a);b[1]=0;j(a[4],l)[1+l]=b;var\np=ci(a,b[2]);return[1,b,0,p,ci(a,b[3])]}if(!bQ(i)){b[1]=ch(b[1]);var\nr=ci(a,b[2]);return[1,b,0,r,ci(a,b[3])]}var\nd=i>>>2|0,k=j(a[5],d)[1+d];if(!k)throw g([0,f,sL],1);var\nm=k[2],q=k[1];j(a[5],d)[1+d]=m;if(0===m)b[1]=0;return q}var\ne=b[1];if(eL(e)&&bQ(e)){var\nc=e>>>2|0,h=j(a[5],c)[1+c];if(!h)return[0,b,0];var\nn=h[2],o=h[1];j(a[5],c)[1+c]=n;return o}b[1]=0;return[0,b,0]}var\neQ=[0,0,[0],0,0];function\nss(a){return a[1]}function\nsx(a){return a[1]}function\nsy(a){return a[2]}function\nsz(a,b){var\nc=hN(0),d=hN(0),e=ef(0),f=ef(0);da(c,e,eJ,a);da(d,f,eK,b);sw(c,d,e,f);return[0,c,d]}function\nsA(a){if(typeof\na===\"number\")return;if(0===a[0]){a[1]=0;return}var\nb=c8(a[3]);a[1]=(hE(c8(a[2]),b)+1|0)<<2;return}function\nsJ(a){var\ne=a[6]-1|0,h=0;if(e>=0){var\nb=h;for(;;){var\nc=j(a[4],b)[1+b];if(typeof\nc!==\"number\")if(0===c[0])c[1]=hJ(c[1]);else\nc[1]=hJ(c[1]);var\nd=j(a[5],b)[1+b];if(!d)throw g([0,f,sK],1);if(d[2]){var\ni=a3(d);j(a[5],b)[1+b]=i}var\nk=b+1|0;if(e===b)break;b=k}}return}function\nhQ(a,b,c){if(typeof\nb===\"number\"){if(typeof\nc===\"number\")return[0,eQ,0]}else if(b[1]===c)return[0,eQ,b];var\nt=typeof\nb===\"number\"?cg:b[1],m=sz(t,c),i=sx(m),n=sy(m),u=hM(n),v=hM(i)+u|0,o=ss(i)-v|0,w=hL(n),p=hL(i)+w|0,x=0,y=ap(p,0),z=ap(p,0),A=a?o:-1,B=a?0:-1,C=a?ap(o,0):[0],d=[0,C,B,A,z,y,x];hP(d,b);if(d[2]!==d[3])throw g([0,f,sM],1);sJ(d);var\nq=ci(d,c),r=d[6]-1|0;if(r>=0){var\nh=r;for(;;){sA(j(d[4],h)[1+h]);var\nF=h-1|0;if(0===h)break;h=F}}if(!a)return[0,eQ,q];var\nk=[0,0],l=[0,0],s=d[6]-1|0,D=0;if(s>=0){var\ne=D;for(;;){a4(function(a){if(typeof\na!==\"number\")if(0===a[0]){var\nb=a[2];if(b){k[1]=[0,b[1],k[1]];return 0}}else{var\nc=a[2];if(c){l[1]=[0,c[1],l[1]];return 0}}return 0},j(d[5],e)[1+e]);var\nE=e+1|0;if(s===e)break;e=E}}return[0,[0,d[2],d[1],k[1],l[1]],q]}function\nsN(d,b){if(typeof\nb===\"number\")return 0;function\nc(a){a:if(typeof\na!==\"number\"){b:{if(0===a[0]){var\nb=a[1];if(typeof\nb!==\"number\"&&0===b[0]){var\ne=a[2];if(e){var\nj=e[1];break b}var\nk=h(d[1],b[2]);a[2]=[0,k];return k}break a}var\nl=a[2];if(!l){var\nn=c(a[3]),o=c(a[4]),m=i(d[2],n,o);a[2]=[0,m];return m}var\nj=l[1]}return j}throw g([0,f,sO],1)}return[0,c(b)]}function\ndb(a,b){return[0,[0,a,b],0]}function\ndc(a){return sN(a[1],a[2])}function\nsP(a,b){var\nc=a[1];return[0,c,hQ(0,a[2],b)[2]]}function\neR(a,b){var\nd=a[1],c=hQ(1,a[2],b);return[0,c[1],[0,d,c[2]]]}function\ndd(a,b,c,d){var\ne=[0,d];if(v===a)var\nh=c[1],g=0;else if(j4<=a)var\nh=c[2].length-1,g=c[1];else\nvar\nh=c[2].length-1,g=0;var\nk=h-1|0;if(k>=g){var\nf=g;for(;;){var\nl=j(c[2],f)[1+f];if(l)e[1]=i(b,l[1],e[1]);var\nm=f+1|0;if(k===f)break;f=m}}if(j4>a)a4(function(a){e[1]=i(b,a,e[1]);return 0},c[3]);if(v!==a)a4(function(a){e[1]=i(b,a,e[1]);return 0},c[4]);return}function\neS(a,b,c){if(typeof\nc===\"number\")throw g([0,f,sQ],1);if(0===c[0])return h(a,c[2]);var\nd=eS(a,b,c[3]);return i(b,eS(a,b,c[2]),d)}function\nbj(a,b,c){var\nd=b[2],e=b[1],f=c2(c);if(f){var\ng=f[1];return typeof\ng===\"number\"?Q(e):Q(eS(a,d,g))}var\nh=[0,db(a,d)];return l(c,function(a){var\nb=sP(h[1],a);h[1]=b;var\nc=dc(b);return c?c[1]:e})}var\naQ=[0,cg,az];function\nsR(a,b){return c5(b,aQ,a)}function\nde(a){return sR(a,J)}function\nhR(a){function\ne(a,b){var\nc=a,d=b;for(;;){if(typeof\nc===\"number\")return d;if(0===c[0])return[0,c[2],d];var\nf=e(c[3],d);c=c[2];d=f}}return e(a,0)}var\nhS=[0,Q(0),function(a,b){return cc(a,b,az)}];function\neT(c,b){return bj(function(a){return J(h(c,a))},aQ,b)}function\nsS(a,b){return ho(bj(b,hS,a))}function\nbk(a){return sS(a,function(a){return l(a,J)})}var\nbl=e;function\nsT(a){return a[kL]}function\nhT(a,b){var\nc=a?a[1]:bl;return zW(b).join(c)}function\neU(a){return 0===sT(a)?1:0}function\ndf(a,b){return k0(a,b)}p[\"Number\"];var\neV=null,sU=undefined;function\ncj(a){return a===eV?1:0}function\nsV(a){return a===sU?1:0}function\nbR(a){var\nb=cj(a);return b?b:sV(a)}function\nhU(a){return 1-bR(a)}function\ndg(a,b){return bR(b)?0:[0,h(a,b)]}var\nk=p;function\neW(a,b){var\nc=a[b];return bR(c)?0:[0,c]}function\neX(a){return new\nk[jU](a)}function\nhV(a){return a[kL]}function\nhW(c,b){return gI(hV(b),function(a){return h(c,b[a])})}function\nhX(a,b){var\nd=b.length-1,e=eX(d),f=d-1|0,g=0;if(f>=0){var\nc=g;for(;;){e[c]=h(a,j(b,c)[1+c]);var\ni=c+1|0;if(f===c)break;c=i}}return e}function\nhY(f,b){return function(a,b,c){var\ne=a,d=c;for(;;){if(!d)return b;var\ng=d[2];b[e]=h(f,d[1]);e=e+1|0;d=g}}(0,eX(0),b)}function\ns0(a,b){var\nc=new\nk[\"Error\"](b);return a?(c[cq]=a[1],c):c}var\ns2=Symbol.iterator;function\ns4(a){return a.next()}function\ns5(a){var\nb=dg(function(a){return a|0},a[\"done\"]);return b?b[1]:0}function\ns6(a){return a[dE]}function\nhZ(i,g,c,d,e){return function(a,b){var\nd=b;for(;;){var\ne=s4(a);if(s5(e))return d;var\nf=s6(e),j=h(g,f[1]);d=x(c,h(i,f[0]),j,d)}}(d,e)}k[\"Promise\"];function\nsY(a){return as(a)}function\nbm(a,b,c){return dZ(a,sY(b),c)}function\naA(a){return as(a)}function\nC(a){return H(a)}function\nbS(a,b){return a\ninstanceof\nb?1:0}var\nsW=true;function\nsX(a,b){a[b];return}function\nsZ(c,b){return lW(hV(b),function(a){return h(c,b[a])})}function\ns1(a,b){return h(function(a){throw a},s0(a,b))}function\ns3(a){return a[s2]()}k[\"Event\"];function\neY(a){return a[fv]}function\nh0(a,b,c,d){var\ne=a?a[1]:{},f=by(1,c);d.addEventListener(b,f,e);return function(a){d.removeEventListener(b,f,e);return 0}}function\nh1(a){return h(a,0)}var\neZ=\"change\",dh=\"click\";k[\"ArrayBuffer\"];k[\"DataView\"];function\ns7(a){a.preventDefault();return 0}var\ns8=\"DOMContentLoaded\",s9=ka,s_=\"scroll\",s$=\"wheel\";k[\"Blob\"];k[\"File\"];var\nh2=k[\"JSON\"];k[\"encodeURI\"];k[\"decodeURI\"];k[\"encodeURIComponent\"];k[\"decodeURIComponent\"];k[\"URL\"];k[\"URLSearchParams\"];function\naR(a,b){return[0,a,b]}var\ndi=[0,bl,bl];function\ne0(a){return[0,a,bl]}function\nh3(a){return a}var\nck=ku,e1=jN,h4=cq,h5=jz,e2=\"type\",e3=dE,td=\"for\";function\naS(a){return aR(ck,a)}function\nh6(a){return aR(td,a)}var\ntf=e0(jl),th=e0(\"required\");function\ndj(a){return aR(h5,a)}var\nti=e0(\"selected\"),bn=k[\"document\"];function\nta(a){return h2.stringify(a)}function\ntb(a){try{var\nc=h2.parse(a)}catch(f){var\nb=L(f);if(b[1]===ey)return[1,b[2]];throw g(b,0)}return[0,c]}function\ntc(a,b){return a?b:di}var\nte=\"placeholder\";function\ntg(a){return aR(e1,a)}function\ntj(a){return aR(e2,a)}function\ntk(a){return aR(e3,a)}function\ntl(a){return a[\"ownerDocument\"]}if(!bR(bn))bn[jI];function\ntm(a,b){a.appendChild(b);return 0}function\ntn(a,b,c,d){var\ng=b,f=c,e=d;for(;;){if(!e){if(0!==g)a.setAttribute(jz,hT([0,\";\"],a3(g)));if(0!==f)a.setAttribute(ku,hT([0,aE],a3(f)));return}var\nh=e[2],k=e[1],i=k[2],j=k[1];if(eU(j))e=h;else if(df(j,h5)){g=[0,i,g];e=h}else if(df(j,ck)){var\nl=eU(i)?f:[0,i,f];f=l;e=h}else{a.setAttribute(j,i);e=h}}}function\nh7(a,b,c,d){var\nf=a?a[1]:bn,g=b?b[1]:0,e=f.createElement(c);tn(e,0,0,g);a4(function(a){return tm(e,a)},d);return e}function\nbo(a,b){var\nc=a?a[1]:bn;return c.createTextNode(C(b))}function\nh8(a,b,c){return eU(a)?0:b?(c.setAttribute(a,b[1]),0):(c.removeAttribute(a),0)}function\nh9(a,b,c){return b?(c[jm].add(a),0):(c[jm].remove(a),0)}var\nh_=\"div\";function\ntx(a,b,c,d){return h7(b,c,a,d)}function\nh$(a,b,c){return tx(h_,a,b,c)}function\nia(a){return a[jI]}function\ndk(a,b,c){dZ(a,b,c);return 0}var\ndl=k[kP];function\ndm(a){return zT(function(a,b,c){var\ne=b,d=c;for(;;){if(!d)return a;var\nf=d[2];a[e]=d[1];e=e+1|0;d=f}}(eX(0),0,a))}function\nah(a){return dk(dl,tA,dm(a))}function\ne4(a){return dk(dl,tF,dm(a))}k[kP];k[\"navigator\"];var\ntI=k[\"performance\"],dn=k[kp];sX(k,tJ);function\nto(a,b){dZ(a,kF,gL(b));return}function\ntp(a,b,c){var\ne=a?a[1]:k[kp],d=e.getComputedStyle(c)[b];return bR(d)?bl:d}function\ntq(a,b){var\nc=a?a[1]:kh,d=kh<=c?1:0;b.scrollIntoView(!!d);return 0}var\ntr=\"button\",ts=\"form\",tt=ka,tu=\"label\",tv=\"option\",tw=\"select\";function\nty(a){var\nb=a[\"body\"];return hU(b)?b:s1(0,\"Document body is null. Try to defer your script execution.\")}function\ntz(a){return dg(function(a){return a},a[\"activeElement\"])}function\ntB(a){return dk(dl,tC,dm(a))}function\ntD(a){return dk(dl,tE,dm(a))}function\ntG(a){return a}function\ntH(a){return a.now()}function\ntK(a,b){return k.setTimeout(by(1,b),a)}function\ntL(a){k.clearTimeout(a);return}function\ntM(a){k.requestAnimationFrame(by(1,a));return}k[\"ClipboardItem\"];k[\"FormData\"];k[\"Headers\"];k[\"Request\"];k[\"Response\"];k[\"fetch\"];k[\"MediaStream\"];k[\"MediaRecorder\"];k[\"MessageChannel\"];k[\"BroadcastChannel\"];k[\"Notification\"];k[\"WebSocket\"];function\ntN(a){return a[\"localStorage\"]}function\ntO(a,b){function\nc(a){return a}return function(a){return dg(c,a)}(a.getItem(b))}function\ntP(a,b,c){try{a.setItem(b,c);return}catch(f){var\nd=L(f);if(d[1]===ey)return;throw g(d,0)}}function\naB(a,b,c){return[0,a,b,c]}function\nib(a){var\nb=a[1];return 82===b?gv(c2(a[2])):83<=b?gv(c2(a[2])):1}function\ndp(a){return cL(c2(a))}function\ntQ(a){return d_(cM(function(a){var\nb=a[1];return 82===b?[0,dp(a[2]),0]:83<=b?hR(dp(a[2])):[0,a[2],0]},a))}function\nic(a){if(!a)return tR;var\nb=l1(ib,a),c=b[2];return[0,tQ(b[1]),c]}var\nid=kF,e5=\"before\";function\ntU(a){return[0,a]}function\ntV(a,b){return[1,eV,a,b]}var\ntW=\"remove\",tX=\"contains\";function\nie(a){var\nb=tz(tl(a));return b?bm(a,tX,[0,b[1]])|0:0}function\nig(e,b){var\nc=[0,db(tU,tV)];return l(b,function(a){var\nb=eR(c[1],a),d=b[2],g=b[1];c[1]=d;dd(v,function(a,b){return 0===a[0]?a[1][dD]=sW:0},g,0);var\nh=ie(e),i=dc(d);if(i){var\nf=function(d,b){if(0!==b[0]){if(!cj(b[1]))return b[1];var\nl=f(d,b[3]),k=f(l,b[2]);b[1]=k;return k}var\nc=b[1];delete\nc[dD];if(c.parentNode!==e)if(cj(d))bm(e,id,[0,c]);else\nbm(d,e5,[0,c]);else{var\na=c.nextSibling!==d?1:0;if(a){if(h)var\ng=ie(c),i=g?function(a){for(;;){var\nb=c.nextSibling;if(b===d)return 1;if(cj(b))return 0;bm(c,e5,[0,b])}}(0):g;else\nvar\ni=h;var\nj=1-i}else\nvar\nj=a;if(j)if(cj(d))bm(e,id,[0,c]);else\nbm(d,e5,[0,c])}return c};f(eV,i[1])}dd(v,function(a,b){if(0!==a[0])return 0;var\nc=a[1],d=hU(c[dD]),e=d?(delete\nc[dD],bm(c,tW,[0]),0):d;return e},g,0);return e})}var\ndq=Q(0),e6=[0,bl,bl];function\ntS(a){if(!a)return tT;var\nb=a[1],c=b[1];if(82===c){if(!a[2])return[0,0,[0,l(b[2],J)]]}else\nif(83<=c){if(!a[2])return[0,0,[0,b[2]]]}else if(!a[2])return[0,[0,b[2],0],0];return lY(ib,a)?[0,d_(cM(function(a){var\nb=a[1];return 82===b?[0,dp(a[2]),0]:83<=b?hR(dp(a[2])):[0,a[2],0]},a)),0]:[0,0,[0,c5(function(a){var\nb=a[1];return 82===b?l(a[2],J):83<=b?a[2]:Q(J(a[2]))},hS,a)]]}function\nih(c,b){function\nd(a){var\nb=a[2],d=a[1];return df(d,ck)?h9(b,1,c):h8(d,[0,b],c)}function\ne(a){var\nb=a[1],d=a[2];return df(b,ck)?h9(d,0,c):h8(b,0,c)}function\nh(a){var\nb=[0,e6];return function(a){if(b[1]!==e6)e(b[1]);var\nc=h3(a);d(c);b[1]=c;return 0}}return c5(function(a){var\nb=a[1];if(82===b){var\ni=a[2];return l(i,h(0))}if(83>b)throw g([0,f,tY],1);var\nj=a[2],c=[0,db(function(a){var\nb=h3(a);d(b);return b},function(a,b){return e6})];return l(j,function(a){var\nb=eR(c[1],a),d=b[2],f=b[1];c[1]=d;dd(v,function(a,b){return e(a)},f,0);dc(d);return 0})},[0,dq,function(a,b){return dq}],b)}function\ne7(a,b){return h0(b[1],b[2],b[3],a)}function\ntZ(c,b){return c5(function(a){var\nb=a[1];if(82===b){var\nd=[0,0];return l(a[2],function(a){var\nb=d[1];if(b)h1(b[1]);d[1]=[0,e7(c,a)];return 0})}if(83>b)throw g([0,f,t0],1);var\nh=a[2],e=[0,db(function(a){return e7(c,a)},function(a,b){return a})];return l(h,function(a){var\nb=eR(e[1],a),c=b[2],d=b[1];e[1]=c;dd(v,function(a,b){return h1(a)},d,0);dc(c);return 0})},[0,dq,function(a,b){return dq}],b)}function\nii(a,b,c,d,e,f){var\nq=b?b[1]:0,r=c?c[1]:0,s=d?d[1]:function(a){return},m=ic(q),k=m[2],t=m[1],n=ic(r),o=n[2],u=n[1],p=tS(f),i=p[2],g=h7(a,[0,t],e,p[1]);h(s,g);if(k)if(i)var\nv=ig(g,i[1]),j=cc(ih(g,k),v,function(a,b){return b});else\nvar\nj=l(ih(g,k),function(a){return g});else\nvar\nj=i?ig(g,i[1]):Q(g);a4(function(a){e7(g,a);return 0},u);var\nw=o?cc(tZ(g,o),j,function(a,b){return b}):j;return w}function\nbT(a,b,c,d,e,f){return ii(b,c,d,e,a,f)}function\nt1(a,b,c,d,e,f){return ii(b,c,d,e,a,0)}function\ne8(a,b,c,d,e){return bT(tr,a,b,c,d,e)}function\nR(a,b,c,d,e){return bT(h_,a,b,c,d,e)}function\nij(a,b,c,d,e){return t1(tt,a,b,c,d,e)}function\nik(a,b,c,d,e){return bT(tu,a,b,c,d,e)}function\nt2(a,b,c,d,e){return bT(ts,a,b,c,d,e)}function\nt3(a,b,c,d,e){return bT(tv,a,b,c,d,e)}function\nt4(a,b,c,d,e){return bT(tw,a,b,c,d,e)}function\ndr(a,b){return b=c)return uj;if(b===\"bold\")return ui;if(b===\"cyan\")return uh;if(b===\"green\")return ug;if(b===\"magenta\")return uf;if(b===\"red\")return ue;if(b===\"reset\")return ud;if(b===\"white\")return uc;if(b===\"yellow\")return ub}else{if(b===\"Black\")return us;if(b===\"Blue\")return ur;if(b===\"Cyan\")return uq;if(b===\"Green\")return up;if(b===\"Magenta\")return uo;if(b===\"Red\")return un;if(b===\"White\")return um;if(b===\"Yellow\")return ul;if(b===\"black\")return uk}throw g(e_,1)}function\nio(a,b){a5(b,a);return uu}function\nip(a){try{mD(a);mE(a)}catch(f){var\nb=L(f);if(b!==ee)throw g(b,0)}return uv}var\niq=[q,uw,ae(0)],ut=0;function\nux(a,b,c){if(c[1]===iq)return io(a,c[2]);if(c[1]!==b$)return h(b,c);var\ne=c[2];try{var\nf=io(a,im(e));return f}catch(f){var\nd=L(f);if(d===e_)return h(b,c);throw g(d,0)}}function\nuy(a,b,c){if(c[1]===iq)return ip(a);if(c[1]!==b$)return h(b,c);var\ne=c[2];try{im(e)}catch(f){var\nd=L(f);if(d===e_)return h(b,c);throw g(d,0)}return ip(a)}function\nuz(a){var\nc=bC(0);p_(a,1);var\nb=p$(a,0),d=b[2],e=b[1];return qa(a,[0,function(a){return ux(c,e,a)},function(a){return uy(c,d,a)},b[3],b[4]])}function\nuA(a,b){var\nd=b8(64),c=ex(d),e=a?ut:a;if(e)uz(c);return qG(function(a){bJ(c,0);return cQ(d)},c,b)}function\nuB(a){return uA(1,a)}function\nuC(a,b){return l3(a,b)}function\nuD(a){try{var\nc=[0,k8(a)];return c}catch(f){var\nb=L(f);if(b[1]===b3)return 0;throw g(b,0)}}function\nuE(a){return a|0}function\nuG(a,b,c,d){var\ng=a,f=b,e=d;for(;;){if(!e){g[1+f]=0;return}var\nj=e[2],i=[0,h(c,e[1]),kg];g[1+f]=i;g=i;f=1;e=j}}function\nuF(a,b){if(!b)return 0;var\nd=b[2],c=[0,h(a,b[1]),kg];uG(c,1,a,d);return c}function\ne$(a,b){return b?[0,h(a,b[1])]:0}function\nuH(a,b,c){return c?h(b,c[1]):a}function\nuI(a,b){if(b)return h(a,b[1]);return}function\nuJ(a,b){return b?b[1]:a}function\nuK(a,b){return a?a[1]:b}function\nuL(a){return a?[0,a[1],0]:0}function\nuM(a,b){return 0===b[0]?h(a,b[1]):[1,b[1]]}function\nuN(a,b){return uM(b,a)}function\nuO(a){var\nb=mv(a);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b[37],,,,,,,,,,,b[23]]}function\nuP(a){var\nb=uO(a);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b[40],,,,,,,,,,,,,,,,,,,,b[51]]}function\nuQ(e,b){var\nd=n(e);if(dr(d,n(b)))return 0;var\nf=n(b)-d|0;return function(a){var\nc=a;for(;;){if(t5(c,d))return 1;if(_(b,f+c|0)!==_(e,c))return 0;c=c+1|0}}(0)}function\nfa(a,b){return uQ(a,b)?[0,eb(b,0,n(b)-n(a)|0)]:0}var\nir=[q,uS,ae(0)];function\nis(a){return[0,[0,a]]}function\nbp(a,b,c,d){return[1,a,b,c,d]}function\nuU(a){if(0===a[0]&&typeof\na[1]===\"number\")return 1;return 0}function\nit(a,b){if(0===b[0]){var\nc=b[1];if(typeof\nc===\"number\")return is(a);switch(c[0]){case\n0:return[0,[1,a,c[1]]];case\n1:return[0,[2,a,c[1],c[2]]];default:return bp(4,[1,a,c[1]],uT,[1,c[2],c[3]])}}var\nd=b[2],f=b[1];if(typeof\nd!==\"number\")switch(d[0]){case\n0:break;case\n1:return bp(f+1|0,[2,a,d[1],d[2]],b[3],b[4]);default:var\ne=b[3],h=d[3],i=d[2],j=d[1],g=aw(e),k=aD===g?e[1]:ba===g?cK(e):e;return bp(f+1|0,[1,a,j],[ba,function(a){return it([0,i,h],k)}],b[4])}return bp(f+1|0,[1,a,d[1]],b[3],b[4])}function\niu(a){if(0===a[0]){var\nb=a[1];if(typeof\nb===\"number\")throw g(ir,1);switch(b[0]){case\n0:return[0,uR,b[1]];case\n1:var\nn=b[2];return[0,is(b[1]),n];default:return[0,[0,[1,b[1],b[2]]],b[3]]}}var\nd=a[3],e=a[2],f=a[1],i=aw(d),j=aD===i?d[1]:ba===i?cK(d):d,h=a[4];if(typeof\nh!==\"number\"&&0!==h[0]){var\nc=a[4];if(typeof\nc!==\"number\"&&2===c[0]){var\nq=c[3];return[0,bp(f-1|0,e,d,[1,c[1],c[2]]),q]}var\np=c[2];return[0,bp(f-1|0,e,d,[0,c[1]]),p]}var\nk=h[1];if(uU(j))return[0,[0,e],k];var\nl=iu(j),m=l[2],o=[1,m[1],m[2]];return[0,bp(f-1|0,e,lF(l[1]),o),k]}function\nuW(a){if(typeof\na===\"number\")return 0;switch(a[0]){case\n0:return 1;case\n1:return 2;default:return 3}}function\nuV(a){try{var\nc=[0,iu(a)];return c}catch(f){var\nb=L(f);if(b===ir)return 0;throw g(b,0)}}function\nuX(a){return 0===a[0]?uW(a[1]):a[1]}function\nuY(a){return a[\"height\"]}function\nuZ(a){return a}function\nu2(a){switch(a){case\n0:return u3;case\n1:return u4;default:return u5}}function\nu0(a){return uZ(a[\"contentRect\"])}function\nu1(a){a[fv];return}function\nu6(a,b,c){var\nd=b?[0,c,{box:C(u2(b[1]))}]:[0,c];dZ(a,\"observe\",d);return 0}function\nu7(c){return new\nk[\"ResizeObserver\"](function(a,b){return i(c,sZ(function(a){return a},a),b)})}var\nu8=jv,u9=\"pattern\",iv=uP([0,ec]);function\nu_(a,b){h(a,b);return b}function\nu$(a){var\nb=fa(va,a);if(b){var\nc=b[1],d=uD(c);if(d)return[0,[0,d[1]]];var\ng=function(a){return[0,a]};return function(a){return e$(g,a)}(e9(c))}var\ne=fa(vb,a);if(e){var\nh=function(a){return[1,a]};return function(a){return e$(h,a)}(e9(e[1]))}var\nf=fa(vc,a);if(!f)return 0;function\ni(a){return[1,a]}return function(a){return e$(i,a)}(e9(f[1]))}function\niw(a){switch(a[0]){case\n0:var\nb=a[1];return h(B(vd),b);case\n1:var\nc=a[1];return h(B(ve),c);default:var\nd=a[1];return h(B(vf),d)}}function\nix(a){var\nc=a?a[1]:ia(bn);function\nb(a){var\nb=u$(as(tp(0,\"font-size\",a)));if(!b)return 16.;var\nc=b[1];return 0===c[0]?c[1]:aK(vg)}return function(a){switch(a[0]){case\n0:return a[1];case\n1:var\nd=a[1];return d*b(ia(bn));default:var\ne=a[1];return e*b(c)}}}function\nvh(e,b,c,d){function\nf(a,b){return cc(d,a,b)}function\ng(a,b){return x(e,b[1],b[2],a)}return function(a){return f(a,g)}(cc(b,c,function(a,b){return[0,a,b]}))}var\nvk=[q,vj,ae(0)],vm=[q,vl,ae(0)];function\niy(a){return[0,0]}function\niz(a,b){if(a[1])throw g(vm,1);a[1]=[0,b];return 0}function\niA(a){var\nb=a[1];if(b)return b[1];throw g(vk,1)}function\nvi(a,b,c){return vh(function(a,b,c){return[0,a,b,c]},a,b,c)}function\nvn(a){return ta(a)}function\nvo(a){var\nb=tb(a);return 0===b[0]?[0,b[1]]:(tB([0,b[1],0]),vp)}var\niB=es(0,64),iC=tN(dn);function\nvq(a){return pS(iB,a)?aK(h(B(vr),a)):pP(iB,a,0)}function\niD(c,b){return function(a){return tP(iC,c,a)}(vn(b))}function\nvs(a){var\nb=tO(iC,a);function\nc(a){return vo(a)}var\nd=b?[0,b[1]]:vt;return uN(d,c)}function\nvu(a,b){var\nc=vs(a);if(0===c[0])return c[1];var\nd=c[1];return typeof\nd===\"number\"?h(b,0):(tD([0,d[2],0]),h(b,0))}function\nvv(d,b){iD(d,b);var\na=am(b),c=eC(0,aP(a));eD(c,function(a){iD(d,bO(c));return 0});bO(c);return a}function\nvw(a,b){vq(a);var\nc=H(a);return vv(c,vu(c,b))}function\niE(a,b){return vw(a,function(a){return b})}var\nvy=iv[49],vx=iv[29];function\nvz(a){return uF(function(a){return[0,80,aS(H(a))]},vy(a))}var\nvA=0;function\na8(d,b,c){var\na=b[1],e=82===a?[0,82,l(b[2],function(a){return function(a){return aR(d,a)}(H(a))})]:83<=a?aK(vD):[0,80,function(a){return aR(d,a)}(H(b[2]))];return[0,e,c]}function\nfb(d,b,c){return b?[0,[0,80,function(a){return aR(d,a)}(H(b[1]))],c]:c}function\niF(a,b){var\nc=b[1];return 82===c?[0,82,l(b[2],a)]:83<=c?[0,83,eT(a,b[2])]:[0,80,h(a,b[2])]}function\nvF(a){return 0===a[0]?aS(H(a[1])):a[1]}function\nfc(a,b){return[0,iF(vF,a),b]}function\nau(a){return fc(a,0)}function\nds(a,b){return fc(a,b)}function\nvB(a,b){var\nd=vz(b[1]),e=b[2],c=function(a){return bB(e,a)}(d);return a?[0,[0,80,tg(H(a[1]))],c]:c}function\nvC(a){return[0,vx(a),vA]}function\nvE(a,b,c){return b?[0,[0,80,a],c]:c}function\nvG(a){return fc(iF(function(a){return[0,a]},a),0)}function\nvH(a,b){return 0===b[0]?(a.scroll(0,b[1]),0):tq(0,b[1])}function\nvI(a,b,c,d,e){var\ng=a?a[1]:0,h=b?b[1]:0,f=am(1),i=ds(vJ,ds([0,82,l(aP(f),function(a){return a?[1,aS(\"locked\")]:[1,di]})],g)),j=vG(vK),k=[0,[0,80,aB(0,dh,function(a){return ac(f,1)})],0],m=R(0,[0,j],[0,k],0,[0,[0,82,e8(0,0,0,0,[0,[0,80,bo(0,vL)],0])],0]),n=aB(0,s$,function(a){var\nb=bM(f);return b?ac(f,0):b});return R(0,[0,i],[0,[0,[0,80,n],h]],c,[0,[0,82,l(vi(e,aP(f),d),function(a){var\nb=a[1],c=a[3];if(a[2])uI(function(a){return vH(b,a)},c);return b})],[0,[0,82,m],0]])}function\ndt(a,b){return typeof\nb===\"number\"?0:0===b[0]?[0,h(a,b[1])]:[1,b[1]]}function\nvM(e,b,c){var\nd=am(c);return[0,aB(0,b,function(a){return ac(d,h(e,eY(a)[dE]))}),d]}function\niG(a,b,c,d,e,f,g,h,i,j){var\nl=d?d[1]:0,m=f?f[1]:0,n=function(a){return fb(u9,h,a)}(function(a){return vE(th,m,a)}([0,[0,80,tj(H(i))],l])),o=uK(b,function(a){return[0,a]}),k=vM(a,g,j),p=k[2],q=k[1];return[0,ij(c,[0,n],[0,[0,[0,80,q],uL(e)]],0,0),p,o]}function\ndu(a,b,c,d,e,f,g,h){var\ni=c?c[1]:0,j=function(a){return fb(e3,h,a)}(function(a){return fb(te,g,a)}(i));return iG(aA,a,b,[0,j],d,e,s9,f,vO,uJ(vN,h))}function\ndv(a,b,c,d){var\ne=b?b[1]:0;return iG(function(a){return 0},0,a,[0,a8(e3,d,e)],c,0,eZ,0,vP,0)}function\naC(a,b){return l(a,function(a){return[0,a,b]})}function\ndw(a,b,c,d){return function(g){var\ni=[0,[0,cg,function(a){return a}],function(a,b){var\nc=b[2],d=a[2];return[0,az(a[1],b[1]),function(a){return h(c,h(d,a))}]}];function\nj(a){var\nb=a[1],c=a[2];function\nd(a){var\nc=bM(b[2]);return h(b[3],c)}return[0,J(b[1]),function(a){var\nb=d(0);return h(h(c,a),b)}]}var\ne=function(a){return bj(j,i,a)}(bk(d[2])),f=[0,82,l(e,function(a){var\nb=a[2];return aB(0,u8,function(a){h(g,h(b,d[1]));return s7(a)})})],k=l(e,function(a){return a[1]}),m=uH([0,f,0],function(a){return lS(f,a)},c);return t2(a,b,[0,m],0,[0,[0,83,bk(k)],0])}}function\niH(a,b){return a?h(B(vQ),b):b}function\nvR(a,b,c,d){var\ne=a?a[1]:1,f=b?b[1]:0,g=c?c[1]:0;return function(a){var\nb=iH(1,d[1]),h=iH(0,d[1]),c=e?iE(b,d[2]):am(d[2]),i=d[3];ik(0,[0,[0,[0,80,h6(H(b))],0]],0,0,i);var\nj=[0,80,h],k=function(a){return a8(e2,vS,a)}(function(a){return a8(h4,j,a)}(a8(e1,[0,80,b],f))),m=[0,[0,80,aB(0,eZ,function(a){return ac(c,aA(eY(a)[dE]))})],g];return[0,t4(0,[0,k],[0,m],0,[0,[0,83,bk(eT(function(a){var\nb=a[1],d=a[2],e=au([0,80,[1,tk(H(b))]]),f=ds([0,82,l(aP(c),function(a){return[1,tc(t9(a,b),ti)]})],e);return t3(0,[0,f],0,0,[0,[0,80,bo(0,d)],0])},a))],0]),,c]}}function\niI(a,b,c,d,e,f,g){var\nm=b?b[1]:0,n=c?c[1]:function(a){return},j=h(uB(vT),d);function\nk(a){return a?[0,e]:0}a:{if(a&&a[1]){var\no=iE(j,k(g)),i=o;break a}var\ni=am(k(g))}var\np=ik(0,[0,[0,[0,80,h6(H(j))],0]],0,0,f),q=[0,80,d],r=function(a){return a8(e2,vU,a)}(function(a){return a8(h4,q,a)}(a8(e1,[0,80,j],0))),s=[0,[0,82,l(aP(i),function(a){return a?tf:di})],r];return[0,R(0,0,0,0,[0,[0,82,ij(0,[0,s],[0,[0,[0,80,aB(0,eZ,function(a){var\nb=k(eY(a)[jl]|0);h(n,b);return ac(i,b)})],m]],0,0)],[0,[0,82,p],0]]),i]}function\nvV(a){var\nd=ed(a);return[0,,function(a){return uX(a[1])},function(a){return},,function(a,b,c){var\ne=d[4].call(null,b,c,a[2]);return[0,it(b,a[1]),e]},function(a){var\nc=uV(a[1]);if(!c)return[0,a,0];var\ne=c[1],b=e[2],f=e[1],g=[0,[0,b,d[28].call(null,b,a[2])]];return[0,[0,f,d[7].call(null,b,a[2])],g]},function(a,b){return d[29].call(null,b,a[2])}]}function\nvW(a){var\nb=vV(a);return[0,function(a){b[3].call(null,0);b[3].call(null,0);return}]}function\nvY(a){return bj(function(a){return J(R(0,0,0,0,a[3]))},aQ,a)}function\nvZ(a){return c4(bj(function(a){return a[2]},[0,v3,function(a,b){return i(B(v2),a,b)}],a),function(a){return i(B(v1),v0,a)})}ix(0)(v7);function\nvX(a,b,c){return[0,a,b,c]}function\nv4(a){return vZ(a[1][1])}function\nv5(a){var\nb=iw(a[2]),c=[0,[0,80,aS(jk)],0],d=[0,[0,80,aS(\"lwdui-lazy-table-header\")],c],e=[0,[0,80,dj(H(h(B(v6),b)))],d];return R(0,[0,e],0,0,[0,[0,83,bk(vY(a[1][1]))],0])}var\nv8=vW([0,uC]),dx=k[\"yjs\"];function\nv9(d,b,c){return function(a){var\nr=a[3],s=a[2],f=iy(0),g=iy(0),k=iw(d[2]),u=h(B(v$),k),v=cf(function(a,b){return J([0,eG(a),a,r])},aQ,s);es(0,2048);(function(a){return v8[1].call(null,50)}(0));var\ne=am(0),m=Q(function(a){return a}),b=eC(0,qR(m,aP(e)));eD(b,function(a){var\nc=bO(b);return c[2]?h(c[1],0):0});bO(b);function\nt(a){return i(B(v_),k,a)}function\nj(a){var\nb=[0,aS(\"row_spacer\"),0];return h$(0,[0,[0,dj(H(t(a))),b]],0)}var\nw=l(bj(function(a){var\nb=a[1],c=a[3],d=a[2],e=a8(ck,wa,0),f=[0,80,dj(H(u))];return b?[0,0,J(R(0,[0,[0,f,e]],0,0,[0,[0,83,bk(i(c,d,b[1]))],0])),0]:[0,1,cg,0]},[0,[0,0,cg,0],function(a,b){var\nf=b[3],g=b[2],c=b[1],d=a[3],e=a[2],h=a[1],k=hF(e),i=hF(g);if(typeof\nk===\"number\")return typeof\ni===\"number\"?[0,((h+d|0)+c|0)+f|0,e,0]:[0,(h+d|0)+c|0,g,f];if(typeof\ni===\"number\")return[0,h,e,(d+c|0)+f|0];var\nl=dr(d+c|0,0)?function(a){return az(e,a)}(az(J(Q(j(d+c|0))),g)):az(e,g);return[0,h,l,f]}],v),function(a){var\nb=a[3],c=a[2],d=a[1],e=dr(d,0)?az(J(Q(j(d))),c):c;return dr(b,0)?az(e,J(Q(j(b)))):e}),x=v5(d),y=u7(function(a,b){var\nd=lT(a);u1(d);var\nc=uY(u0(d)),f=bM(e);return f?t6(f[1],c)?ac(e,[0,c]):0:ac(e,[0,c])}),z=au(wb),n=R(0,[0,z],0,[0,function(a){return iz(f,a)}],[0,[0,83,bk(w)],0]),o=au(wc),p=[0,[0,82,l(m,function(c){return aB(0,s_,function(a){var\nd=[0,0.],b=[0,-1];function\ne(e){var\na=800,f=tH(tI);if(t7(b[1],0))tL(b[1]);b[1]=tK(a,function(a){return h(c,e)});var\ng=t8(f-d[1],a);return g?(d[1]=f,h(c,e)):g}iA(g);(function(a){return e(a)}(0));return 0})})],0];function\nq(a){return iz(g,a)}var\nA=c?vI([0,o],[0,p],[0,q],l(c[1],function(a){var\nb=iA(f),c=d[2];return[0,[0,cC(a,uE(ix([0,b])(c)))]]}),n):R(0,[0,o],[0,p],[0,q],[0,[0,82,n],0]);function\nC(a){return u6(y,0,a)}function\nD(a){return u_(C,a)}var\nE=function(a){return l(a,D)}(A),F=vB(0,vC(wd));return R(0,[0,[0,[0,82,l(v4(d),function(a){return dj(H(a))})],F]],0,0,[0,[0,82,x],[0,[0,82,E],0]])}}var\nfd=ed([0,ec]),fe=dx[\"Text\"],ff=dx[jU],fg=dx[\"Map\"],bU=hl(wi,wh),a9=hl(wk,wj);function\nwe(a,b){return[0,a,b]}function\niJ(a){return bS(a,ff)?[0,aW,a]:bS(a,fg)?[0,v,a]:bS(a,fe)?[0,bv,a]:[0,T,a]}function\nwl(a){var\nb=eW(a,wm);if(b)return[0,b[1]];var\nc=eW(a,wn);if(c)return[1,hW(iJ,c[1])];var\nd=eW(a,wo);if(d)return[2,d[1]];throw g([0,f,wp],1)}hn(wq,bU,[0,function(a){return new\nff},function(a,b,c){a.insert(b,hX(function(a){var\nb=a[1];return bv<=b?aW<=b?a[2]:a[2]:v<=b?a[2]:a[2]},c));return 0},function(a,b,c){a.delete(b,c);return 0},function(a,b){a.push(hX(function(a){var\nb=a[1];return bv<=b?aW<=b?a[2]:a[2]:v<=b?a[2]:a[2]},b));return 0},function(a,d){a.forEach(function(a,b,c){return x(d,b,iJ(a),c)});return 0},function(a,b){function\nc(a){return h(b,we(wl,a))}a.observe(c);return c}]);function\nfh(a){return bS(a,ff)?[0,aW,a]:bS(a,fg)?[0,v,a]:bS(a,fe)?[0,bv,a]:[0,T,a]}function\niK(a,b){return function(a){return dg(fh,a)}(a.get(C(b)))}function\nwr(a){return a}function\nws(a){return wr(a[fv])}function\nwt(a){var\nb=aA(a[\"action\"]);if(b!==\"add\")if(b!==jF){if(b!==\"update\")throw g([0,cH,h(B(wu),b)],1);var\nc=1}else\nvar\nc=2;else\nvar\nc=0;var\nd=a[\"oldValue\"],e=bR(d)?0:[0,fh(d)];return[0,c,0,e]}function\niL(a){return s3(a.entries())}hn(wv,a9,[0,function(a){return new\nfg},[0,function(d){var\na=d[jM][\"keys\"].entries();return hZ(aA,wt,function(a,b,c){var\ne=iK(ws(d),a);return fd[4].call(null,a,[0,b[1],e,b[3]],c)},a,fd[1])}],iK,function(a,b,c){var\nd=c[1],e=bv<=d?aW<=d?c[2]:c[2]:v<=d?c[2]:c[2];a.set(C(b),e);return 0},function(a,b){a.delete(C(b));return 0},iL,function(a,d,c){return hZ(aA,fh,function(a,b,c){return x(d,a,b,c)},iL(a),c)},function(a,b){function\nc(a){return h(b,a)}a.observe(c);return c}]);var\nww=dx[\"Doc\"];function\niM(a,b){return a.getArray(C(b))}function\nbq(a,b){a.transact(by(1,b));return 0}function\niN(a){return a}var\nai=a9[4],aT=a9[3],cl=a9[1],dy=bU[5],fi=bU[4],iO=bU[3],iP=bU[1];function\nwf(a){var\nb=a[1];return[0,function(a){return hW(b,a)}(a[2][jM][\"delta\"])]}function\nwg(a,b){var\nc=a?[0,C(a[1])]:[0];return zS(fe,c)}function\nwx(a){return new\nww}var\nwy=a9[8],wz=a9[7],wA=a9[5],wB=a9[2][1],wC=bU[6];function\nwD(a){return a}var\nwE=k[\"IndexeddbPersistence\"];function\nwF(a,b){var\nc=iN(b);new\nwE(C(a),c);return}var\nwG=k[\"WebrtcProvider\"];function\nwH(a,b,c){var\ne=lH(function(a){return[0,wI,hY(C,a)]},b),d=[0,[0,wL,{config:{iceServers:hY(function(a){return a},cM(function(a){return{urls:C(h(B(wK),a))}},wJ))}}]];ah([0,d,0]);var\nf=k$(gL(l0(function(a){return a})([0,e,[0,d,0]]))),g=iN(c);return new\nwG(C(a),g,f)}var\niQ=k[\"Quill\"],wM=k[\"QuillCursors\"];function\nwN(a,b){iQ.register(C(a),b);return}function\nwO(a,b,c){var\nd=a?a[1]:0,e=d?wP:wR,f=b?[0,[0,wQ,!!b[1]]]:[0],g=k$(f);return{theme:C(e),modules:g}}function\nwS(a,b){return new\niQ(a,b)}function\nwT(a){return a}var\nwU=k[\"QuillBinding\"];function\nwV(a,b){var\nc=wT(b);new\nwU(wD(a),c);return}function\nwW(a,b,c){return x(eo(t,wX),b,c,a)}function\niR(a,b,c){var\nd=0<=c?1:0;if(d)var\ne=0<=b?1:0,f=e?(b+c|0)<=a?1:0:e;else\nvar\nf=d;var\ng=1-f;return g?wW(a,b,c):g}var\nwY=[0];function\nwZ(a,b,c,d){var\ne=ap(a,b);cP(c,0,e,0,d);return e}function\niS(a,b){return b<=a?a:b}function\niT(a){return eo(t,a)}function\nw0(a,b){var\nc=a[1];return i(iT(w1),b,c)}function\nw2(a,b){return i(iT(w3),a,b.length-1)}function\ncm(a,b){var\nc=1-(a<=b.length-1?1:0);return c?w2(a,b):c}function\niU(a){return[0,0,0,wY]}function\ncn(a){return a[1]}function\nw4(a,b){return a[3][1+b]}function\niV(a){var\nb=a[1],c=a[3];cm(b,c);if(0>>4|0)));var\nf=b+1|0;function\ni(a,b,c){a0(a,b,c);return}return function(a){return i(d,f,a)}(h(g,c&15))}for(;;){if(4<=d[1])break;var\nn=y(b,d[1]);f(e,c[1],n);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(6<=d[1])break;var\nm=y(b,d[1]);f(e,c[1],m);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(8<=d[1])break;var\nl=y(b,d[1]);f(e,c[1],l);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(10<=d[1])break;var\nk=y(b,d[1]);f(e,c[1],k);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(16<=d[1])return $(e);var\nj=y(b,d[1]);f(e,c[1],j);c[1]=c[1]+2|0;d[1]++}}var\nxf=gU(0),an=wx(0);wN(xh,wM);var\ndz=wH(xj,xi,an);wF(xk,an);dn[\"yjsdoc\"]=an;dn[\"yjsprovider\"]=dz;dz.on(C(xm),by(1,function(a){return ah(xl)}));dz.on(C(xo),by(1,function(a){return ah([0,xn,[0,a,0]])}));dz.on(C(xq),by(1,function(a){return ah([0,xp,[0,a,0]])}));function\nxg(a){return xc(xf,0)}function\nxr(a,b){var\nc=a?a[1]:64,d=hw(0);return[0,d,es(0,c)]}function\niY(a,b,c){var\ne=g1(a[2],b);if(e)var\nd=e[1];else{var\ng=eF(0,a[1]);g2(a[2],b,g);var\nd=g}var\nf=eG(d);return f?ac(f[1][2],[0,c]):rG(d,[0,b,am([0,c])])}function\nfk(a,b){var\nc=g1(a[2],b);if(c)var\nd=c[1];else{var\nf=a[1],e=eF([0,[0,b,am(0)]],f);g2(a[2],b,e);var\nd=e}return aP(cL(eG(d))[2])}function\nfl(a,b){return l(fk(a,b),function(a){if(!a)return 0;var\nb=a[1];if(typeof\nb!==\"number\"&&T===b[1])return[0,aA(b[2])];throw g([0,f,xs],1)})}function\nxt(a){var\nb=hw(0);return[0,b,iU(0)]}function\nxu(a){try{var\nc=[0,iX(a[2],0)];return c}catch(f){var\nb=L(f);if(b[1]===cH)return 0;throw g(b,0)}}function\niZ(a,b){var\nc=eF(a,b[1]);return w7(b[2],c)}function\ni0(a,b,c,d){var\ne=[0,b,[0,c,[0,cn(d),0]]];e4([0,xv,[0,cn(a),e]]);var\nf=cn(d),g=iX(a,0);fj(d,gI(c,function(a){return g}));return w$(a,b,d,f,c)}function\nxw(i,b,c){var\ne=[0,0],j=i[2],d=iU(0);gJ(function(a){switch(a[0]){case\n0:var\nm=a[1];i0(j,e[1],m,d);e[1]=e[1]+m|0;return 0;case\n1:var\nc=a[1];if(0!==cn(d)){var\no=[0,iV(d)];return fj(d,gK(function(a){var\nd=h(b,a),c=rC([0,d],o[1]);o[1]=c;return c},c))}var\nn=xu(i);if(!n)return gJ(function(a){var\nc=h(b,a);return iZ([0,c],[0,i[1],d])},c);var\ns=n[1];return fj(d,gK(function(a){return rA([0,h(b,a)],s)},c));default:var\nk=a[1],t=0===e[1]?sj(i[1]):hD(iV(d)),p=[0,t],u=1;if(k>=1){var\nl=u;for(;;){var\nq=p[1];if(!q)throw g([0,f,xx],1);var\nr=q[1];p[1]=hD(r);rJ(r);var\nv=l+1|0;if(k===l)break;l=v}}e[1]=e[1]+k|0;return 0}},c);var\nk=e[1],a=cn(j)-k|0;if(0}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template K,V\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template {Map} MAP\n * @template {MAP extends Map ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n", "/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value ?? undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n", "/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n\n/**\n * @template {ArrayLike} ARR\n * @template {function(ARR extends ArrayLike ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n", "/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n\n/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n/* c8 ignore end */\n", "/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n", "/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n", "import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n", "/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * \u2022 Transforms data to a binary format (not to a string)\n * \u2022 Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * \u2022 Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) \u21D2 RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n", "/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n", "/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n", "/* eslint-env browser */\n\nexport const subtle = crypto.subtle\nexport const getRandomValues = crypto.getRandomValues.bind(crypto)\n", "/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\nimport { getRandomValues } from 'lib0/webcrypto'\n\nexport const rand = Math.random\n\nexport const uint32 = () => getRandomValues(new Uint32Array(1))[0]\n\nexport const uint53 = () => {\n const arr = getRandomValues(new Uint32Array(8))\n return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0)\n}\n\n/**\n * @template T\n * @param {Array} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\n\n/**\n * @return {string}\n */\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n", "/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10\u03BCs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n", "/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve,function(Error):void):any} f\n * @return {Promise}\n */\nexport const create = f => /** @type {Promise} */ (new Promise(f))\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template {unknown[] | []} PS\n *\n * @param {PS} ps\n * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>}\n */\nexport const all = Promise.all.bind(Promise)\n\n/**\n * @param {Error} [reason]\n * @return {Promise}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @template T\n * @param {T} res\n * @return {Promise}\n */\nexport const resolveWith = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n * @deprecated use untilAsync instead\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* c8 ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {()=>Promise|boolean} check\n * @param {number} timeout\n * @param {number} intervalResolution\n * @return {Promise}\n */\nexport const untilAsync = async (check, timeout = 0, intervalResolution = 10) => {\n const startTime = time.getUnixTime()\n const noTimeout = timeout <= 0\n // eslint-disable-next-line no-unmodified-loop-condition\n while (noTimeout || time.getUnixTime() - startTime <= timeout) {\n if (await check()) return\n await wait(intervalResolution)\n }\n throw new Error('Timeout')\n}\n\n/**\n * @param {number} timeout\n * @return {Promise}\n */\nexport const wait = timeout => create((resolve, _reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n", "/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n", "/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined' && localStorage) {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n", "/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @deprecated use object.size instead\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const size = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n\n/**\n * Make an object immutable. This hurts performance and is usually not needed if you perform good\n * coding practices.\n */\nexport const freeze = Object.freeze\n\n/**\n * Make an object and all its children immutable.\n * This *really* hurts performance and is usually not needed if you perform good coding practices.\n *\n * @template {any} T\n * @param {T} o\n * @return {Readonly}\n */\nexport const deepFreeze = (o) => {\n for (const key in o) {\n const c = o[key]\n if (typeof c === 'object' || typeof c === 'function') {\n deepFreeze(o[key])\n }\n }\n return freeze(o)\n}\n", "/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n", "/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module environment\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next 2 */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {string}\n */\n/* c8 ignore next 5 */\nexport const ensureConf = (name) => {\n const c = getConf(name)\n if (c == null) throw new Error(`Expected configuration \"${name.toUpperCase().replaceAll('-', '_')}\"`)\n return c\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\n/**\n * Color is enabled by default if the terminal supports it.\n *\n * Explicitly enable color using `--color` parameter\n * Disable color using `--no-color` parameter or using `NO_COLOR=1` environment variable.\n * `FORCE_COLOR=1` enables color and takes precedence over all.\n */\nexport const supportsColor = forceColor || (\n !hasParam('--no-colors') && // @todo deprecate --no-colors\n !hasConf('no-color') &&\n (!isNode || process.stdout.isTTY) && (\n !isNode ||\n hasParam('--color') ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n )\n)\n/* c8 ignore stop */\n", "/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as array from './array.js'\nimport * as math from './math.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Implements base64url - see https://datatracker.ietf.org/doc/html/rfc4648#section-5\n * @param {Uint8Array} buf\n */\nexport const toBase64UrlEncoded = buf => toBase64(buf).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n\n/**\n * @param {string} base64\n */\nexport const fromBase64UrlEncoded = base64 => fromBase64(base64.replaceAll('-', '+').replaceAll('_', '/'))\n\n/**\n * Base64 is always a more efficient choice. This exists for utility purposes only.\n *\n * @param {Uint8Array} buf\n */\nexport const toHexString = buf => array.map(buf, b => b.toString(16).padStart(2, '0')).join('')\n\n/**\n * Note: This function expects that the hex doesn't start with 0x..\n *\n * @param {string} hex\n */\nexport const fromHexString = hex => {\n const hlen = hex.length\n const buf = new Uint8Array(math.ceil(hlen / 2))\n for (let i = 0; i < hlen; i += 2) {\n buf[buf.length - i / 2 - 1] = Number.parseInt(hex.slice(hlen - i - 2, hlen - i), 16)\n }\n return buf\n}\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data =>\n encoding.encode(encoder => encoding.writeAny(encoder, data))\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n\n/**\n * Shift Byte Array {N} bits to the left. Does not expand byte array.\n *\n * @param {Uint8Array} bs\n * @param {number} N should be in the range of [0-7]\n */\nexport const shiftNBitsLeft = (bs, N) => {\n if (N === 0) return bs\n bs = new Uint8Array(bs)\n bs[0] <<= N\n for (let i = 1; i < bs.length; i++) {\n bs[i - 1] |= bs[i] >>> (8 - N)\n bs[i] <<= N\n }\n return bs\n}\n", "/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array>} arr\n * @param {function(L, R):X} f\n * @return {Array}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n", "/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* c8 ignore start */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\nexport const createTextNode = text => doc.createTextNode(text)\n\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array>} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array|HTMLCollection} children\n * @return {DocumentFragment}\n */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array} nodes\n * @return {Element}\n */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array|pair.Pair>} attrs Array of key-value pairs\n * @param {Array} children\n * @return {Element}\n */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair} pair\n */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array>} pairs\n * @return {string}\n */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map} m\n * @return {string}\n */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf}\n */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nconst _parse = html => domParser.parseFromString(`${html}`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n/* c8 ignore stop */\n", "/**\n * JSON utility functions.\n *\n * @module json\n */\n\n/**\n * Transform JavaScript object to JSON.\n *\n * @param {any} object\n * @return {string}\n */\nexport const stringify = JSON.stringify\n\n/**\n * Parse JSON object.\n *\n * @param {string} json\n * @return {any}\n */\nexport const parse = JSON.parse\n", "/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n", "import * as symbol from './symbol.js'\nimport * as time from './time.js'\nimport * as env from './environment.js'\nimport * as func from './function.js'\nimport * as json from './json.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n * @return {Array}\n */\nexport const computeNoColorLoggingArgs = args => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n if (arg === undefined) {\n break\n } else if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else if (arg.constructor === Object) {\n break\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/* c8 ignore start */\n/**\n * @param {function(...any):void} _print\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (_print, moduleName) => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null &&\n (debugRegexVar === '*' || debugRegexVar === 'true' ||\n new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n return !doLogging\n ? func.nop\n : (...args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = args[0]()\n }\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n _print(\n color,\n moduleName,\n UNCOLOR,\n ...args.map((arg) => {\n if (arg != null && arg.constructor === Uint8Array) {\n arg = Array.from(arg)\n }\n const t = typeof arg\n switch (t) {\n case 'string':\n case 'symbol':\n return arg\n default: {\n return json.stringify(arg)\n }\n }\n }),\n color,\n ' +' + timeDiff + 'ms'\n )\n }\n}\n/* c8 ignore stop */\n", "/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as set from './set.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as common from './logging.common.js'\n\nexport { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js'\n\n/**\n * @type {Object>}\n */\nconst _browserStyleMap = {\n [common.BOLD]: pair.create('font-weight', 'bold'),\n [common.UNBOLD]: pair.create('font-weight', 'normal'),\n [common.BLUE]: pair.create('color', 'blue'),\n [common.GREEN]: pair.create('color', 'green'),\n [common.GREY]: pair.create('color', 'grey'),\n [common.RED]: pair.create('color', 'red'),\n [common.PURPLE]: pair.create('color', 'purple'),\n [common.ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [common.UNCOLOR]: pair.create('color', 'black')\n}\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst computeBrowserLoggingArgs = (args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n break\n }\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst computeLoggingArgs = env.supportsColor\n ? computeBrowserLoggingArgs\n : common.computeNoColorLoggingArgs\n/* c8 ignore stop */\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.print(args))\n}\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(common.ORANGE)\n vconsoles.forEach((vc) => vc.print(args))\n}\n/* c8 ignore stop */\n\n/**\n * @param {Error} err\n */\n/* c8 ignore start */\nexport const printError = (err) => {\n console.error(err)\n vconsoles.forEach((vc) => vc.printError(err))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\n/* c8 ignore start */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log(\n '%c ',\n `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`\n )\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach((vc) => vc.printImg(url, height))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} base64\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printImgBase64 = (base64, height) =>\n printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.group(args))\n}\n\n/**\n * @param {Array} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupEnd())\n}\n\n/**\n * @param {function():Node} createNode\n */\n/* c8 ignore next 2 */\nexport const printDom = (createNode) =>\n vconsoles.forEach((vc) => vc.printDom(createNode()))\n\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printCanvas = (canvas, height) =>\n printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = set.create()\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst _computeLineSpans = (args) => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n let arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n arg = 'undefined '\n }\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [\n pair.create('style', dom.mapToStyleString(currentStyle))\n ], [dom.text(arg.toString())])\n if (span.innerHTML === '') {\n span.innerHTML = ' '\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(\n dom.element('span', [], [dom.text(/** @type {string} */ (content))])\n )\n }\n }\n return spans\n}\n/* c8 ignore stop */\n\nconst lineStyle =\n 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* c8 ignore start */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [\n pair.create('hidden', collapsed),\n pair.create('style', 'color:grey;font-size:120%;')\n ], [dom.text('\u25BC')])\n const triangleRight = dom.element('span', [\n pair.create('hidden', !collapsed),\n pair.create('style', 'color:grey;font-size:125%;')\n ], [dom.text('\u25B6')])\n const content = dom.element(\n 'div',\n [pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )],\n [triangleDown, triangleRight, dom.text(' ')].concat(\n _computeLineSpans(args)\n )\n )\n const nextContainer = dom.element('div', [\n pair.create('hidden', collapsed)\n ])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', (_event) => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('div', [\n pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )\n ], _computeLineSpans(args))\n ])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([common.RED, common.BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('img', [\n pair.create('src', url),\n pair.create('height', `${math.round(height * 1.5)}px`)\n ])\n ])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n/* c8 ignore stop */\n\n/**\n * @param {Element} dom\n */\n/* c8 ignore next */\nexport const createVConsole = (dom) => new VConsole(dom)\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName)\n", "/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator} iterator\n * @param {function(T):R} f\n * @return {IterableIterator}\n */\nexport const mapIterator = (iterator, f) => ({\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult} next\n * @return {IterableIterator}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n", "import { ObservableV2 } from 'lib0/observable'\n\nimport {\n Doc // eslint-disable-line\n} from '../internals.js'\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {ObservableV2}\n */\nexport class AbstractConnector extends ObservableV2 {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super()\n this.doc = ydoc\n this.awareness = awareness\n }\n}\n", "import {\n findIndexSS,\n getState,\n splitItem,\n iterateStructs,\n UpdateEncoderV2,\n DSDecoderV1, DSEncoderV1, DSDecoderV2, DSEncoderV2, Item, GC, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nimport * as array from 'lib0/array'\nimport * as math from 'lib0/math'\nimport * as map from 'lib0/map'\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\n\nexport class DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock\n /**\n * @type {number}\n */\n this.len = len\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nexport class DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid))\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i]\n iterateStructs(transaction, structs, del.clock, del.len, f)\n }\n })\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nexport const findIndexDS = (dis, clock) => {\n let left = 0\n let right = dis.length - 1\n while (left <= right) {\n const midindex = math.floor((left + right) / 2)\n const mid = dis[midindex]\n const midclock = mid.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client)\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n}\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock)\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1]\n const right = dels[i]\n if (left.clock + left.len >= right.clock) {\n left.len = math.max(left.len, right.clock + right.len - left.clock)\n } else {\n if (j < i) {\n dels[j] = right\n }\n j++\n }\n }\n dels.length = j\n })\n}\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nexport const mergeDeleteSets = dss => {\n const merged = new DeleteSet()\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice()\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || [])\n }\n merged.clients.set(client, dels)\n }\n })\n }\n sortAndMergeDeleteSet(merged)\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([])).push(new DeleteItem(clock, length))\n}\n\nexport const createDeleteSet = () => new DeleteSet()\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nexport const createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet()\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = []\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i]\n if (struct.deleted) {\n const clock = struct.id.clock\n let len = struct.length\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {\n len += next.length\n }\n }\n dsitems.push(new DeleteItem(clock, len))\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems)\n }\n })\n return ds\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nexport const writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size)\n\n // Ensure that the delete set is written in a deterministic order\n array.from(ds.clients.entries())\n .sort((a, b) => b[0] - a[0])\n .forEach(([client, dsitems]) => {\n encoder.resetDsCurVal()\n encoding.writeVarUint(encoder.restEncoder, client)\n const len = dsitems.length\n encoding.writeVarUint(encoder.restEncoder, len)\n for (let i = 0; i < len; i++) {\n const item = dsitems[i]\n encoder.writeDsClock(item.clock)\n encoder.writeDsLen(item.len)\n }\n })\n}\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nexport const readDeleteSet = decoder => {\n const ds = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([]))\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()))\n }\n }\n }\n return ds\n}\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {Uint8Array|null} Returns a v2 update containing all deletes that couldn't be applied yet; or null if all deletes were applied successfully.\n *\n * @private\n * @function\n */\nexport const readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet()\n const numClients = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal()\n const client = decoding.readVarUint(decoder.restDecoder)\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder)\n const structs = store.clients.get(client) || []\n const state = getState(store, client)\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock()\n const clockEnd = clock + decoder.readDsLen()\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state)\n }\n let index = findIndexSS(structs, clock)\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index]\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n index++ // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++]\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock))\n }\n struct.delete(transaction)\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock)\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n const ds = new UpdateEncoderV2()\n encoding.writeVarUint(ds.restEncoder, 0) // encode 0 structs\n writeDeleteSet(ds, unappliedDS)\n return ds.toUint8Array()\n }\n return null\n}\n\n/**\n * @param {DeleteSet} ds1\n * @param {DeleteSet} ds2\n */\nexport const equalDeleteSets = (ds1, ds2) => {\n if (ds1.clients.size !== ds2.clients.size) return false\n for (const [client, deleteItems1] of ds1.clients.entries()) {\n const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client))\n if (deleteItems2 === undefined || deleteItems1.length !== deleteItems2.length) return false\n for (let i = 0; i < deleteItems1.length; i++) {\n const di1 = deleteItems1[i]\n const di2 = deleteItems2[i]\n if (di1.clock !== di2.clock || di1.len !== di2.len) {\n return false\n }\n }\n }\n return true\n}\n", "/**\n * @module Y\n */\n\nimport {\n StructStore,\n AbstractType,\n YArray,\n YText,\n YMap,\n YXmlElement,\n YXmlFragment,\n transact,\n ContentDoc, Item, Transaction, YEvent // eslint-disable-line\n} from '../internals.js'\n\nimport { ObservableV2 } from 'lib0/observable'\nimport * as random from 'lib0/random'\nimport * as map from 'lib0/map'\nimport * as array from 'lib0/array'\nimport * as promise from 'lib0/promise'\n\nexport const generateNewClientId = random.uint32\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {string | null} [DocOpts.collectionid] Associate this document with a collection. This only plays a role if your provider has a concept of collection.\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n * @property {boolean} [DocOpts.shouldLoad] Whether the document should be synced by the provider now. This is toggled to true when you call ydoc.load()\n */\n\n/**\n * @typedef {Object} DocEvents\n * @property {function(Doc):void} DocEvents.destroy\n * @property {function(Doc):void} DocEvents.load\n * @property {function(boolean, Doc):void} DocEvents.sync\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.update\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.updateV2\n * @property {function(Doc):void} DocEvents.beforeAllTransactions\n * @property {function(Transaction, Doc):void} DocEvents.beforeTransaction\n * @property {function(Transaction, Doc):void} DocEvents.beforeObserverCalls\n * @property {function(Transaction, Doc):void} DocEvents.afterTransaction\n * @property {function(Transaction, Doc):void} DocEvents.afterTransactionCleanup\n * @property {function(Doc, Array):void} DocEvents.afterAllTransactions\n * @property {function({ loaded: Set, added: Set, removed: Set }, Doc, Transaction):void} DocEvents.subdocs\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends ObservableV2\n */\nexport class Doc extends ObservableV2 {\n /**\n * @param {DocOpts} opts configuration\n */\n constructor ({ guid = random.uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {\n super()\n this.gc = gc\n this.gcFilter = gcFilter\n this.clientID = generateNewClientId()\n this.guid = guid\n this.collectionid = collectionid\n /**\n * @type {Map>>}\n */\n this.share = new Map()\n this.store = new StructStore()\n /**\n * @type {Transaction | null}\n */\n this._transaction = null\n /**\n * @type {Array}\n */\n this._transactionCleanups = []\n /**\n * @type {Set}\n */\n this.subdocs = new Set()\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null\n this.shouldLoad = shouldLoad\n this.autoLoad = autoLoad\n this.meta = meta\n /**\n * This is set to true when the persistence provider loaded the document from the database or when the `sync` event fires.\n * Note that not all providers implement this feature. Provider authors are encouraged to fire the `load` event when the doc content is loaded from the database.\n *\n * @type {boolean}\n */\n this.isLoaded = false\n /**\n * This is set to true when the connection provider has successfully synced with a backend.\n * Note that when using peer-to-peer providers this event may not provide very useful.\n * Also note that not all providers implement this feature. Provider authors are encouraged to fire\n * the `sync` event when the doc has been synced (with `true` as a parameter) or if connection is\n * lost (with false as a parameter).\n */\n this.isSynced = false\n this.isDestroyed = false\n /**\n * Promise that resolves once the document has been loaded from a presistence provider.\n */\n this.whenLoaded = promise.create(resolve => {\n this.on('load', () => {\n this.isLoaded = true\n resolve(this)\n })\n })\n const provideSyncedPromise = () => promise.create(resolve => {\n /**\n * @param {boolean} isSynced\n */\n const eventHandler = (isSynced) => {\n if (isSynced === undefined || isSynced === true) {\n this.off('sync', eventHandler)\n resolve()\n }\n }\n this.on('sync', eventHandler)\n })\n this.on('sync', isSynced => {\n if (isSynced === false && this.isSynced) {\n this.whenSynced = provideSyncedPromise()\n }\n this.isSynced = isSynced === undefined || isSynced === true\n if (this.isSynced && !this.isLoaded) {\n this.emit('load', [this])\n }\n })\n /**\n * Promise that resolves once the document has been synced with a backend.\n * This promise is recreated when the connection is lost.\n * Note the documentation about the `isSynced` property.\n */\n this.whenSynced = provideSyncedPromise()\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this)\n }, null, true)\n }\n this.shouldLoad = true\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @template T\n * @param {function(Transaction):T} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n * @return T\n *\n * @public\n */\n transact (f, origin = null) {\n return transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`\n *\n * After this method is called, the type is also available on `ydoc.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Y.Doc instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @template {typeof AbstractType} Type\n * @example\n * const ydoc = new Y.Doc(..)\n * const appState = {\n * document: ydoc.getText('document')\n * comments: ydoc.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {InstanceType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = /** @type {any} */ (AbstractType)) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor()\n t._integrate(this, null)\n return t\n })\n const Constr = type.constructor\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor()\n t._map = type._map\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t\n }\n })\n t._start = type._start\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t\n }\n t._length = type._length\n this.share.set(name, t)\n t._integrate(this, null)\n return /** @type {InstanceType} */ (t)\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return /** @type {InstanceType} */ (type)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n return /** @type {YArray} */ (this.get(name, YArray))\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n return this.get(name, YText)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n return /** @type {YMap} */ (this.get(name, YMap))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlElement}\n *\n * @public\n */\n getXmlElement (name = '') {\n return /** @type {YXmlElement<{[key:string]:string}>} */ (this.get(name, YXmlElement))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n * Doesn't log types that have not been defined (using ydoc.getType(..)).\n *\n * @deprecated Do not use this method and rather call toJSON directly on the shared types.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {}\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON()\n })\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n this.isDestroyed = true\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy())\n const item = this._item\n if (item !== null) {\n this._item = null\n const content = /** @type {ContentDoc} */ (item.content)\n content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false })\n content.doc._item = item\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n const doc = content.doc\n if (!item.deleted) {\n transaction.subdocsAdded.add(doc)\n }\n transaction.subdocsRemoved.add(this)\n }, null, true)\n }\n // @ts-ignore\n this.emit('destroyed', [true]) // DEPRECATED!\n this.emit('destroy', [this])\n super.destroy()\n }\n}\n", "import * as buffer from 'lib0/buffer'\nimport * as decoding from 'lib0/decoding'\nimport {\n ID, createID\n} from '../internals.js'\n\nexport class DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nexport class UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nexport class DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n /**\n * @private\n */\n this.dsCurrVal = 0\n this.restDecoder = decoder\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder)\n return this.dsCurrVal\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1\n this.dsCurrVal += diff\n return diff\n }\n}\n\nexport class UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder)\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = []\n decoding.readVarUint(decoder) // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder))\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8)\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder))\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read()\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read()\n this.keys.push(key)\n return key\n }\n }\n}\n", "import * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nimport {\n ID // eslint-disable-line\n} from '../internals.js'\n\nexport class DSEncoderV1 {\n constructor () {\n this.restEncoder = encoding.createEncoder()\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n}\n\nexport class UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client)\n encoding.writeVarUint(this.restEncoder, id.clock)\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed))\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key)\n }\n}\n\nexport class DSEncoderV2 {\n constructor () {\n this.restEncoder = encoding.createEncoder() // encodes all the rest / non-optimized\n this.dsCurrVal = 0\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal\n this.dsCurrVal = clock\n encoding.writeVarUint(this.restEncoder, diff)\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase()\n }\n encoding.writeVarUint(this.restEncoder, len - 1)\n this.dsCurrVal += len\n }\n}\n\nexport class UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super()\n /**\n * @type {Map}\n */\n this.keyMap = new Map()\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.clientEncoder = new encoding.UintOptRleEncoder()\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder()\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.stringEncoder = new encoding.StringEncoder()\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8)\n this.typeRefEncoder = new encoding.UintOptRleEncoder()\n this.lenEncoder = new encoding.UintOptRleEncoder()\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, 0) // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder))\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder))\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array())\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array())\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder))\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client)\n this.leftClockEncoder.write(id.clock)\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client)\n this.rightClockEncoder.write(id.clock)\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info)\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s)\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0)\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len)\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any)\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed)\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key)\n if (clock === undefined) {\n /**\n * @todo uncomment to introduce this feature finally\n *\n * Background. The ContentFormat object was always encoded using writeKey, but the decoder used to use readString.\n * Furthermore, I forgot to set the keyclock. So everything was working fine.\n *\n * However, this feature here is basically useless as it is not being used (it actually only consumes extra memory).\n *\n * I don't know yet how to reintroduce this feature..\n *\n * Older clients won't be able to read updates when we reintroduce this feature. So this should probably be done using a flag.\n *\n */\n // this.keyMap.set(key, this.keyClock)\n this.keyClockEncoder.write(this.keyClock++)\n this.stringEncoder.write(key)\n } else {\n this.keyClockEncoder.write(clock)\n }\n }\n}\n", "/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\nimport {\n findIndexSS,\n getState,\n createID,\n getStateVector,\n readAndApplyDeleteSet,\n writeDeleteSet,\n createDeleteSetFromStructStore,\n transact,\n readItemContent,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n DSEncoderV2,\n DSDecoderV1,\n DSEncoderV1,\n mergeUpdates,\n mergeUpdatesV2,\n Skip,\n diffUpdateV2,\n convertUpdateFormatV2ToV1,\n DSDecoderV2, Doc, Transaction, GC, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as binary from 'lib0/binary'\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as array from 'lib0/array'\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n clock = math.max(clock, structs[0].id.clock) // make sure the first id exists\n const startNewStructs = findIndexSS(structs, clock)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs)\n encoder.writeClient(client)\n encoding.writeVarUint(encoder.restEncoder, clock)\n const firstStruct = structs[startNewStructs]\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock)\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0)\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nexport const writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map()\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock)\n }\n })\n getStateVector(store).forEach((_clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0)\n }\n })\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size)\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n writeStructs(encoder, /** @type {Array} */ (store.clients.get(client)), client, clock)\n })\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder The decoder object to read data from.\n * @param {Doc} doc\n * @return {Map }>}\n *\n * @private\n * @function\n */\nexport const readClientsStructRefs = (decoder, doc) => {\n /**\n * @type {Map }>}\n */\n const clientRefs = map.create()\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n // const start = performance.now()\n clientRefs.set(client, { i: 0, refs })\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n switch (binary.BITS5 & info) {\n case 0: { // GC\n const len = decoder.readLen()\n refs[i] = new GC(createID(client, clock), len)\n clock += len\n break\n }\n case 10: { // Skip Struct (nothing to apply)\n // @todo we could reduce the amount of checks by adding Skip struct to clientRefs so we know that something is missing.\n const len = decoding.readVarUint(decoder.restDecoder)\n refs[i] = new Skip(createID(client, clock), len)\n clock += len\n break\n }\n default: { // Item with content\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // left\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct\n clock += struct.length\n }\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n}\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {Map} clientsStructRefs\n * @return { null | { update: Uint8Array, missing: Map } }\n *\n * @private\n * @function\n */\nconst integrateStructs = (transaction, store, clientsStructRefs) => {\n /**\n * @type {Array}\n */\n const stack = []\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n let clientsStructRefsIds = array.from(clientsStructRefs.keys()).sort((a, b) => a - b)\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n const getNextStructTarget = () => {\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop()\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]))\n } else {\n return null\n }\n }\n return nextStructsTarget\n }\n let curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n return null\n }\n\n /**\n * @type {StructStore}\n */\n const restStructs = new StructStore()\n const missingSV = new Map()\n /**\n * @param {number} client\n * @param {number} clock\n */\n const updateMissingSv = (client, clock) => {\n const mclock = missingSV.get(client)\n if (mclock == null || mclock > clock) {\n missingSV.set(client, clock)\n }\n }\n /**\n * @type {GC|Item}\n */\n let stackHead = /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]\n // caching the state because it is used very often\n const state = new Map()\n\n const addStackToRestSS = () => {\n for (const item of stack) {\n const client = item.id.client\n const unapplicableItems = clientsStructRefs.get(client)\n if (unapplicableItems) {\n // decrement because we weren't able to apply previous operation\n unapplicableItems.i--\n restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i))\n clientsStructRefs.delete(client)\n unapplicableItems.i = 0\n unapplicableItems.refs = []\n } else {\n // item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue\n restStructs.clients.set(client, [item])\n }\n // remove client from clientsStructRefsIds to prevent users from applying the same update again\n clientsStructRefsIds = clientsStructRefsIds.filter(c => c !== client)\n }\n stack.length = 0\n }\n\n // iterate over all struct readers until we are done\n while (true) {\n if (stackHead.constructor !== Skip) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client))\n const offset = localClock - stackHead.id.clock\n if (offset < 0) {\n // update from the same client is missing\n stack.push(stackHead)\n updateMissingSv(stackHead.id.client, stackHead.id.clock - 1)\n // hid a dead wall, add all items from stack to restSS\n addStackToRestSS()\n } else {\n const missing = stackHead.getMissing(transaction, store)\n if (missing !== null) {\n stack.push(stackHead)\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(/** @type {number} */ (missing)) || { refs: [], i: 0 }\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message that doesn't exist yet\n updateMissingSv(/** @type {number} */ (missing), getState(store, missing))\n addStackToRestSS()\n } else {\n stackHead = structRefs.refs[structRefs.i++]\n continue\n }\n } else if (offset === 0 || offset < stackHead.length) {\n // all fine, apply the stackhead\n stackHead.integrate(transaction, offset)\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length)\n }\n }\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop())\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n } else {\n curStructsTarget = getNextStructTarget()\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++])\n }\n }\n }\n if (restStructs.clients.size > 0) {\n const encoder = new UpdateEncoderV2()\n writeClientsStructs(encoder, restStructs, new Map())\n // write empty deleteset\n // writeDeleteSet(encoder, new DeleteSet())\n encoding.writeVarUint(encoder.restEncoder, 0) // => no need for an extra function call, just write 0 deletes\n return { missing: missingSV, update: encoder.toUint8Array() }\n }\n return null\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {UpdateDecoderV1 | UpdateDecoderV2} [structDecoder]\n *\n * @function\n */\nexport const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n // force that transaction.local is set to non-local\n transaction.local = false\n let retry = false\n const doc = transaction.doc\n const store = doc.store\n // let start = performance.now()\n const ss = readClientsStructRefs(structDecoder, doc)\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const restStructs = integrateStructs(transaction, store, ss)\n const pending = store.pendingStructs\n if (pending) {\n // check if we can apply something\n for (const [client, clock] of pending.missing) {\n if (clock < getState(store, client)) {\n retry = true\n break\n }\n }\n if (restStructs) {\n // merge restStructs into store.pending\n for (const [client, clock] of restStructs.missing) {\n const mclock = pending.missing.get(client)\n if (mclock == null || mclock > clock) {\n pending.missing.set(client, clock)\n }\n }\n pending.update = mergeUpdatesV2([pending.update, restStructs.update])\n }\n } else {\n store.pendingStructs = restStructs\n }\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store)\n if (store.pendingDs) {\n // @todo we could make a lower-bound state-vector check as we do above\n const pendingDSUpdate = new UpdateDecoderV2(decoding.createDecoder(store.pendingDs))\n decoding.readVarUint(pendingDSUpdate.restDecoder) // read 0 structs, because we only encode deletes in pendingdsupdate\n const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store)\n if (dsRest && dsRest2) {\n // case 1: ds1 != null && ds2 != null\n store.pendingDs = mergeUpdatesV2([dsRest, dsRest2])\n } else {\n // case 2: ds1 != null\n // case 3: ds2 != null\n // case 4: ds1 == null && ds2 == null\n store.pendingDs = dsRest || dsRest2\n }\n } else {\n // Either dsRest == null && pendingDs == null OR dsRest != null\n store.pendingDs = dsRest\n }\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n if (retry) {\n const update = /** @type {{update: Uint8Array}} */ (store.pendingStructs).update\n store.pendingStructs = null\n applyUpdateV2(transaction.doc, update)\n }\n }, transactionOrigin, false)\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder))\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nexport const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update)\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder))\n}\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nexport const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1)\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nexport const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector)\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store))\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {UpdateEncoderV1 | UpdateEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {\n const targetStateVector = decodeStateVector(encodedTargetStateVector)\n writeStateAsUpdate(encoder, doc, targetStateVector)\n const updates = [encoder.toUint8Array()]\n // also add the pending updates (if there are any)\n if (doc.store.pendingDs) {\n updates.push(doc.store.pendingDs)\n }\n if (doc.store.pendingStructs) {\n updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector))\n }\n if (updates.length > 1) {\n if (encoder.constructor === UpdateEncoderV1) {\n return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)))\n } else if (encoder.constructor === UpdateEncoderV2) {\n return mergeUpdatesV2(updates)\n }\n }\n return updates[0]\n}\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new UpdateEncoderV1())\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder)\n const clock = decoding.readVarUint(decoder.restDecoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\n// export const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nexport const decodeStateVector = decodedState => readStateVector(new DSDecoderV1(decoding.createDecoder(decodedState)))\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Map} sv\n * @function\n */\nexport const writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size)\n array.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n encoding.writeVarUint(encoder.restEncoder, client) // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock)\n })\n return encoder\n}\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Doc} doc\n *\n * @function\n */\nexport const writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store))\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n if (doc instanceof Map) {\n writeStateVector(encoder, doc)\n } else {\n writeDocumentStateVector(encoder, doc)\n }\n return encoder.toUint8Array()\n}\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @return {Uint8Array}\n *\n * @function\n */\nexport const encodeStateVector = doc => encodeStateVectorV2(doc, new DSEncoderV1())\n", "import * as f from 'lib0/function'\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nexport class EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = []\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nexport const createEventHandler = () => new EventHandler()\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nexport const addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f)\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nexport const removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l\n const len = l.length\n eventHandler.l = l.filter(g => f !== g)\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.')\n }\n}\n\n/**\n * Removes all event listeners.\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n *\n * @private\n * @function\n */\nexport const removeAllEventHandlerListeners = eventHandler => {\n eventHandler.l.length = 0\n}\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nexport const callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1])\n", "import { AbstractType } from '../internals.js' // eslint-disable-line\n\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as error from 'lib0/error'\n\nexport class ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nexport const createID = (client, clock) => new ID(client, clock)\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nexport const writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client)\n encoding.writeVarUint(encoder, id.clock)\n}\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nexport const readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nexport const findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n}\n", "import { AbstractType, Item } from '../internals.js' // eslint-disable-line\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nexport const isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item\n }\n return false\n}\n", "import {\n AbstractType // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nexport const logType = type => {\n const res = []\n let n = type._start\n while (n) {\n res.push(n)\n n = n.right\n }\n console.log('Children: ', res)\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content))\n}\n", "import {\n YArray,\n YMap,\n readDeleteSet,\n writeDeleteSet,\n createDeleteSet,\n DSEncoderV1, DSDecoderV1, ID, DeleteSet, YArrayEvent, Transaction, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as decoding from 'lib0/decoding'\n\nimport { mergeDeleteSets, isDeleted } from './DeleteSet.js'\n\nexport class PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map()\n this.yusers = storeType\n this.doc = doc\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map()\n this.dss = dss\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds')\n const ids = user.get('ids')\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription)\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]))\n }\n })\n })\n })\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))))\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n )\n ids.forEach(addClientId)\n }\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n )\n })\n // add intial data\n storeType.forEach(initUser)\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} conf\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers\n let user = users.get(userDescription)\n if (!user) {\n user = new YMap()\n user.set('ids', new YArray())\n user.set('ds', new YArray())\n users.set(userDescription, user)\n }\n user.get('ids').push([clientid])\n users.observe(_event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription)\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid])\n }\n })\n const encoder = new DSEncoderV1()\n const ds = this.dss.get(userDescription)\n if (ds) {\n writeDeleteSet(encoder, ds)\n user.get('ds').push([encoder.toUint8Array()])\n }\n }\n }, 0)\n })\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds')\n const ds = transaction.deleteSet\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1()\n writeDeleteSet(encoder, ds)\n yds.push([encoder.toUint8Array()])\n }\n })\n })\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n", "import {\n writeID,\n readID,\n compareIDs,\n getState,\n findRootTypeKey,\n Item,\n createID,\n ContentType,\n followRedone,\n getItem,\n ID, Doc, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as error from 'lib0/error'\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nexport class RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n * @param {number} assoc\n */\n constructor (type, tname, item, assoc = 0) {\n /**\n * @type {ID|null}\n */\n this.type = type\n /**\n * @type {string|null}\n */\n this.tname = tname\n /**\n * @type {ID | null}\n */\n this.item = item\n /**\n * A relative position is associated to a specific character. By default\n * assoc >= 0, the relative position is associated to the character\n * after the meant position.\n * I.e. position 1 in 'ab' is associated to character 'b'.\n *\n * If assoc < 0, then the relative position is associated to the caharacter\n * before the meant position.\n *\n * @type {number}\n */\n this.assoc = assoc\n }\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {any}\n */\nexport const relativePositionToJSON = rpos => {\n const json = {}\n if (rpos.type) {\n json.type = rpos.type\n }\n if (rpos.tname) {\n json.tname = rpos.tname\n }\n if (rpos.item) {\n json.item = rpos.item\n }\n if (rpos.assoc != null) {\n json.assoc = rpos.assoc\n }\n return json\n}\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc)\n\nexport class AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n */\n constructor (type, index, assoc = 0) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n /**\n * @type {number}\n */\n this.index = index\n this.assoc = assoc\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc)\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n * @param {number} [assoc]\n *\n * @function\n */\nexport const createRelativePosition = (type, item, assoc) => {\n let typeid = null\n let tname = null\n if (type._item === null) {\n tname = findRootTypeKey(type)\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock)\n }\n return new RelativePosition(typeid, tname, item, assoc)\n}\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @param {number} [assoc]\n * @return {RelativePosition}\n *\n * @function\n */\nexport const createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {\n let t = type._start\n if (assoc < 0) {\n // associated to the left character or the beginning of a type, increment index if possible.\n if (index === 0) {\n return createRelativePosition(type, null, assoc)\n }\n index--\n }\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc)\n }\n index -= t.length\n }\n if (t.right === null && assoc < 0) {\n // left-associated position, return last available id\n return createRelativePosition(type, t.lastId, assoc)\n }\n t = t.right\n }\n return createRelativePosition(type, null, assoc)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nexport const writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item, assoc } = rpos\n if (item !== null) {\n encoding.writeVarUint(encoder, 0)\n writeID(encoder, item)\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1)\n encoding.writeVarString(encoder, tname)\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2)\n writeID(encoder, type)\n } else {\n throw error.unexpectedCase()\n }\n encoding.writeVarInt(encoder, assoc)\n return encoder\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nexport const encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder()\n writeRelativePosition(encoder, rpos)\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition}\n *\n * @function\n */\nexport const readRelativePosition = decoder => {\n let type = null\n let tname = null\n let itemID = null\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder)\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder)\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder)\n }\n }\n const assoc = decoding.hasContent(decoder) ? decoding.readVarInt(decoder) : 0\n return new RelativePosition(type, tname, itemID, assoc)\n}\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition}\n */\nexport const decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array))\n\n/**\n * Transform a relative position to an absolute position.\n *\n * If you want to share the relative position with other users, you should set\n * `followUndoneDeletions` to false to get consistent results across all clients.\n *\n * When calculating the absolute position, we try to follow the \"undone deletions\". This yields\n * better results for the user who performed undo. However, only the user who performed the undo\n * will get the better results, the other users don't know which operations recreated a deleted\n * range of content. There is more information in this ticket: https://github.com/yjs/yjs/issues/638\n *\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @param {boolean} followUndoneDeletions - whether to follow undone deletions - see https://github.com/yjs/yjs/issues/638\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nexport const createAbsolutePositionFromRelativePosition = (rpos, doc, followUndoneDeletions = true) => {\n const store = doc.store\n const rightID = rpos.item\n const typeID = rpos.type\n const tname = rpos.tname\n const assoc = rpos.assoc\n let type = null\n let index = 0\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followUndoneDeletions ? followRedone(store, rightID) : { item: getItem(store, rightID), diff: 0 }\n const right = res.item\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent)\n if (type._item === null || !type._item.deleted) {\n index = (right.deleted || !right.countable) ? 0 : (res.diff + (assoc >= 0 ? 0 : 1)) // adjust position based on left association if necessary\n let n = right.left\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length\n }\n n = n.left\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname)\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) }\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n if (assoc >= 0) {\n index = type._length\n } else {\n index = 0\n }\n }\n return createAbsolutePosition(type, index, rpos.assoc)\n}\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n * @return {boolean}\n *\n * @function\n */\nexport const compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc\n)\n", "import {\n isDeleted,\n createDeleteSetFromStructStore,\n getStateVector,\n getItemCleanStart,\n iterateDeletedStructs,\n writeDeleteSet,\n writeStateVector,\n readDeleteSet,\n readStateVector,\n createDeleteSet,\n createID,\n getState,\n findIndexSS,\n UpdateEncoderV2,\n applyUpdateV2,\n LazyStructReader,\n equalDeleteSets,\n UpdateDecoderV1, UpdateDecoderV2, DSEncoderV1, DSEncoderV2, DSDecoderV1, DSDecoderV2, Transaction, Doc, DeleteSet, Item, // eslint-disable-line\n mergeDeleteSets\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as set from 'lib0/set'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\n\nexport class Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nexport const equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients\n const ds2 = snap2.ds.clients\n const sv1 = snap1.sv\n const sv2 = snap2.sv\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || []\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i]\n const dsitem2 = dsitems2[i]\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n */\nexport const encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds)\n writeStateVector(encoder, snapshot.sv)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nexport const encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DSEncoderV1())\n\n/**\n * @param {Uint8Array} buf\n * @param {DSDecoderV1 | DSDecoderV2} [decoder]\n * @return {Snapshot}\n */\nexport const decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nexport const decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)))\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nexport const createSnapshot = (ds, sm) => new Snapshot(ds, sm)\n\nexport const emptySnapshot = createSnapshot(createDeleteSet(), new Map())\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nexport const snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store))\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nexport const isVisible = (item, snapshot) => snapshot === undefined\n ? !item.deleted\n : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id)\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nexport const splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create)\n const store = transaction.doc.store\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n })\n iterateDeletedStructs(transaction, snapshot.ds, _item => {})\n meta.add(snapshot)\n }\n}\n\n/**\n * @example\n * const ydoc = new Y.Doc({ gc: false })\n * ydoc.getText().insert(0, 'world!')\n * const snapshot = Y.snapshot(ydoc)\n * ydoc.getText().insert(0, 'hello ')\n * const restored = Y.createDocFromSnapshot(ydoc, snapshot)\n * assert(restored.getText().toString() === 'world!')\n *\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nexport const createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('Garbage-collection must be disabled in `originDoc`!')\n }\n const { sv, ds } = snapshot\n\n const encoder = new UpdateEncoderV2()\n originDoc.transact(transaction => {\n let size = 0\n sv.forEach(clock => {\n if (clock > 0) {\n size++\n }\n })\n encoding.writeVarUint(encoder.restEncoder, size)\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock))\n }\n const structs = originDoc.store.clients.get(client) || []\n const lastStructIndex = findIndexSS(structs, clock - 1)\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1)\n encoder.writeClient(client)\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0)\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0)\n }\n }\n writeDeleteSet(encoder, ds)\n })\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot')\n return newDoc\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n */\nexport const snapshotContainsUpdateV2 = (snapshot, update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n if ((snapshot.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) {\n return false\n }\n }\n const mergedDS = mergeDeleteSets([snapshot.ds, readDeleteSet(updateDecoder)])\n return equalDeleteSets(snapshot.ds, mergedDS)\n}\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n */\nexport const snapshotContainsUpdate = (snapshot, update) => snapshotContainsUpdateV2(snapshot, update, UpdateDecoderV1)\n", "import {\n GC,\n splitItem,\n Transaction, ID, Item, DSDecoderV2 // eslint-disable-line\n} from '../internals.js'\n\nimport * as math from 'lib0/math'\nimport * as error from 'lib0/error'\n\nexport class StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map()\n /**\n * @type {null | { missing: Map, update: Uint8Array }}\n */\n this.pendingStructs = null\n /**\n * @type {null | Uint8Array}\n */\n this.pendingDs = null\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nexport const getStateVector = store => {\n const sm = new Map()\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1]\n sm.set(client, struct.id.clock + struct.length)\n })\n return sm\n}\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nexport const getState = (store, client) => {\n const structs = store.clients.get(client)\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1]\n return lastStruct.id.clock + lastStruct.length\n}\n\n/**\n * @param {StructStore} store\n *\n * @private\n * @function\n */\nexport const integretyCheck = store => {\n store.clients.forEach(structs => {\n for (let i = 1; i < structs.length; i++) {\n const l = structs[i - 1]\n const r = structs[i]\n if (l.id.clock + l.length !== r.id.clock) {\n throw new Error('StructStore failed integrety check')\n }\n }\n })\n}\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nexport const addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client)\n if (structs === undefined) {\n structs = []\n store.clients.set(struct.id.client, structs)\n } else {\n const lastStruct = structs[structs.length - 1]\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct)\n}\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nexport const findIndexSS = (structs, clock) => {\n let left = 0\n let right = structs.length - 1\n let mid = structs[right]\n let midclock = mid.id.clock\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right) // pivoting the search\n while (left <= right) {\n mid = structs[midindex]\n midclock = mid.id.clock\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1\n } else {\n right = midindex - 1\n }\n midindex = math.floor((left + right) / 2)\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nexport const find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n return structs[findIndexSS(structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nexport const getItem = /** @type {function(StructStore,ID):Item} */ (find)\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nexport const findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock)\n const struct = structs[index]\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock))\n return index + 1\n }\n return index\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client))\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n}\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nexport const getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client)\n const index = findIndexSS(structs, id.clock)\n const struct = structs[index]\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1))\n }\n return struct\n}\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nexport const replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client))\n structs[findIndexSS(structs, struct.id.clock)] = newStruct\n}\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nexport const iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len\n let index = findIndexCleanStart(transaction, structs, clockStart)\n let struct\n do {\n struct = structs[index++]\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd)\n }\n f(struct)\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n}\n", "import {\n getState,\n writeStructsFromTransaction,\n writeDeleteSet,\n DeleteSet,\n sortAndMergeDeleteSet,\n getStateVector,\n findIndexSS,\n callEventHandlerListeners,\n Item,\n generateNewClientId,\n createID,\n cleanupYTextAfterTransaction,\n UpdateEncoderV1, UpdateEncoderV2, GC, StructStore, AbstractType, AbstractStruct, YEvent, Doc // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as set from 'lib0/set'\nimport * as logging from 'lib0/logging'\nimport { callAll } from 'lib0/function'\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const ydoc = new Y.Doc()\n * const map = ydoc.getMap('map')\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * ydoc.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nexport class Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet()\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store)\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map()\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map>,Set>}\n */\n this.changed = new Map()\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map>,Array>>}\n */\n this.changedParentTypes = new Map()\n /**\n * @type {Array}\n */\n this._mergeStructs = []\n /**\n * @type {any}\n */\n this.origin = origin\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map()\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set()\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set()\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set()\n /**\n * @type {boolean}\n */\n this._needFormattingCleanup = false\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nexport const writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet)\n writeStructsFromTransaction(encoder, transaction)\n writeDeleteSet(encoder, transaction.deleteSet)\n return true\n}\n\n/**\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nexport const nextID = transaction => {\n const y = transaction.doc\n return createID(y.clientID, getState(y.store, y.clientID))\n}\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType>} type\n * @param {string|null} parentSub\n */\nexport const addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub)\n }\n}\n\n/**\n * @param {Array} structs\n * @param {number} pos\n * @return {number} # of merged structs\n */\nconst tryToMergeWithLefts = (structs, pos) => {\n let right = structs[pos]\n let left = structs[pos - 1]\n let i = pos\n for (; i > 0; right = left, left = structs[--i - 1]) {\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left))\n }\n continue\n }\n }\n break\n }\n const merged = pos - i\n if (merged) {\n // remove all merged structs from the array\n structs.splice(pos + 1 - merged, merged)\n }\n return merged\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n const endDeleteItemClock = deleteItem.clock + deleteItem.len\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si]\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false)\n }\n }\n }\n }\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiency and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client))\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di]\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1))\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[si]\n ) {\n si -= 1 + tryToMergeWithLefts(structs, si)\n }\n }\n })\n}\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nexport const tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter)\n tryMergeDeleteSet(ds, store)\n}\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i]\n const doc = transaction.doc\n const store = doc.store\n const ds = transaction.deleteSet\n const mergeStructs = transaction._mergeStructs\n try {\n sortAndMergeDeleteSet(ds)\n transaction.afterState = getStateVector(transaction.doc.store)\n doc.emit('beforeObserverCalls', [transaction, doc])\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = []\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs)\n }\n })\n )\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n )\n events\n .forEach(event => {\n event.currentTarget = type\n // path is relative to the current target\n event._path = null\n })\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length)\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction)\n }\n })\n })\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]))\n callAll(fs, [])\n if (transaction._needFormattingCleanup) {\n cleanupYTextAfterTransaction(transaction)\n }\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter)\n }\n tryMergeDeleteSet(ds, store)\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client))\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1)\n for (let i = structs.length - 1; i >= firstChangePos;) {\n i -= 1 + tryToMergeWithLefts(structs, i)\n }\n }\n })\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = mergeStructs.length - 1; i >= 0; i--) {\n const { client, clock } = mergeStructs[i].id\n const structs = /** @type {Array} */ (store.clients.get(client))\n const replacedStructPos = findIndexSS(structs, clock)\n if (replacedStructPos + 1 < structs.length) {\n if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {\n continue // no need to perform next check, both are already merged\n }\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLefts(structs, replacedStructPos)\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.')\n doc.clientID = generateNewClientId()\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc])\n if (doc._observers.has('update')) {\n const encoder = new UpdateEncoderV1()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2()\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction)\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc, transaction])\n }\n }\n const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction\n if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {\n subdocsAdded.forEach(subdoc => {\n subdoc.clientID = doc.clientID\n if (subdoc.collectionid == null) {\n subdoc.collectionid = doc.collectionid\n }\n doc.subdocs.add(subdoc)\n })\n subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc))\n doc.emit('subdocs', [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction])\n subdocsRemoved.forEach(subdoc => subdoc.destroy())\n }\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = []\n doc.emit('afterAllTransactions', [doc, transactionCleanups])\n } else {\n cleanupTransactions(transactionCleanups, i + 1)\n }\n }\n }\n}\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @template T\n * @param {Doc} doc\n * @param {function(Transaction):T} f\n * @param {any} [origin=true]\n * @return {T}\n *\n * @function\n */\nexport const transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups\n let initialCall = false\n /**\n * @type {any}\n */\n let result = null\n if (doc._transaction === null) {\n initialCall = true\n doc._transaction = new Transaction(doc, origin, local)\n transactionCleanups.push(doc._transaction)\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc])\n }\n doc.emit('beforeTransaction', [doc._transaction, doc])\n }\n try {\n result = f(doc._transaction)\n } finally {\n if (initialCall) {\n const finishCleanup = doc._transaction === transactionCleanups[0]\n doc._transaction = null\n if (finishCleanup) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0)\n }\n }\n }\n return result\n}\n", "import {\n mergeDeleteSets,\n iterateDeletedStructs,\n keepItem,\n transact,\n createID,\n redoItem,\n isParentOf,\n followRedone,\n getItemCleanStart,\n isDeleted,\n addToDeleteSet,\n YEvent, Transaction, Doc, Item, GC, DeleteSet, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as time from 'lib0/time'\nimport * as array from 'lib0/array'\nimport * as logging from 'lib0/logging'\nimport { ObservableV2 } from 'lib0/observable'\n\nexport class StackItem {\n /**\n * @param {DeleteSet} deletions\n * @param {DeleteSet} insertions\n */\n constructor (deletions, insertions) {\n this.insertions = insertions\n this.deletions = deletions\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map()\n }\n}\n/**\n * @param {Transaction} tr\n * @param {UndoManager} um\n * @param {StackItem} stackItem\n */\nconst clearUndoManagerStackItem = (tr, um, stackItem) => {\n iterateDeletedStructs(tr, stackItem.deletions, item => {\n if (item instanceof Item && um.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false)\n }\n })\n}\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {'undo'|'redo'} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Keep a reference to the transaction so we can fire the event with the changedParentTypes\n * @type {any}\n */\n let _tr = null\n const doc = undoManager.doc\n const scope = undoManager.scope\n transact(doc, transaction => {\n while (stack.length > 0 && undoManager.currStackItem === null) {\n const store = doc.store\n const stackItem = /** @type {StackItem} */ (stack.pop())\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set()\n /**\n * @type {Array}\n */\n const itemsToDelete = []\n let performedChange = false\n iterateDeletedStructs(transaction, stackItem.insertions, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id)\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff))\n }\n struct = item\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct)\n }\n }\n })\n iterateDeletedStructs(transaction, stackItem.deletions, struct => {\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.\n !isDeleted(stackItem.insertions, struct.id)\n ) {\n itemsToRedo.add(struct)\n }\n })\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange\n })\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i]\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction)\n performedChange = true\n }\n }\n undoManager.currStackItem = performedChange ? stackItem : null\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0\n }\n })\n _tr = transaction\n }, undoManager)\n const res = undoManager.currStackItem\n if (res != null) {\n const changedParentTypes = _tr.changedParentTypes\n undoManager.emit('stack-item-popped', [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager])\n undoManager.currStackItem = null\n }\n return res\n}\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Transaction):boolean} [UndoManagerOptions.captureTransaction] Do not capture changes of a Transaction if result false.\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter what an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n * @property {boolean} [ignoreRemoteMapChanges] Experimental. By default, the UndoManager will never overwrite remote changes. Enable this property to enable overwriting remote changes on key-value changes (Y.Map, properties on Y.Xml, etc..).\n * @property {Doc} [doc] The document that this UndoManager operates on. Only needed if typeScope is empty.\n */\n\n/**\n * @typedef {Object} StackItemEvent\n * @property {StackItem} StackItemEvent.stackItem\n * @property {any} StackItemEvent.origin\n * @property {'undo'|'redo'} StackItemEvent.type\n * @property {Map>,Array>>} StackItemEvent.changedParentTypes\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {ObservableV2<{'stack-item-added':function(StackItemEvent, UndoManager):void, 'stack-item-popped': function(StackItemEvent, UndoManager):void, 'stack-cleared': function({ undoStackCleared: boolean, redoStackCleared: boolean }):void, 'stack-item-updated': function(StackItemEvent, UndoManager):void }>}\n */\nexport class UndoManager extends ObservableV2 {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, {\n captureTimeout = 500,\n captureTransaction = _tr => true,\n deleteFilter = () => true,\n trackedOrigins = new Set([null]),\n ignoreRemoteMapChanges = false,\n doc = /** @type {Doc} */ (array.isArray(typeScope) ? typeScope[0].doc : typeScope.doc)\n } = {}) {\n super()\n /**\n * @type {Array>}\n */\n this.scope = []\n this.doc = doc\n this.addToScope(typeScope)\n this.deleteFilter = deleteFilter\n trackedOrigins.add(this)\n this.trackedOrigins = trackedOrigins\n this.captureTransaction = captureTransaction\n /**\n * @type {Array}\n */\n this.undoStack = []\n /**\n * @type {Array}\n */\n this.redoStack = []\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false\n this.redoing = false\n /**\n * The currently popped stack item if UndoManager.undoing or UndoManager.redoing\n *\n * @type {StackItem|null}\n */\n this.currStackItem = null\n this.lastChange = 0\n this.ignoreRemoteMapChanges = ignoreRemoteMapChanges\n this.captureTimeout = captureTimeout\n /**\n * @param {Transaction} transaction\n */\n this.afterTransactionHandler = transaction => {\n // Only track certain transactions\n if (\n !this.captureTransaction(transaction) ||\n !this.scope.some(type => transaction.changedParentTypes.has(type)) ||\n (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))\n ) {\n return\n }\n const undoing = this.undoing\n const redoing = this.redoing\n const stack = undoing ? this.redoStack : this.undoStack\n if (undoing) {\n this.stopCapturing() // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.clear(false, true)\n }\n const insertions = new DeleteSet()\n transaction.afterState.forEach((endClock, client) => {\n const startClock = transaction.beforeState.get(client) || 0\n const len = endClock - startClock\n if (len > 0) {\n addToDeleteSet(insertions, client, startClock, len)\n }\n })\n const now = time.getUnixTime()\n let didAdd = false\n if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1]\n lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet])\n lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions])\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, insertions))\n didAdd = true\n }\n if (!undoing && !redoing) {\n this.lastChange = now\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true)\n }\n })\n /**\n * @type {[StackItemEvent, UndoManager]}\n */\n const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this]\n if (didAdd) {\n this.emit('stack-item-added', changeEvent)\n } else {\n this.emit('stack-item-updated', changeEvent)\n }\n }\n this.doc.on('afterTransaction', this.afterTransactionHandler)\n this.doc.on('destroy', () => {\n this.destroy()\n })\n }\n\n /**\n * @param {Array> | AbstractType} ytypes\n */\n addToScope (ytypes) {\n ytypes = array.isArray(ytypes) ? ytypes : [ytypes]\n ytypes.forEach(ytype => {\n if (this.scope.every(yt => yt !== ytype)) {\n if (ytype.doc !== this.doc) logging.warn('[yjs#509] Not same Y.Doc') // use MultiDocUndoManager instead. also see https://github.com/yjs/yjs/issues/509\n this.scope.push(ytype)\n }\n })\n }\n\n /**\n * @param {any} origin\n */\n addTrackedOrigin (origin) {\n this.trackedOrigins.add(origin)\n }\n\n /**\n * @param {any} origin\n */\n removeTrackedOrigin (origin) {\n this.trackedOrigins.delete(origin)\n }\n\n clear (clearUndoStack = true, clearRedoStack = true) {\n if ((clearUndoStack && this.canUndo()) || (clearRedoStack && this.canRedo())) {\n this.doc.transact(tr => {\n if (clearUndoStack) {\n this.undoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.undoStack = []\n }\n if (clearRedoStack) {\n this.redoStack.forEach(item => clearUndoManagerStackItem(tr, this, item))\n this.redoStack = []\n }\n this.emit('stack-cleared', [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }])\n })\n }\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true\n let res\n try {\n res = popStackItem(this, this.undoStack, 'undo')\n } finally {\n this.undoing = false\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true\n let res\n try {\n res = popStackItem(this, this.redoStack, 'redo')\n } finally {\n this.redoing = false\n }\n return res\n }\n\n /**\n * Are undo steps available?\n *\n * @return {boolean} `true` if undo is possible\n */\n canUndo () {\n return this.undoStack.length > 0\n }\n\n /**\n * Are redo steps available?\n *\n * @return {boolean} `true` if redo is possible\n */\n canRedo () {\n return this.redoStack.length > 0\n }\n\n destroy () {\n this.trackedOrigins.delete(this)\n this.doc.off('afterTransaction', this.afterTransactionHandler)\n super.destroy()\n }\n}\n", "import * as binary from 'lib0/binary'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as error from 'lib0/error'\nimport * as f from 'lib0/function'\nimport * as logging from 'lib0/logging'\nimport * as map from 'lib0/map'\nimport * as math from 'lib0/math'\nimport * as string from 'lib0/string'\n\nimport {\n ContentAny,\n ContentBinary,\n ContentDeleted,\n ContentDoc,\n ContentEmbed,\n ContentFormat,\n ContentJSON,\n ContentString,\n ContentType,\n createID,\n decodeStateVector,\n DSEncoderV1,\n DSEncoderV2,\n GC,\n Item,\n mergeDeleteSets,\n readDeleteSet,\n readItemContent,\n Skip,\n UpdateDecoderV1,\n UpdateDecoderV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n writeDeleteSet,\n YXmlElement,\n YXmlHook\n} from '../internals.js'\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n */\nfunction * lazyStructReaderGenerator (decoder) {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder)\n const client = decoder.readClient()\n let clock = decoding.readVarUint(decoder.restDecoder)\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo()\n // @todo use switch instead of ifs\n if (info === 10) {\n const len = decoding.readVarUint(decoder.restDecoder)\n yield new Skip(createID(client, clock), len)\n clock += len\n } else if ((binary.BITS5 & info) !== 0) {\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n // @ts-ignore Force writing a string here.\n cantCopyParentInfo ? (decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n yield struct\n clock += struct.length\n } else {\n const len = decoder.readLen()\n yield new GC(createID(client, clock), len)\n clock += len\n }\n }\n }\n}\n\nexport class LazyStructReader {\n /**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {boolean} filterSkips\n */\n constructor (decoder, filterSkips) {\n this.gen = lazyStructReaderGenerator(decoder)\n /**\n * @type {null | Item | Skip | GC}\n */\n this.curr = null\n this.done = false\n this.filterSkips = filterSkips\n this.next()\n }\n\n /**\n * @return {Item | GC | Skip |null}\n */\n next () {\n // ignore \"Skip\" structs\n do {\n this.curr = this.gen.next().value || null\n } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip)\n return this.curr\n }\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const logUpdate = update => logUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n logging.print('Structs: ', structs)\n const ds = readDeleteSet(updateDecoder)\n logging.print('DeleteSet: ', ds)\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nexport const decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nexport const decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = []\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr)\n }\n return {\n structs,\n ds: readDeleteSet(updateDecoder)\n }\n}\n\nexport class LazyStructWriter {\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n constructor (encoder) {\n this.currClient = 0\n this.startClock = 0\n this.written = 0\n this.encoder = encoder\n /**\n * We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client.\n *\n * This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder.\n *\n * We fragment the restEncoder and store a slice of it per-client until we know how many clients there are.\n * When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information.\n *\n * @type {Array<{ written: number, restEncoder: Uint8Array }>}\n */\n this.clientStructs = []\n }\n}\n\n/**\n * @param {Array} updates\n * @return {Uint8Array}\n */\nexport const mergeUpdates = updates => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof DSEncoderV1 | typeof DSEncoderV2} YEncoder\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {\n const encoder = new YEncoder()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let size = 0\n let currClient = curr.id.client\n let stopCounting = curr.id.clock !== 0 // must start at 0\n let currClock = stopCounting ? 0 : curr.id.clock + curr.length\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n if (currClock !== 0) {\n size++\n // We found a new client\n // write what we have to the encoder\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n currClient = curr.id.client\n currClock = 0\n stopCounting = curr.id.clock !== 0\n }\n // we ignore skips\n if (curr.constructor === Skip) {\n stopCounting = true\n }\n if (!stopCounting) {\n currClock = curr.id.clock + curr.length\n }\n }\n // write what we have\n if (currClock !== 0) {\n size++\n encoding.writeVarUint(encoder.restEncoder, currClient)\n encoding.writeVarUint(encoder.restEncoder, currClock)\n }\n // prepend the size of the state vector\n const enc = encoding.createEncoder()\n encoding.writeVarUint(enc, size)\n encoding.writeBinaryEncoder(enc, encoder.restEncoder)\n encoder.restEncoder = enc\n return encoder.toUint8Array()\n } else {\n encoding.writeVarUint(encoder.restEncoder, 0)\n return encoder.toUint8Array()\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {Uint8Array}\n */\nexport const encodeStateVectorFromUpdate = update => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {{ from: Map, to: Map }}\n */\nexport const parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {\n /**\n * @type {Map}\n */\n const from = new Map()\n /**\n * @type {Map}\n */\n const to = new Map()\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false)\n let curr = updateDecoder.curr\n if (curr !== null) {\n let currClient = curr.id.client\n let currClock = curr.id.clock\n // write the beginning to `from`\n from.set(currClient, currClock)\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n // We found a new client\n // write the end to `to`\n to.set(currClient, currClock)\n // write the beginning to `from`\n from.set(curr.id.client, curr.id.clock)\n // update currClient\n currClient = curr.id.client\n }\n currClock = curr.id.clock + curr.length\n }\n // write the end to `to`\n to.set(currClient, currClock)\n }\n return { from, to }\n}\n\n/**\n * @param {Uint8Array} update\n * @return {{ from: Map, to: Map }}\n */\nexport const parseUpdateMeta = update => parseUpdateMetaV2(update, UpdateDecoderV1)\n\n/**\n * This method is intended to slice any kind of struct and retrieve the right part.\n * It does not handle side-effects, so it should only be used by the lazy-encoder.\n *\n * @param {Item | GC | Skip} left\n * @param {number} diff\n * @return {Item | GC}\n */\nconst sliceStruct = (left, diff) => {\n if (left.constructor === GC) {\n const { client, clock } = left.id\n return new GC(createID(client, clock + diff), left.length - diff)\n } else if (left.constructor === Skip) {\n const { client, clock } = left.id\n return new Skip(createID(client, clock + diff), left.length - diff)\n } else {\n const leftItem = /** @type {Item} */ (left)\n const { client, clock } = leftItem.id\n return new Item(\n createID(client, clock + diff),\n null,\n createID(client, clock + diff - 1),\n null,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n }\n}\n\n/**\n *\n * This function works similarly to `readUpdateV2`.\n *\n * @param {Array} updates\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n * @return {Uint8Array}\n */\nexport const mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n if (updates.length === 1) {\n return updates[0]\n }\n const updateDecoders = updates.map(update => new YDecoder(decoding.createDecoder(update)))\n let lazyStructDecoders = updateDecoders.map(decoder => new LazyStructReader(decoder, true))\n\n /**\n * @todo we don't need offset because we always slice before\n * @type {null | { struct: Item | GC | Skip, offset: number }}\n */\n let currWrite = null\n\n const updateEncoder = new YEncoder()\n // write structs lazily\n const lazyStructEncoder = new LazyStructWriter(updateEncoder)\n\n // Note: We need to ensure that all lazyStructDecoders are fully consumed\n // Note: Should merge document updates whenever possible - even from different updates\n // Note: Should handle that some operations cannot be applied yet ()\n\n while (true) {\n // Write higher clients first ⇒ sort by clientID & clock and remove decoders without content\n lazyStructDecoders = lazyStructDecoders.filter(dec => dec.curr !== null)\n lazyStructDecoders.sort(\n /** @type {function(any,any):number} */ (dec1, dec2) => {\n if (dec1.curr.id.client === dec2.curr.id.client) {\n const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock\n if (clockDiff === 0) {\n // @todo remove references to skip since the structDecoders must filter Skips.\n return dec1.curr.constructor === dec2.curr.constructor\n ? 0\n : dec1.curr.constructor === Skip ? 1 : -1 // we are filtering skips anyway.\n } else {\n return clockDiff\n }\n } else {\n return dec2.curr.id.client - dec1.curr.id.client\n }\n }\n )\n if (lazyStructDecoders.length === 0) {\n break\n }\n const currDecoder = lazyStructDecoders[0]\n // write from currDecoder until the next operation is from another client or if filler-struct\n // then we need to reorder the decoders and find the next operation to write\n const firstClient = /** @type {Item | GC} */ (currDecoder.curr).id.client\n\n if (currWrite !== null) {\n let curr = /** @type {Item | GC | null} */ (currDecoder.curr)\n let iterated = false\n\n // iterate until we find something that we haven't written already\n // remember: first the high client-ids are written\n while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {\n curr = currDecoder.next()\n iterated = true\n }\n if (\n curr === null || // current decoder is empty\n curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`\n (iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) // the above while loop was used and we are potentially missing updates\n ) {\n continue\n }\n\n if (firstClient !== currWrite.struct.id.client) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n } else {\n if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {\n // @todo write currStruct & set currStruct = Skip(clock = currStruct.id.clock + currStruct.length, length = curr.id.clock - self.clock)\n if (currWrite.struct.constructor === Skip) {\n // extend existing skip\n currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock\n } else {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length\n /**\n * @type {Skip}\n */\n const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff)\n currWrite = { struct, offset: 0 }\n }\n } else { // if (currWrite.struct.id.clock + currWrite.struct.length >= curr.id.clock) {\n const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock\n if (diff > 0) {\n if (currWrite.struct.constructor === Skip) {\n // prefer to slice Skip because the other struct might contain more information\n currWrite.struct.length -= diff\n } else {\n curr = sliceStruct(curr, diff)\n }\n }\n if (!currWrite.struct.mergeWith(/** @type {any} */ (curr))) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: curr, offset: 0 }\n currDecoder.next()\n }\n }\n }\n } else {\n currWrite = { struct: /** @type {Item | GC} */ (currDecoder.curr), offset: 0 }\n currDecoder.next()\n }\n for (\n let next = currDecoder.curr;\n next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip;\n next = currDecoder.next()\n ) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = { struct: next, offset: 0 }\n }\n }\n if (currWrite !== null) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset)\n currWrite = null\n }\n finishLazyStructWriting(lazyStructEncoder)\n\n const dss = updateDecoders.map(decoder => readDeleteSet(decoder))\n const ds = mergeDeleteSets(dss)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n */\nexport const diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n const state = decodeStateVector(sv)\n const encoder = new YEncoder()\n const lazyStructWriter = new LazyStructWriter(encoder)\n const decoder = new YDecoder(decoding.createDecoder(update))\n const reader = new LazyStructReader(decoder, false)\n while (reader.curr) {\n const curr = reader.curr\n const currClient = curr.id.client\n const svClock = state.get(currClient) || 0\n if (reader.curr.constructor === Skip) {\n // the first written struct shouldn't be a skip\n reader.next()\n continue\n }\n if (curr.id.clock + curr.length > svClock) {\n writeStructToLazyStructWriter(lazyStructWriter, curr, math.max(svClock - curr.id.clock, 0))\n reader.next()\n while (reader.curr && reader.curr.id.client === currClient) {\n writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0)\n reader.next()\n }\n } else {\n // read until something new comes up\n while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {\n reader.next()\n }\n }\n }\n finishLazyStructWriting(lazyStructWriter)\n // write ds\n const ds = readDeleteSet(decoder)\n writeDeleteSet(encoder, ds)\n return encoder.toUint8Array()\n}\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n */\nexport const diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {LazyStructWriter} lazyWriter\n */\nconst flushLazyStructWriter = lazyWriter => {\n if (lazyWriter.written > 0) {\n lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: encoding.toUint8Array(lazyWriter.encoder.restEncoder) })\n lazyWriter.encoder.restEncoder = encoding.createEncoder()\n lazyWriter.written = 0\n }\n}\n\n/**\n * @param {LazyStructWriter} lazyWriter\n * @param {Item | GC} struct\n * @param {number} offset\n */\nconst writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {\n // flush curr if we start another client\n if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {\n flushLazyStructWriter(lazyWriter)\n }\n if (lazyWriter.written === 0) {\n lazyWriter.currClient = struct.id.client\n // write next client\n lazyWriter.encoder.writeClient(struct.id.client)\n // write startClock\n encoding.writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset)\n }\n struct.write(lazyWriter.encoder, offset)\n lazyWriter.written++\n}\n/**\n * Call this function when we collected all parts and want to\n * put all the parts together. After calling this method,\n * you can continue using the UpdateEncoder.\n *\n * @param {LazyStructWriter} lazyWriter\n */\nconst finishLazyStructWriting = (lazyWriter) => {\n flushLazyStructWriter(lazyWriter)\n\n // this is a fresh encoder because we called flushCurr\n const restEncoder = lazyWriter.encoder.restEncoder\n\n /**\n * Now we put all the fragments together.\n * This works similarly to `writeClientsStructs`\n */\n\n // write # states that were updated - i.e. the clients\n encoding.writeVarUint(restEncoder, lazyWriter.clientStructs.length)\n\n for (let i = 0; i < lazyWriter.clientStructs.length; i++) {\n const partStructs = lazyWriter.clientStructs[i]\n /**\n * Works similarly to `writeStructs`\n */\n // write # encoded structs\n encoding.writeVarUint(restEncoder, partStructs.written)\n // write the rest of the fragment\n encoding.writeUint8Array(restEncoder, partStructs.restEncoder)\n }\n}\n\n/**\n * @param {Uint8Array} update\n * @param {function(Item|GC|Skip):Item|GC|Skip} blockTransformer\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} YDecoder\n * @param {typeof UpdateEncoderV2 | typeof UpdateEncoderV1 } YEncoder\n */\nexport const convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {\n const updateDecoder = new YDecoder(decoding.createDecoder(update))\n const lazyDecoder = new LazyStructReader(updateDecoder, false)\n const updateEncoder = new YEncoder()\n const lazyWriter = new LazyStructWriter(updateEncoder)\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0)\n }\n finishLazyStructWriting(lazyWriter)\n const ds = readDeleteSet(updateDecoder)\n writeDeleteSet(updateEncoder, ds)\n return updateEncoder.toUint8Array()\n}\n\n/**\n * @typedef {Object} ObfuscatorOptions\n * @property {boolean} [ObfuscatorOptions.formatting=true]\n * @property {boolean} [ObfuscatorOptions.subdocs=true]\n * @property {boolean} [ObfuscatorOptions.yxml=true] Whether to obfuscate nodeName / hookName\n */\n\n/**\n * @param {ObfuscatorOptions} obfuscator\n */\nconst createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => {\n let i = 0\n const mapKeyCache = map.create()\n const nodeNameCache = map.create()\n const formattingKeyCache = map.create()\n const formattingValueCache = map.create()\n formattingValueCache.set(null, null) // end of a formatting range should always be the end of a formatting range\n /**\n * @param {Item|GC|Skip} block\n * @return {Item|GC|Skip}\n */\n return block => {\n switch (block.constructor) {\n case GC:\n case Skip:\n return block\n case Item: {\n const item = /** @type {Item} */ (block)\n const content = item.content\n switch (content.constructor) {\n case ContentDeleted:\n break\n case ContentType: {\n if (yxml) {\n const type = /** @type {ContentType} */ (content).type\n if (type instanceof YXmlElement) {\n type.nodeName = map.setIfUndefined(nodeNameCache, type.nodeName, () => 'node-' + i)\n }\n if (type instanceof YXmlHook) {\n type.hookName = map.setIfUndefined(nodeNameCache, type.hookName, () => 'hook-' + i)\n }\n }\n break\n }\n case ContentAny: {\n const c = /** @type {ContentAny} */ (content)\n c.arr = c.arr.map(() => i)\n break\n }\n case ContentBinary: {\n const c = /** @type {ContentBinary} */ (content)\n c.content = new Uint8Array([i])\n break\n }\n case ContentDoc: {\n const c = /** @type {ContentDoc} */ (content)\n if (subdocs) {\n c.opts = {}\n c.doc.guid = i + ''\n }\n break\n }\n case ContentEmbed: {\n const c = /** @type {ContentEmbed} */ (content)\n c.embed = {}\n break\n }\n case ContentFormat: {\n const c = /** @type {ContentFormat} */ (content)\n if (formatting) {\n c.key = map.setIfUndefined(formattingKeyCache, c.key, () => i + '')\n c.value = map.setIfUndefined(formattingValueCache, c.value, () => ({ i }))\n }\n break\n }\n case ContentJSON: {\n const c = /** @type {ContentJSON} */ (content)\n c.arr = c.arr.map(() => i)\n break\n }\n case ContentString: {\n const c = /** @type {ContentString} */ (content)\n c.str = string.repeat((i % 10) + '', c.str.length)\n break\n }\n default:\n // unknown content type\n error.unexpectedCase()\n }\n if (item.parentSub) {\n item.parentSub = map.setIfUndefined(mapKeyCache, item.parentSub, () => i + '')\n }\n i++\n return block\n }\n default:\n // unknown block-type\n error.unexpectedCase()\n }\n }\n}\n\n/**\n * This function obfuscates the content of a Yjs update. This is useful to share\n * buggy Yjs documents while significantly limiting the possibility that a\n * developer can on the user. Note that it might still be possible to deduce\n * some information by analyzing the \"structure\" of the document or by analyzing\n * the typing behavior using the CRDT-related metadata that is still kept fully\n * intact.\n *\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nexport const obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1)\n\n/**\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nexport const obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2)\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV1ToV2 = update => convertUpdateFormat(update, f.id, UpdateDecoderV1, UpdateEncoderV2)\n\n/**\n * @param {Uint8Array} update\n */\nexport const convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, f.id, UpdateDecoderV2, UpdateEncoderV1)\n", "import {\n isDeleted,\n Item, AbstractType, Transaction, AbstractStruct // eslint-disable-line\n} from '../internals.js'\n\nimport * as set from 'lib0/set'\nimport * as array from 'lib0/array'\nimport * as error from 'lib0/error'\n\nconst errorComputeChanges = 'You must not compute changes after the event-handler fired.'\n\n/**\n * @template {AbstractType} T\n * YEvent describes the changes on a YType.\n */\nexport class YEvent {\n /**\n * @param {T} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {T}\n */\n this.target = target\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction\n /**\n * @type {Object|null}\n */\n this._changes = null\n /**\n * @type {null | Map}\n */\n this._keys = null\n /**\n * @type {null | Array<{ insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object }>}\n */\n this._delta = null\n /**\n * @type {Array|null}\n */\n this._path = null\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n return this._path || (this._path = getPathTo(this.currentTarget, this.target))\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * @type {Map}\n */\n get keys () {\n if (this._keys === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const keys = new Map()\n const target = this.target\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key))\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action\n let oldValue\n if (this.adds(item)) {\n let prev = item.left\n while (prev !== null && this.adds(prev)) {\n prev = prev.left\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete'\n oldValue = array.last(prev.content.getContent())\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update'\n oldValue = array.last(prev.content.getContent())\n } else {\n action = 'add'\n oldValue = undefined\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete'\n oldValue = array.last(/** @type {Item} */ item.content.getContent())\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue })\n }\n })\n this._keys = keys\n }\n return this._keys\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {Array<{insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object}>}\n */\n get delta () {\n return this.changes.delta\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n let changes = this._changes\n if (changes === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const target = this.target\n const added = set.create()\n const deleted = set.create()\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = []\n changes = {\n added,\n deleted,\n delta,\n keys: this.keys\n }\n const changed = /** @type Set */ (this.transaction.changed.get(target))\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp)\n }\n }\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp()\n lastOp = { delete: 0 }\n }\n lastOp.delete += item.length\n deleted.add(item)\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp()\n lastOp = { insert: [] }\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent())\n added.add(item)\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp()\n lastOp = { retain: 0 }\n }\n lastOp.retain += item.length\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp()\n }\n }\n this._changes = changes\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = []\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub)\n } else {\n // parent is array-ish\n let i = 0\n let c = /** @type {AbstractType} */ (child._item.parent)._start\n while (c !== child._item && c !== null) {\n if (!c.deleted && c.countable) {\n i += c.length\n }\n c = c.right\n }\n path.unshift(i)\n }\n child = /** @type {AbstractType} */ (child._item.parent)\n }\n return path\n}\n", "import {\n removeEventHandlerListener,\n callEventHandlerListeners,\n addEventHandlerListener,\n createEventHandler,\n getState,\n isVisible,\n ContentType,\n createID,\n ContentAny,\n ContentBinary,\n getItemCleanStart,\n ContentDoc, YText, YArray, UpdateEncoderV1, UpdateEncoderV2, Doc, Snapshot, Transaction, EventHandler, YEvent, Item, // eslint-disable-line\n} from '../internals.js'\n\nimport * as map from 'lib0/map'\nimport * as iterator from 'lib0/iterator'\nimport * as error from 'lib0/error'\nimport * as math from 'lib0/math'\nimport * as log from 'lib0/logging'\n\n/**\n * https://docs.yjs.dev/getting-started/working-with-shared-types#caveats\n */\nexport const warnPrematureAccess = () => { log.warn('Invalid access: Add Yjs type to a document before reading data.') }\n\nconst maxSearchMarker = 80\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0\n\nexport class ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true\n this.p = p\n this.index = index\n this.timestamp = globalSearchMarkerTimestamp++\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++ }\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false\n marker.p = p\n p.marker = true\n marker.index = index\n marker.timestamp = globalSearchMarkerTimestamp++\n}\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b)\n overwriteMarker(marker, p, index)\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index)\n searchMarker.push(pm)\n return pm\n }\n}\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nexport const findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b)\n let p = yarray._start\n let pindex = 0\n if (marker !== null) {\n p = marker.p\n pindex = marker.index\n refreshMarkerTimestamp(marker) // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length\n }\n p = p.right\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left\n if (!p.deleted && p.countable) {\n pindex -= p.length\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex)\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n}\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nexport const updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i]\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p\n p.marker = false\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1)\n continue\n }\n m.p = p\n p.marker = true\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len)\n }\n }\n}\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nexport const getTypeChildren = t => {\n t.doc ?? warnPrematureAccess()\n let s = t._start\n const arr = []\n while (s) {\n arr.push(s)\n s = s.right\n }\n return arr\n}\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nexport const callTypeObservers = (type, transaction, event) => {\n const changedType = type\n const changedParentTypes = transaction.changedParentTypes\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event)\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent)\n }\n callEventHandlerListeners(changedType._eH, event, transaction)\n}\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nexport class AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null\n /**\n * @type {Map}\n */\n this._map = new Map()\n /**\n * @type {Item|null}\n */\n this._start = null\n /**\n * @type {Doc|null}\n */\n this.doc = null\n this._length = 0\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler()\n /**\n * Deep event handlers\n * @type {EventHandler>,Transaction>}\n */\n this._dEH = createEventHandler()\n /**\n * @type {null | Array}\n */\n this._searchMarker = null\n }\n\n /**\n * @return {AbstractType|null}\n */\n get parent () {\n return this._item ? /** @type {AbstractType} */ (this._item.parent) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y\n this._item = item\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {AbstractType}\n */\n clone () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder\n */\n _write (_encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} _parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, _parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f)\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f)\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f)\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} start\n * @param {number} end\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListSlice = (type, start, end) => {\n type.doc ?? warnPrematureAccess()\n if (start < 0) {\n start = type._length + start\n }\n if (end < 0) {\n end = type._length + end\n }\n let len = end - start\n const cs = []\n let n = type._start\n while (n !== null && len > 0) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n if (c.length <= start) {\n start -= c.length\n } else {\n for (let i = start; i < c.length && len > 0; i++) {\n cs.push(c[i])\n len--\n }\n start = 0\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArray = type => {\n type.doc ?? warnPrematureAccess()\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListToArraySnapshot = (type, snapshot) => {\n const cs = []\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i])\n }\n }\n n = n.right\n }\n return cs\n}\n\n/**\n * Executes a provided function on once on every element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nexport const typeListForEach = (type, f) => {\n let index = 0\n let n = type._start\n type.doc ?? warnPrematureAccess()\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nexport const typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = []\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type))\n })\n return result\n}\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nexport const typeListCreateIterator = type => {\n let n = type._start\n /**\n * @type {Array|null}\n */\n let currentContent = null\n let currentContentIndex = 0\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent()\n currentContentIndex = 0\n n = n.right // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++]\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null\n }\n return {\n done: false,\n value\n }\n }\n }\n}\n\n/**\n * Executes a provided function on once on every element of this YArray.\n * Operates on a snapshotted state of the document.\n *\n * @param {AbstractType} type\n * @param {function(any,number,AbstractType):void} f A function to execute on every element of this YArray.\n * @param {Snapshot} snapshot\n *\n * @private\n * @function\n */\nexport const typeListForEachSnapshot = (type, f, snapshot) => {\n let index = 0\n let n = type._start\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent()\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type)\n }\n }\n n = n.right\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nexport const typeListGet = (type, index) => {\n type.doc ?? warnPrematureAccess()\n const marker = findMarker(type, index)\n let n = type._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length\n }\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const store = doc.store\n const right = referenceItem === null ? parent._start : referenceItem.right\n /**\n * @type {Array|number|null>}\n */\n let jsonContent = []\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent))\n left.integrate(transaction, 0)\n jsonContent = []\n }\n }\n content.forEach(c => {\n if (c === null) {\n jsonContent.push(c)\n } else {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c)\n break\n default:\n packJsonContent()\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))))\n left.integrate(transaction, 0)\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)))\n left.integrate(transaction, 0)\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c))\n left.integrate(transaction, 0)\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n }\n })\n packJsonContent()\n}\n\nconst lengthExceeded = () => error.create('Length exceeded!')\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index > parent._length) {\n throw lengthExceeded()\n }\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n break\n }\n index -= n.length\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length)\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * Pushing content is special as we generally want to push after the last item. So we don't have to update\n * the serach marker.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nexport const typeListPushGenerics = (transaction, parent, content) => {\n // Use the marker with the highest index and iterate to the right.\n const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start })\n let n = marker.p\n if (n) {\n while (n.right) {\n n = n.right\n }\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nexport const typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index\n const startLength = length\n const marker = findMarker(parent, index)\n let n = parent._start\n if (marker !== null) {\n n = marker.p\n index -= marker.index\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index))\n }\n index -= n.length\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length))\n }\n n.delete(transaction)\n length -= n.length\n }\n n = n.right\n }\n if (length > 0) {\n throw lengthExceeded()\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nexport const typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key)\n if (c !== undefined) {\n c.delete(transaction)\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|null|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nexport const typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null\n const doc = transaction.doc\n const ownClientId = doc.clientID\n let content\n if (value == null) {\n content = new ContentAny([value])\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value])\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value))\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value))\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value)\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0)\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGet = (parent, key) => {\n parent.doc ?? warnPrematureAccess()\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent.doc ?? warnPrematureAccess()\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nexport const typeMapHas = (parent, key) => {\n parent.doc ?? warnPrematureAccess()\n const val = parent._map.get(key)\n return val !== undefined && !val.deleted\n}\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nexport const typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n}\n\n/**\n * @param {AbstractType} parent\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nexport const typeMapGetAllSnapshot = (parent, snapshot) => {\n /**\n * @type {Object}\n */\n const res = {}\n parent._map.forEach((value, key) => {\n /**\n * @type {Item|null}\n */\n let v = value\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left\n }\n if (v !== null && isVisible(v, snapshot)) {\n res[key] = v.content.getContent()[v.length - 1]\n }\n })\n return res\n}\n\n/**\n * @param {AbstractType & { _map: Map }} type\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nexport const createMapIterator = type => {\n type.doc ?? warnPrematureAccess()\n return iterator.iteratorFilter(type._map.entries(), /** @param {any} entry */ entry => !entry[1].deleted)\n}\n", "/**\n * @module YArray\n */\n\nimport {\n YEvent,\n AbstractType,\n typeListGet,\n typeListToArray,\n typeListForEach,\n typeListCreateIterator,\n typeListInsertGenerics,\n typeListPushGenerics,\n typeListDelete,\n typeListMap,\n YArrayRefID,\n callTypeObservers,\n transact,\n warnPrematureAccess,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\nimport { typeListSlice } from './AbstractType.js'\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n * @extends YEvent>\n */\nexport class YArrayEvent extends YEvent {}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nexport class YArray extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = []\n /**\n * @type {Array}\n */\n this._searchMarker = []\n }\n\n /**\n * Construct a new YArray containing the specified items.\n * @template {Object|Array|number|null|string|Uint8Array} T\n * @param {Array} items\n * @return {YArray}\n */\n static from (items) {\n /**\n * @type {YArray}\n */\n const a = new YArray()\n a.push(items)\n return a\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n /**\n * @return {YArray}\n */\n _copy () {\n return new YArray()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YArray}\n */\n clone () {\n /**\n * @type {YArray}\n */\n const arr = new YArray()\n arr.insert(0, this.toArray().map(el =>\n el instanceof AbstractType ? /** @type {typeof el} */ (el.clone()) : el\n ))\n return arr\n }\n\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction))\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, /** @type {any} */ (content))\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content)\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n *\n * @todo Use the following implementation in all types.\n */\n push (content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListPushGenerics(transaction, this, /** @type {any} */ (content))\n })\n } else {\n /** @type {Array} */ (this._prelimContent).push(...content)\n }\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length)\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Returns a portion of this YArray into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function once on every element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nexport const readYArray = _decoder => new YArray()\n", "/**\n * @module YMap\n */\n\nimport {\n YEvent,\n AbstractType,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapHas,\n createMapIterator,\n YMapRefID,\n callTypeObservers,\n transact,\n warnPrematureAccess,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as iterator from 'lib0/iterator'\n\n/**\n * @template T\n * @extends YEvent>\n * Event that describes the changes on a YMap.\n */\nexport class YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction)\n this.keysChanged = subs\n }\n}\n\n/**\n * @template MapType\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable<[string, MapType]>}\n */\nexport class YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super()\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null\n\n if (entries === undefined) {\n this._prelimContent = new Map()\n } else {\n this._prelimContent = new Map(entries)\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value)\n })\n this._prelimContent = null\n }\n\n /**\n * @return {YMap}\n */\n _copy () {\n return new YMap()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YMap}\n */\n clone () {\n /**\n * @type {YMap}\n */\n const map = new YMap()\n this.forEach((value, key) => {\n map.set(key, value instanceof AbstractType ? /** @type {typeof value} */ (value.clone()) : value)\n })\n return map\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs))\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n this.doc ?? warnPrematureAccess()\n /**\n * @type {Object}\n */\n const map = {}\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1]\n map[key] = v instanceof AbstractType ? v.toJSON() : v\n }\n })\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this), /** @param {any} v */ v => /** @type {any} */ ([v[0], v[1].content.getContent()[v[1].length - 1]]))\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(MapType,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n this.doc ?? warnPrematureAccess()\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this)\n }\n })\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key)\n })\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key)\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n * @template {MapType} VAL\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {VAL} value The value of the element to add\n * @return {VAL}\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, /** @type {any} */ (value))\n })\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value)\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {MapType|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * Removes all elements from this YMap.\n */\n clear () {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n this.forEach(function (_value, key, map) {\n typeMapDelete(transaction, map, key)\n })\n })\n } else {\n /** @type {Map} */ (this._prelimContent).clear()\n }\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nexport const readYMap = _decoder => new YMap()\n", "/**\n * @module YText\n */\n\nimport {\n YEvent,\n AbstractType,\n getItemCleanStart,\n getState,\n isVisible,\n createID,\n YTextRefID,\n callTypeObservers,\n transact,\n ContentEmbed,\n GC,\n ContentFormat,\n ContentString,\n splitSnapshotAffectedStructs,\n iterateDeletedStructs,\n iterateStructs,\n findMarker,\n typeMapDelete,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n updateMarkerChanges,\n ContentType,\n warnPrematureAccess,\n ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ID, Doc, Item, Snapshot, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as object from 'lib0/object'\nimport * as map from 'lib0/map'\nimport * as error from 'lib0/error'\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b))\n\nexport class ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left\n this.right = right\n this.index = index\n this.currentAttributes = currentAttributes\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase()\n }\n switch (this.right.content.constructor) {\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content))\n }\n break\n default:\n if (!this.right.deleted) {\n this.index += this.right.length\n }\n break\n }\n this.left = this.right\n this.right = this.right.right\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content))\n }\n break\n default:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count))\n }\n pos.index += pos.right.length\n count -= pos.right.length\n }\n break\n }\n pos.left = pos.right\n pos.right = pos.right.right\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {boolean} useSearchMarker\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index, useSearchMarker) => {\n const currentAttributes = new Map()\n const marker = useSearchMarker ? findMarker(parent, index) : null\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes)\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes)\n return findNextPosition(transaction, pos, index)\n }\n}\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key)\n }\n currPos.forward()\n }\n const doc = transaction.doc\n const ownClientId = doc.clientID\n negatedAttributes.forEach((val, key) => {\n const left = currPos.left\n const right = currPos.right\n const nextFormat = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n nextFormat.integrate(transaction, 0)\n currPos.right = nextFormat\n currPos.forward()\n })\n}\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format\n if (value === null) {\n currentAttributes.delete(key)\n } else {\n currentAttributes.set(key, value)\n }\n}\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] ?? null, /** @type {ContentFormat} */ (currPos.right.content).value))) {\n //\n } else {\n break\n }\n currPos.forward()\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n const negatedAttributes = new Map()\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key]\n const currentVal = currPos.currentAttributes.get(key) ?? null\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal)\n const { left, right } = currPos\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n }\n return negatedAttributes\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object|AbstractType} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((_val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null\n }\n })\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : (text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text))\n let { left, right, index } = currPos\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength())\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content)\n right.integrate(transaction, 0)\n currPos.right = right\n currPos.index = index\n currPos.forward()\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc\n const ownClientId = doc.clientID\n minimizeAttributeChanges(currPos, attributes)\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes)\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n // also check the attributes after the first non-format as we do not want to insert redundant negated attributes there\n // eslint-disable-next-line no-labels\n iterationLoop: while (\n currPos.right !== null &&\n (length > 0 ||\n (\n negatedAttributes.size > 0 &&\n (currPos.right.deleted || currPos.right.content.constructor === ContentFormat)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key)\n } else {\n if (length === 0) {\n // no need to further extend negatedAttributes\n // eslint-disable-next-line no-labels\n break iterationLoop\n }\n negatedAttributes.set(key, value)\n }\n currPos.right.delete(transaction)\n } else {\n currPos.currentAttributes.set(key, value)\n }\n break\n }\n default:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n break\n }\n }\n currPos.forward()\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = ''\n for (; length > 0; length--) {\n newlines += '\\n'\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines))\n currPos.right.integrate(transaction, 0)\n currPos.forward()\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes)\n}\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} curr exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} currAttributes\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {\n /**\n * @type {Item|null}\n */\n let end = start\n /**\n * @type {Map}\n */\n const endFormats = map.create()\n while (end && (!end.countable || end.deleted)) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n const cf = /** @type {ContentFormat} */ (end.content)\n endFormats.set(cf.key, cf)\n }\n end = end.right\n }\n let cleanups = 0\n let reachedCurr = false\n while (start !== end) {\n if (curr === start) {\n reachedCurr = true\n }\n if (!start.deleted) {\n const content = start.content\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content)\n const startAttrValue = startAttributes.get(key) ?? null\n if (endFormats.get(key) !== content || startAttrValue === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction)\n cleanups++\n if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {\n if (startAttrValue === null) {\n currAttributes.delete(key)\n } else {\n currAttributes.set(key, startAttrValue)\n }\n }\n }\n if (!reachedCurr && !start.deleted) {\n updateCurrentAttributes(currAttributes, /** @type {ContentFormat} */ (content))\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right)\n }\n return cleanups\n}\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || !item.right.countable)) {\n item = item.right\n }\n const attrs = new Set()\n // iterate back until a content item is found\n while (item && (item.deleted || !item.countable)) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key\n if (attrs.has(key)) {\n item.delete(transaction)\n } else {\n attrs.add(key)\n }\n }\n item = item.left\n }\n}\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nexport const cleanupYTextFormatting = type => {\n let res = 0\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start)\n let end = type._start\n let startAttributes = map.create()\n const currentAttributes = map.copy(startAttributes)\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content))\n break\n default:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes)\n startAttributes = map.copy(currentAttributes)\n start = end\n break\n }\n }\n end = end.right\n }\n })\n return res\n}\n\n/**\n * This will be called by the transction once the event handlers are called to potentially cleanup\n * formatting attributes.\n *\n * @param {Transaction} transaction\n */\nexport const cleanupYTextAfterTransaction = transaction => {\n /**\n * @type {Set}\n */\n const needFullCleanup = new Set()\n // check if another formatting item was inserted\n const doc = transaction.doc\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (\n !item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat && item.constructor !== GC\n ) {\n needFullCleanup.add(/** @type {any} */ (item).parent)\n }\n })\n }\n // cleanup in a new transaction\n transact(doc, (t) => {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || !(/** @type {YText} */ (item.parent)._hasFormatting) || needFullCleanup.has(/** @type {YText} */ (item.parent))) {\n return\n }\n const parent = /** @type {YText} */ (item.parent)\n if (item.content.constructor === ContentFormat) {\n needFullCleanup.add(parent)\n } else {\n // If no formatting attribute was inserted or deleted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n cleanupContextlessFormattingGap(t, item)\n }\n })\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n for (const yText of needFullCleanup) {\n cleanupYTextFormatting(yText)\n }\n })\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length\n const startAttrs = map.copy(currPos.currentAttributes)\n const start = currPos.right\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentType:\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length))\n }\n length -= currPos.right.length\n currPos.right.delete(transaction)\n break\n }\n }\n currPos.forward()\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes)\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent)\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length)\n }\n return currPos\n}\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @extends YEvent\n * Event that describes the changes on a YText type.\n */\nexport class YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed\n */\n constructor (ytext, transaction, subs) {\n super(ytext, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.keysChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.keysChanged.add(sub)\n }\n })\n }\n\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n if (this._changes === null) {\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string|AbstractType|object, delete?:number, retain?:number}>}}\n */\n const changes = {\n keys: this.keys,\n delta: this.delta,\n added: new Set(),\n deleted: new Set()\n }\n this._changes = changes\n }\n return /** @type {any} */ (this._changes)\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc)\n /**\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n */\n const delta = []\n transact(y, transaction => {\n const currentAttributes = new Map() // saves all current attributes for insert\n const oldAttributes = new Map()\n let item = this.target._start\n /**\n * @type {string?}\n */\n let action = null\n /**\n * @type {Object}\n */\n const attributes = {} // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = ''\n let retain = 0\n let deleteLen = 0\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op = null\n switch (action) {\n case 'delete':\n if (deleteLen > 0) {\n op = { delete: deleteLen }\n }\n deleteLen = 0\n break\n case 'insert':\n if (typeof insert === 'object' || insert.length > 0) {\n op = { insert }\n if (currentAttributes.size > 0) {\n op.attributes = {}\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value\n }\n })\n }\n }\n insert = ''\n break\n case 'retain':\n if (retain > 0) {\n op = { retain }\n if (!object.isEmpty(attributes)) {\n op.attributes = object.assign({}, attributes)\n }\n }\n retain = 0\n break\n }\n if (op) delta.push(op)\n action = null\n }\n }\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentType:\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp()\n action = 'insert'\n insert = item.content.getContent()[0]\n addOp()\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += 1\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += 1\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp()\n action = 'insert'\n }\n insert += /** @type {ContentString} */ (item.content).str\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp()\n action = 'delete'\n }\n deleteLen += item.length\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp()\n action = 'retain'\n }\n retain += item.length\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content)\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) ?? null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (equalAttrs(value, (oldAttributes.get(key) ?? null))) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (value !== null) {\n item.delete(transaction)\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value)\n const curVal = currentAttributes.get(key) ?? null\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp()\n }\n attributes[key] = curVal\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value)\n const attr = attributes[key]\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp()\n }\n if (value === null) {\n delete attributes[key]\n } else {\n attributes[key] = value\n }\n } else if (attr !== null) { // this will be cleaned up automatically by the contextless cleanup function\n item.delete(transaction)\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp()\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content))\n }\n break\n }\n }\n item = item.right\n }\n addOp()\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1]\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop()\n } else {\n break\n }\n }\n })\n this._delta = delta\n }\n return /** @type {any} */ (this._delta)\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nexport class YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super()\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : []\n /**\n * @type {Array|null}\n */\n this._searchMarker = []\n /**\n * Whether this YText contains formatting attributes.\n * This flag is updated when a formatting item is integrated (see ContentFormat.integrate)\n */\n this._hasFormatting = false\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n try {\n /** @type {Array} */ (this._pending).forEach(f => f())\n } catch (e) {\n console.error(e)\n }\n this._pending = null\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YText}\n */\n clone () {\n const text = new YText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs)\n const event = new YTextEvent(this, transaction, parentSubs)\n callTypeObservers(this, transaction, event)\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local && this._hasFormatting) {\n transaction._needFormattingCleanup = true\n }\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n this.doc ?? warnPrematureAccess()\n let str = ''\n /**\n * @type {Item|null}\n */\n let n = this._start\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str\n }\n n = n.right\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} opts\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map())\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i]\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {})\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {})\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete)\n }\n }\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta))\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n this.doc ?? warnPrematureAccess()\n /**\n * @type{Array}\n */\n const ops = []\n const currentAttributes = new Map()\n const doc = /** @type {Doc} */ (this.doc)\n let str = ''\n let n = this._start\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {}\n let addAttributes = false\n currentAttributes.forEach((value, key) => {\n addAttributes = true\n attributes[key] = value\n })\n /**\n * @type {Object}\n */\n const op = { insert: str }\n if (addAttributes) {\n op.attributes = attributes\n }\n ops.push(op)\n str = ''\n }\n }\n const computeDelta = () => {\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange')\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'removed') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' })\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'added') {\n packStr()\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' })\n }\n } else if (cur !== undefined) {\n packStr()\n currentAttributes.delete('ychange')\n }\n str += /** @type {ContentString} */ (n.content).str\n break\n }\n case ContentType:\n case ContentEmbed: {\n packStr()\n /**\n * @type {Object}\n */\n const op = {\n insert: n.content.getContent()[0]\n }\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({})\n op.attributes = attrs\n currentAttributes.forEach((value, key) => {\n attrs[key] = value\n })\n }\n ops.push(op)\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr()\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content))\n }\n break\n }\n }\n n = n.right\n }\n packStr()\n }\n if (snapshot || prevSnapshot) {\n // snapshots are merged again after the transaction, so we need to keep the\n // transaction alive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot)\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot)\n }\n computeDelta()\n }, 'cleanup')\n } else {\n computeDelta()\n }\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes)\n if (!attributes) {\n attributes = {}\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v })\n }\n insertText(transaction, this, pos, text, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes))\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object | AbstractType} embed The Object that represents the embed.\n * @param {TextAttributes} [attributes] Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes) {\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes)\n insertText(transaction, this, pos, embed, attributes || {})\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes || {}))\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index, true), length)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length))\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, false)\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes))\n }\n }\n\n /**\n * Removes an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.removeAttribute(attributeName))\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {any} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Array} */ (this._pending).push(() => this.setAttribute(attributeName, attributeValue))\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {any} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes () {\n return typeMapGetAll(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nexport const readYText = _decoder => new YText()\n", "/**\n * @module YXml\n */\n\nimport {\n YXmlEvent,\n YXmlElement,\n AbstractType,\n typeListMap,\n typeListForEach,\n typeListInsertGenerics,\n typeListInsertGenericsAfter,\n typeListDelete,\n typeListToArray,\n YXmlFragmentRefID,\n callTypeObservers,\n transact,\n typeListGet,\n typeListSlice,\n warnPrematureAccess,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, ContentType, Transaction, Item, YXmlText, YXmlHook // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\nimport * as array from 'lib0/array'\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nexport class YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f\n this._root = root\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start)\n this._firstCall = true\n root.doc ?? warnPrematureAccess()\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode\n let type = n && n.content && /** @type {any} */ (n.content).type\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right\n break\n } else if (n.parent === this._root) {\n n = null\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nexport class YXmlFragment extends AbstractType {\n constructor () {\n super()\n /**\n * @type {Array|null}\n */\n this._prelimContent = []\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get firstChild () {\n const first = this._first\n return first ? first.content.getContent()[0] : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n this.insert(0, /** @type {Array} */ (this._prelimContent))\n this._prelimContent = null\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlFragment}\n */\n clone () {\n const el = new YXmlFragment()\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n get length () {\n this.doc ?? warnPrematureAccess()\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase()\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)\n const next = iterator.next()\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase()\n // @ts-ignore\n return array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction))\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment()\n if (binding !== undefined) {\n binding._createAssociation(fragment, this)\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null)\n })\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content)\n }\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at\n * @param {Array} content The array of content\n */\n insertAfter (ref, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const refItem = (ref && ref instanceof AbstractType) ? ref._item : ref\n typeListInsertGenericsAfter(transaction, this, refItem, content)\n })\n } else {\n const pc = /** @type {Array} */ (this._prelimContent)\n const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1\n if (index === 0 && ref !== null) {\n throw error.create('Reference item not found')\n }\n pc.splice(index, 0, ...content)\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length)\n })\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length)\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content)\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content)\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {YXmlElement|YXmlText}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Returns a portion of this YXmlFragment into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Executes a provided function on once on every child element.\n *\n * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f)\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nexport const readYXmlFragment = _decoder => new YXmlFragment()\n", "import * as object from 'lib0/object'\n\nimport {\n YXmlFragment,\n transact,\n typeMapDelete,\n typeMapHas,\n typeMapSet,\n typeMapGet,\n typeMapGetAll,\n typeMapGetAllSnapshot,\n typeListForEach,\n YXmlElementRefID,\n Snapshot, YXmlText, ContentType, AbstractType, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Item // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @typedef {Object|number|null|Array|string|Uint8Array|AbstractType} ValueTypes\n */\n\n/**\n * An YXmlElement imitates the behavior of a\n * https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n *\n * @template {{ [key: string]: ValueTypes }} [KV={ [key: string]: string }]\n */\nexport class YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super()\n this.nodeName = nodeName\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map()\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value)\n })\n this._prelimAttrs = null\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlElement}\n */\n clone () {\n /**\n * @type {YXmlElement}\n */\n const el = new YXmlElement(this.nodeName)\n const attrs = this.getAttributes()\n object.forEach(attrs, (value, key) => {\n if (typeof value === 'string') {\n el.setAttribute(key, value)\n }\n })\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item))\n return el\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes()\n const stringBuilder = []\n const keys = []\n for (const key in attrs) {\n keys.push(key)\n }\n keys.sort()\n const keysLen = keys.length\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i]\n stringBuilder.push(key + '=\"' + attrs[key] + '\"')\n }\n const nodeName = this.nodeName.toLocaleLowerCase()\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {string} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName)\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that is to be set.\n * @param {KV[KEY]} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue)\n })\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue)\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that identifies the\n * queried value.\n * @return {KV[KEY]|undefined} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns whether an attribute exists\n *\n * @param {string} attributeName The attribute name to check for existence.\n * @return {boolean} whether the attribute exists.\n *\n * @public\n */\n hasAttribute (attributeName) {\n return /** @type {any} */ (typeMapHas(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {{ [Key in Extract]?: KV[Key]}} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return /** @type {any} */ (snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this))\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName)\n const attrs = this.getAttributes()\n for (const key in attrs) {\n const value = attrs[key]\n if (typeof value === 'string') {\n dom.setAttribute(key, value)\n }\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding))\n })\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID)\n encoder.writeKey(this.nodeName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nexport const readYXmlElement = decoder => new YXmlElement(decoder.readKey())\n", "import {\n YEvent,\n YXmlText, YXmlElement, YXmlFragment, Transaction // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @extends YEvent\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nexport class YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction)\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set()\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true\n } else {\n this.attributesChanged.add(sub)\n }\n })\n }\n}\n", "import {\n YMap,\n YXmlHookRefID,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2 // eslint-disable-line\n} from '../internals.js'\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nexport class YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super()\n /**\n * @type {string}\n */\n this.hookName = hookName\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlHook}\n */\n clone () {\n const el = new YXmlHook(this.hookName)\n this.forEach((value, key) => {\n el.set(key, value)\n })\n return el\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName]\n let dom\n if (hook !== undefined) {\n dom = hook.createDom(this)\n } else {\n dom = document.createElement(this.hookName)\n }\n dom.setAttribute('data-yjs-hook', this.hookName)\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID)\n encoder.writeKey(this.hookName)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nexport const readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey())\n", "import {\n YText,\n YXmlTextRefID,\n ContentType, YXmlElement, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, // eslint-disable-line\n} from '../internals.js'\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nexport class YXmlText extends YText {\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlText}\n */\n clone () {\n const text = new YXmlText()\n text.applyDelta(this.toDelta())\n return text\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString())\n if (binding !== undefined) {\n binding._createAssociation(dom, this)\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = []\n for (const nodeName in delta.attributes) {\n const attrs = []\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] })\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1)\n nestedNodes.push({ nodeName, attrs })\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1)\n // now convert to dom string\n let str = ''\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i]\n str += `<${node.nodeName}`\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j]\n str += ` ${attr.key}=\"${attr.value}\"`\n }\n str += '>'\n }\n str += delta.insert\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nexport const readYXmlText = decoder => new YXmlText()\n", "import {\n UpdateEncoderV1, UpdateEncoderV2, ID, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id\n this.length = length\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n", "import {\n AbstractStruct,\n addStruct,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\n\nexport const structGCRefNumber = 0\n\n/**\n * @private\n */\nexport class GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.length -= offset\n }\n addStruct(transaction.doc.store, this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber)\n encoder.writeLen(this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\nexport class ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentBinary}\n */\nexport const readContentBinary = decoder => new ContentBinary(decoder.readBuf())\n", "import {\n addToDeleteSet,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nexport class ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset)\n this.len = offset\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len)\n item.markDeleted()\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentDeleted}\n */\nexport const readContentDeleted = decoder => new ContentDeleted(decoder.readLen())\n", "import {\n Doc, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @param {string} guid\n * @param {Object} opts\n */\nconst createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false })\n\n/**\n * @private\n */\nexport class ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.')\n }\n /**\n * @type {Doc}\n */\n this.doc = doc\n /**\n * @type {any}\n */\n const opts = {}\n this.opts = opts\n if (!doc.gc) {\n opts.gc = false\n }\n if (doc.autoLoad) {\n opts.autoLoad = true\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts))\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item\n transaction.subdocsAdded.add(this.doc)\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc)\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc)\n } else {\n transaction.subdocsRemoved.add(this.doc)\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid)\n encoder.writeAny(this.opts)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentDoc}\n */\nexport const readContentDoc = decoder => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()))\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Item, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentEmbed}\n */\nexport const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON())\n", "import {\n YText, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Item, StructStore, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @private\n */\nexport class ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key\n this.value = value\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} _offset\n * @return {ContentFormat}\n */\n splice (_offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} _right\n * @return {boolean}\n */\n mergeWith (_right) {\n return false\n }\n\n /**\n * @param {Transaction} _transaction\n * @param {Item} item\n */\n integrate (_transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n const p = /** @type {YText} */ (item.parent)\n p._searchMarker = null\n p._hasFormatting = true\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key)\n encoder.writeJSON(this.value)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentFormat}\n */\nexport const readContentFormat = decoder => new ContentFormat(decoder.readKey(), decoder.readJSON())\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c))\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentJSON}\n */\nexport const readContentJSON = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n const c = decoder.readString()\n if (c === 'undefined') {\n cs.push(undefined)\n } else {\n cs.push(JSON.parse(c))\n }\n }\n return new ContentJSON(cs)\n}\n", "import {\n UpdateEncoderV1, UpdateEncoderV2, UpdateDecoderV1, UpdateDecoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\nimport * as env from 'lib0/environment'\nimport * as object from 'lib0/object'\n\nconst isDevMode = env.getVariable('node_env') === 'development'\n\nexport class ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr\n isDevMode && object.deepFreeze(arr)\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset))\n this.arr = this.arr.slice(0, offset)\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr)\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length\n encoder.writeLen(len - offset)\n for (let i = offset; i < len; i++) {\n const c = this.arr[i]\n encoder.writeAny(c)\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentAny}\n */\nexport const readContentAny = decoder => {\n const len = decoder.readLen()\n const cs = []\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny())\n }\n return new ContentAny(cs)\n}\n", "import {\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Transaction, Item, StructStore // eslint-disable-line\n} from '../internals.js'\n\n/**\n * @private\n */\nexport class ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset))\n this.str = this.str.slice(0, offset)\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1)\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�'\n // replace right as well\n right.str = '�' + right.str.slice(1)\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset))\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentString}\n */\nexport const readContentString = decoder => new ContentString(decoder.readString())\n", "import {\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText,\n UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, Item, YEvent, AbstractType // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\n\n/**\n * @type {Array>}\n * @private\n */\nexport const typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n]\n\nexport const YArrayRefID = 0\nexport const YMapRefID = 1\nexport const YTextRefID = 2\nexport const YXmlElementRefID = 3\nexport const YXmlFragmentRefID = 4\nexport const YXmlHookRefID = 5\nexport const YXmlTextRefID = 6\n\n/**\n * @private\n */\nexport class ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item)\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction)\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // This will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item)\n }\n item = item.right\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction)\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // same as above\n transaction._mergeStructs.push(item)\n }\n })\n transaction.changed.delete(this.type)\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start\n while (item !== null) {\n item.gc(store, true)\n item = item.right\n }\n this.type._start = null\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true)\n item = item.left\n }\n })\n this.type._map = new Map()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder)\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentType}\n */\nexport const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder))\n", "import {\n GC,\n getState,\n AbstractStruct,\n replaceStruct,\n addStruct,\n addToDeleteSet,\n findRootTypeKey,\n compareIDs,\n getItem,\n getItemCleanEnd,\n getItemCleanStart,\n readContentDeleted,\n readContentBinary,\n readContentJSON,\n readContentAny,\n readContentString,\n readContentEmbed,\n readContentDoc,\n createID,\n readContentFormat,\n readContentType,\n addChangedTypeToTransaction,\n isDeleted,\n StackItem, DeleteSet, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, ContentType, ContentDeleted, StructStore, ID, AbstractType, Transaction // eslint-disable-line\n} from '../internals.js'\n\nimport * as error from 'lib0/error'\nimport * as binary from 'lib0/binary'\nimport * as array from 'lib0/array'\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nexport const followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id\n let diff = 0\n let item\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff)\n }\n item = getItem(store, nextID)\n diff = nextID.clock - item.id.clock\n nextID = item.redone\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n}\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nexport const keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep\n item = /** @type {AbstractType} */ (item.parent)._item\n }\n}\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nexport const splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n if (leftItem.deleted) {\n rightItem.markDeleted()\n }\n if (leftItem.keep) {\n rightItem.keep = true\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff)\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem)\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem)\n }\n leftItem.length = diff\n return rightItem\n}\n\n/**\n * @param {Array} stack\n * @param {ID} id\n */\nconst isDeletedByUndoStack = (stack, id) => array.some(stack, /** @param {StackItem} s */ s => isDeleted(s.deletions, id))\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n * @param {DeleteSet} itemsToDelete\n * @param {boolean} ignoreRemoteMapChanges\n * @param {import('../utils/UndoManager.js').UndoManager} um\n *\n * @return {Item|null}\n *\n * @private\n */\nexport const redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {\n const doc = transaction.doc\n const store = doc.store\n const ownClientID = doc.clientID\n const redone = item.redone\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item\n /**\n * @type {Item|null}\n */\n let left = null\n /**\n * @type {Item|null}\n */\n let right\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true) {\n // try to undo parent if it will be undone anyway\n if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {\n return null\n }\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone)\n }\n }\n const parentType = parentItem === null ? /** @type {AbstractType} */ (item.parent) : /** @type {ContentType} */ (parentItem.content).type\n\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left\n right = item\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone)\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace\n break\n }\n left = left.left\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone)\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace\n break\n }\n right = right.right\n }\n } else {\n right = null\n if (item.right && !ignoreRemoteMapChanges) {\n left = item\n // Iterate right while right is in itemsToDelete\n // If it is intended to delete right while item is redone, we can expect that item should replace right.\n while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) {\n left = left.right\n // follow redone\n while (left.redone) left = getItemCleanStart(transaction, left.redone)\n }\n if (left && left.right !== null) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n } else {\n left = parentType._map.get(item.parentSub) || null\n }\n }\n const nextClock = getState(store, ownClientID)\n const nextId = createID(ownClientID, nextClock)\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentType,\n item.parentSub,\n item.content.copy()\n )\n item.redone = nextId\n keepItem(redoneItem, true)\n redoneItem.integrate(transaction, 0)\n return redoneItem\n}\n\n/**\n * Abstract class that represents any content.\n */\nexport class Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength())\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub\n /**\n * If this type's effect is redone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null\n /**\n * @type {AbstractContent}\n */\n this.content = content\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin)\n this.origin = this.left.lastId\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin)\n this.rightOrigin = this.right.id\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null\n } else if (!this.parent) {\n // only set parent if this shouldn't be garbage collected\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent\n this.parentSub = this.left.parentSub\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent\n this.parentSub = this.right.parentSub\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent)\n if (parentItem.constructor === GC) {\n this.parent = null\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1))\n this.origin = this.left.lastId\n this.content = this.content.splice(offset)\n this.length -= offset\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left\n\n /**\n * @type {Item|null}\n */\n let o\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (o !== null && o.left !== null) {\n o = o.left\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set()\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set()\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o)\n conflictingItems.add(o)\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o\n conflictingItems.clear()\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o\n conflictingItems.clear()\n }\n } else {\n break\n }\n o = o.right\n }\n this.left = left\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right\n this.right = right\n this.left.right = this\n } else {\n let r\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null\n while (r !== null && r.left !== null) {\n r = r.left\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this\n }\n this.right = r\n }\n if (this.right !== null) {\n this.right.left = this\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this)\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction)\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length\n }\n addStruct(transaction.doc.store, this)\n this.content.integrate(transaction, this)\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub)\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction)\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0)\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right\n while (n !== null && n.deleted) {\n n = n.right\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left\n while (n !== null && n.deleted) {\n n = n.left\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n this.constructor === right.constructor &&\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n const searchMarker = /** @type {AbstractType} */ (this.parent)._searchMarker\n if (searchMarker) {\n searchMarker.forEach(marker => {\n if (marker.p === right) {\n // right is going to be \"forgotten\" so we need to update the marker\n marker.p = this\n // adjust marker index\n if (!this.deleted && this.countable) {\n marker.index -= this.length\n }\n }\n })\n }\n if (right.keep) {\n this.keep = true\n }\n this.right = right.right\n if (this.right !== null) {\n this.right.left = this\n }\n this.length += right.length\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent)\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length\n }\n this.markDeleted()\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length)\n addChangedTypeToTransaction(transaction, parent, this.parentSub)\n this.content.delete(transaction)\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store)\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length))\n } else {\n this.content = new ContentDeleted(this.length)\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin\n const rightOrigin = this.rightOrigin\n const parentSub = this.parentSub\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6) // parentSub is non-null\n encoder.writeInfo(info)\n if (origin !== null) {\n encoder.writeLeftID(origin)\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin)\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent)\n if (parent._item !== undefined) {\n const parentItem = parent._item\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent)\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(ykey)\n } else {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parentItem.id)\n }\n } else if (parent.constructor === String) { // this edge case was added by differential updates\n encoder.writeParentInfo(true) // write parentYKey\n encoder.writeString(parent)\n } else if (parent.constructor === ID) {\n encoder.writeParentInfo(false) // write parent id\n encoder.writeLeftID(parent)\n } else {\n error.unexpectedCase()\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub)\n }\n }\n this.content.write(encoder, offset)\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {number} info\n */\nexport const readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder)\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nexport const contentRefs = [\n () => { error.unexpectedCase() }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc, // 9\n () => { error.unexpectedCase() } // 10 - Skip is not ItemContent\n]\n\n/**\n * Do not implement this class!\n */\nexport class AbstractContent {\n /**\n * @return {number}\n */\n getLength () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Should return false if this Item is some kind of meta information\n * (e.g. format information).\n *\n * * Whether this Item should be addressable via `yarray.get(i)`\n * * Whether this Item should be counted when computing yarray.length\n *\n * @return {boolean}\n */\n isCountable () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {AbstractContent}\n */\n copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {number} _offset\n * @return {AbstractContent}\n */\n splice (_offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {AbstractContent} _right\n * @return {boolean}\n */\n mergeWith (_right) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} _transaction\n * @param {Item} _item\n */\n integrate (_transaction, _item) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} _transaction\n */\n delete (_transaction) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {StructStore} _store\n */\n gc (_store) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder\n * @param {number} _offset\n */\n write (_encoder, _offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @return {number}\n */\n getRef () {\n throw error.methodUnimplemented()\n }\n}\n", "import {\n AbstractStruct,\n UpdateEncoderV1, UpdateEncoderV2, StructStore, Transaction, ID // eslint-disable-line\n} from '../internals.js'\nimport * as error from 'lib0/error'\nimport * as encoding from 'lib0/encoding'\n\nexport const structSkipRefNumber = 10\n\n/**\n * @private\n */\nexport class Skip extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {Skip} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n // skip structs cannot be integrated\n error.unexpectedCase()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structSkipRefNumber)\n // write as VarUint because Skips can't make use of predictable length-encoding\n encoding.writeVarUint(encoder.restEncoder, this.length - offset)\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n", "/** eslint-env browser */\n\nexport {\n Doc,\n Transaction,\n YArray as Array,\n YMap as Map,\n YText as Text,\n YXmlText as XmlText,\n YXmlHook as XmlHook,\n YXmlElement as XmlElement,\n YXmlFragment as XmlFragment,\n YXmlEvent,\n YMapEvent,\n YArrayEvent,\n YTextEvent,\n YEvent,\n Item,\n AbstractStruct,\n GC,\n Skip,\n ContentBinary,\n ContentDeleted,\n ContentDoc,\n ContentEmbed,\n ContentFormat,\n ContentJSON,\n ContentAny,\n ContentString,\n ContentType,\n AbstractType,\n getTypeChildren,\n createRelativePositionFromTypeIndex,\n createRelativePositionFromJSON,\n createAbsolutePositionFromRelativePosition,\n compareRelativePositions,\n AbsolutePosition,\n RelativePosition,\n ID,\n createID,\n compareIDs,\n getState,\n Snapshot,\n createSnapshot,\n createDeleteSet,\n createDeleteSetFromStructStore,\n cleanupYTextFormatting,\n snapshot,\n emptySnapshot,\n findRootTypeKey,\n findIndexSS,\n getItem,\n typeListToArraySnapshot,\n typeMapGetSnapshot,\n typeMapGetAllSnapshot,\n createDocFromSnapshot,\n iterateDeletedStructs,\n applyUpdate,\n applyUpdateV2,\n readUpdate,\n readUpdateV2,\n encodeStateAsUpdate,\n encodeStateAsUpdateV2,\n encodeStateVector,\n UndoManager,\n decodeSnapshot,\n encodeSnapshot,\n decodeSnapshotV2,\n encodeSnapshotV2,\n decodeStateVector,\n logUpdate,\n logUpdateV2,\n decodeUpdate,\n decodeUpdateV2,\n relativePositionToJSON,\n isDeleted,\n isParentOf,\n equalSnapshots,\n PermanentUserData, // @TODO experimental\n tryGc,\n transact,\n AbstractConnector,\n logType,\n mergeUpdates,\n mergeUpdatesV2,\n parseUpdateMeta,\n parseUpdateMetaV2,\n encodeStateVectorFromUpdate,\n encodeStateVectorFromUpdateV2,\n encodeRelativePosition,\n decodeRelativePosition,\n diffUpdate,\n diffUpdateV2,\n convertUpdateFormatV1ToV2,\n convertUpdateFormatV2ToV1,\n obfuscateUpdate,\n obfuscateUpdateV2,\n UpdateEncoderV1,\n UpdateEncoderV2,\n UpdateDecoderV1,\n UpdateDecoderV2,\n equalDeleteSets,\n mergeDeleteSets,\n snapshotContainsUpdate\n} from './internals.js'\n\nconst glo = /** @type {any} */ (typeof globalThis !== 'undefined'\n ? globalThis\n : typeof window !== 'undefined'\n ? window\n // @ts-ignore\n : typeof global !== 'undefined' ? global : {})\n\nconst importIdentifier = '__ $YJS$ __'\n\nif (glo[importIdentifier] === true) {\n /**\n * Dear reader of this message. Please take this seriously.\n *\n * If you see this message, make sure that you only import one version of Yjs. In many cases,\n * your package manager installs two versions of Yjs that are used by different packages within your project.\n * Another reason for this message is that some parts of your project use the commonjs version of Yjs\n * and others use the EcmaScript version of Yjs.\n *\n * This often leads to issues that are hard to debug. We often need to perform constructor checks,\n * e.g. `struct instanceof GC`. If you imported different versions of Yjs, it is impossible for us to\n * do the constructor checks anymore - which might break the CRDT algorithm.\n *\n * https://github.com/yjs/yjs/issues/438\n */\n console.error('Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438')\n}\nglo[importIdentifier] = true\n", "/* eslint-env browser */\n\n/**\n * Tiny websocket connection handler.\n *\n * Implements exponential backoff reconnects, ping/pong, and a nice event system using [lib0/observable].\n *\n * @module websocket\n */\n\nimport { Observable } from './observable.js'\nimport * as time from './time.js'\nimport * as math from './math.js'\n\nconst reconnectTimeoutBase = 1200\nconst maxReconnectTimeout = 2500\n// @todo - this should depend on awareness.outdatedTime\nconst messageReconnectTimeout = 30000\n\n/**\n * @param {WebsocketClient} wsclient\n */\nconst setupWS = (wsclient) => {\n if (wsclient.shouldConnect && wsclient.ws === null) {\n const websocket = new WebSocket(wsclient.url)\n const binaryType = wsclient.binaryType\n /**\n * @type {any}\n */\n let pingTimeout = null\n if (binaryType) {\n websocket.binaryType = binaryType\n }\n wsclient.ws = websocket\n wsclient.connecting = true\n wsclient.connected = false\n websocket.onmessage = event => {\n wsclient.lastMessageReceived = time.getUnixTime()\n const data = event.data\n const message = typeof data === 'string' ? JSON.parse(data) : data\n if (message && message.type === 'pong') {\n clearTimeout(pingTimeout)\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n wsclient.emit('message', [message, wsclient])\n }\n /**\n * @param {any} error\n */\n const onclose = error => {\n if (wsclient.ws !== null) {\n wsclient.ws = null\n wsclient.connecting = false\n if (wsclient.connected) {\n wsclient.connected = false\n wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient])\n } else {\n wsclient.unsuccessfulReconnects++\n }\n // Start with no reconnect timeout and increase timeout by\n // log10(wsUnsuccessfulReconnects).\n // The idea is to increase reconnect timeout slowly and have no reconnect\n // timeout at the beginning (log(1) = 0)\n setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient)\n }\n clearTimeout(pingTimeout)\n }\n const sendPing = () => {\n if (wsclient.ws === websocket) {\n wsclient.send({\n type: 'ping'\n })\n }\n }\n websocket.onclose = () => onclose(null)\n websocket.onerror = error => onclose(error)\n websocket.onopen = () => {\n wsclient.lastMessageReceived = time.getUnixTime()\n wsclient.connecting = false\n wsclient.connected = true\n wsclient.unsuccessfulReconnects = 0\n wsclient.emit('connect', [{ type: 'connect' }, wsclient])\n // set ping\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n }\n}\n\n/**\n * @deprecated\n * @extends Observable\n */\nexport class WebsocketClient extends Observable {\n /**\n * @param {string} url\n * @param {object} opts\n * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`\n */\n constructor (url, { binaryType } = {}) {\n super()\n this.url = url\n /**\n * @type {WebSocket?}\n */\n this.ws = null\n this.binaryType = binaryType || null\n this.connected = false\n this.connecting = false\n this.unsuccessfulReconnects = 0\n this.lastMessageReceived = 0\n /**\n * Whether to connect to other peers or not\n * @type {boolean}\n */\n this.shouldConnect = true\n this._checkInterval = setInterval(() => {\n if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) {\n // no message received in a long time - not even your own awareness\n // updates (which are updated every 15 seconds)\n /** @type {WebSocket} */ (this.ws).close()\n }\n }, messageReconnectTimeout / 2)\n setupWS(this)\n }\n\n /**\n * @param {any} message\n */\n send (message) {\n if (this.ws) {\n this.ws.send(JSON.stringify(message))\n }\n }\n\n destroy () {\n clearInterval(this._checkInterval)\n this.disconnect()\n super.destroy()\n }\n\n disconnect () {\n this.shouldConnect = false\n if (this.ws !== null) {\n this.ws.close()\n }\n }\n\n connect () {\n this.shouldConnect = true\n if (!this.connected && this.ws === null) {\n setupWS(this)\n }\n }\n}\n", "/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n", "/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n", "(function(e){if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();else if(\"function\"==typeof define&&define.amd)define([],e);else{var t;t=\"undefined\"==typeof window?\"undefined\"==typeof global?\"undefined\"==typeof self?this:self:global:window,t.SimplePeer=e()}})(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function(){function d(s,e,n){function t(o,i){if(!e[o]){if(!s[o]){var l=\"function\"==typeof require&&require;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error(\"Cannot find module '\"+o+\"'\");throw c.code=\"MODULE_NOT_FOUND\",c}var a=e[o]={exports:{}};s[o][0].call(a.exports,function(e){var r=s[o][1][e];return t(r||e)},a,a.exports,d,s,e,n)}return e[o].exports}for(var r=\"function\"==typeof require&&require,a=0;a>16,l[c++]=255&t>>8,l[c++]=255&t;return 2===s&&(t=u[e.charCodeAt(n)]<<2|u[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===s&&(t=u[e.charCodeAt(n)]<<10|u[e.charCodeAt(n+1)]<<4|u[e.charCodeAt(n+2)]>>2,l[c++]=255&t>>8,l[c++]=255&t),l}function d(e){return c[63&e>>18]+c[63&e>>12]+c[63&e>>6]+c[63&e]}function s(e,t,n){for(var r,a=[],o=t;ol?l:d+o));return 1===r?(t=e[n-1],a.push(c[t>>2]+c[63&t<<4]+\"==\")):2===r&&(t=(e[n-2]<<8)+e[n-1],a.push(c[t>>10]+c[63&t>>4]+c[63&t<<2]+\"=\")),a.join(\"\")}n.byteLength=function(e){var t=r(e),n=t[0],a=t[1];return 3*(n+a)/4-a},n.toByteArray=o,n.fromByteArray=l;for(var c=[],u=[],p=\"undefined\"==typeof Uint8Array?Array:Uint8Array,f=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",g=0,_=f.length;g<_;++g)c[g]=f[g],u[f.charCodeAt(g)]=g;u[45]=62,u[95]=63},{}],2:[function(){},{}],3:[function(e,t,n){(function(){(function(){/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */'use strict';var t=String.fromCharCode,o=Math.min;function d(e){if(2147483647e)throw new RangeError(\"The value \\\"\"+e+\"\\\" is invalid for option \\\"size\\\"\")}function u(e,t,n){return c(e),0>=e?d(e):void 0===t?d(e):\"string\"==typeof n?d(e).fill(t,n):d(e).fill(t)}function p(e){return c(e),d(0>e?0:0|m(e))}function f(e,t){if((\"string\"!=typeof t||\"\"===t)&&(t=\"utf8\"),!s.isEncoding(t))throw new TypeError(\"Unknown encoding: \"+t);var n=0|b(e,t),r=d(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function g(e){for(var t=0>e.length?0:0|m(e.length),n=d(t),r=0;rt||e.byteLength=2147483647)throw new RangeError(\"Attempt to allocate Buffer larger than maximum size: 0x\"+2147483647 .toString(16)+\" bytes\");return 0|e}function b(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||K(e,ArrayBuffer))return e.byteLength;if(\"string\"!=typeof e)throw new TypeError(\"The \\\"string\\\" argument must be one of type string, Buffer, or ArrayBuffer. Received type \"+typeof e);var n=e.length,r=2>>1;case\"base64\":return z(e).length;default:if(a)return r?-1:H(e).length;t=(\"\"+t).toLowerCase(),a=!0;}}function y(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return\"\";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return\"\";if(n>>>=0,t>>>=0,n<=t)return\"\";for(e||(e=\"utf8\");;)switch(e){case\"hex\":return P(this,t,n);case\"utf8\":case\"utf-8\":return x(this,t,n);case\"ascii\":return D(this,t,n);case\"latin1\":case\"binary\":return I(this,t,n);case\"base64\":return A(this,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return M(this,t,n);default:if(r)throw new TypeError(\"Unknown encoding: \"+e);e=(e+\"\").toLowerCase(),r=!0;}}function C(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function R(e,t,n,r,a){if(0===e.length)return-1;if(\"string\"==typeof n?(r=n,n=0):2147483647n&&(n=-2147483648),n=+n,X(n)&&(n=a?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(0>n)if(a)n=0;else return-1;if(\"string\"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:E(e,t,n,r,a);if(\"number\"==typeof t)return t&=255,\"function\"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):E(e,[t],n,r,a);throw new TypeError(\"val must be string, number or Buffer\")}function E(e,t,n,r,a){function o(e,t){return 1===d?e[t]:e.readUInt16BE(t*d)}var d=1,s=e.length,l=t.length;if(void 0!==r&&(r=(r+\"\").toLowerCase(),\"ucs2\"===r||\"ucs-2\"===r||\"utf16le\"===r||\"utf-16le\"===r)){if(2>e.length||2>t.length)return-1;d=2,s/=2,l/=2,n/=2}var c;if(a){var u=-1;for(c=n;cs&&(n=s-l),c=n;0<=c;c--){for(var p=!0,f=0;fa&&(r=a)):r=a;var o=t.length;r>o/2&&(r=o/2);for(var d,s=0;sd&&(s=d):2===l?(c=e[a+1],128==(192&c)&&(f=(31&d)<<6|63&c,127f||57343f&&(s=f))):void 0}null===s?(s=65533,l=1):65535>>10),s=56320|1023&s),r.push(s),a+=l}return N(r)}function N(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r=\"\",a=0;at)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var a=\"\",o=t;oe)throw new RangeError(\"offset is not uint\");if(e+t>n)throw new RangeError(\"Trying to access beyond buffer length\")}function F(e,t,n,r,a,o){if(!s.isBuffer(e))throw new TypeError(\"\\\"buffer\\\" argument must be a Buffer instance\");if(t>a||te.length)throw new RangeError(\"Index out of range\")}function B(e,t,n,r){if(n+r>e.length)throw new RangeError(\"Index out of range\");if(0>n)throw new RangeError(\"Index out of range\")}function U(e,t,n,r,a){return t=+t,n>>>=0,a||B(e,t,n,4,34028234663852886e22,-34028234663852886e22),J.write(e,t,n,r,23,4),n+4}function j(e,t,n,r,a){return t=+t,n>>>=0,a||B(e,t,n,8,17976931348623157e292,-17976931348623157e292),J.write(e,t,n,r,52,8),n+8}function q(e){if(e=e.split(\"=\")[0],e=e.trim().replace(Q,\"\"),2>e.length)return\"\";for(;0!=e.length%4;)e+=\"=\";return e}function W(e){return 16>e?\"0\"+e.toString(16):e.toString(16)}function H(e,t){t=t||1/0;for(var n,r=e.length,a=null,o=[],d=0;dn){if(!a){if(56319n){-1<(t-=3)&&o.push(239,191,189),a=n;continue}n=(a-55296<<10|n-56320)+65536}else a&&-1<(t-=3)&&o.push(239,191,189);if(a=null,128>n){if(0>(t-=1))break;o.push(n)}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;o.push(224|n>>12,128|63&n>>6,128|63&n)}else if(1114112>n){if(0>(t-=4))break;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}else throw new Error(\"Invalid code point\")}return o}function Y(e){for(var t=[],n=0;n(t-=2));++d)n=e.charCodeAt(d),r=n>>8,a=n%256,o.push(a),o.push(r);return o}function z(e){return $.toByteArray(q(e))}function G(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function K(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!==e}var $=e(\"base64-js\"),J=e(\"ieee754\");n.Buffer=s,n.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},n.INSPECT_MAX_BYTES=50;n.kMaxLength=2147483647,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||\"undefined\"==typeof console||\"function\"!=typeof console.error||console.error(\"This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.\"),Object.defineProperty(s.prototype,\"parent\",{enumerable:!0,get:function(){return s.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(s.prototype,\"offset\",{enumerable:!0,get:function(){return s.isBuffer(this)?this.byteOffset:void 0}}),\"undefined\"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,n){return l(e,t,n)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,n){return u(e,t,n)},s.allocUnsafe=function(e){return p(e)},s.allocUnsafeSlow=function(e){return p(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(K(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),K(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError(\"The \\\"buf1\\\", \\\"buf2\\\" arguments must be one of type Buffer or Uint8Array\");if(e===t)return 0;for(var n=e.length,r=t.length,d=0,l=o(n,r);dt&&(e+=\" ... \"),\"\"},s.prototype.compare=function(e,t,n,r,a){if(K(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError(\"The \\\"target\\\" argument must be one of type Buffer or Uint8Array. Received type \"+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),0>t||n>e.length||0>r||a>this.length)throw new RangeError(\"out of range index\");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var d=a-r,l=n-t,c=o(d,l),u=this.slice(r,a),p=e.slice(t,n),f=0;f>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r=\"utf8\")):(r=n,n=void 0);else throw new Error(\"Buffer.write(string, encoding, offset[, length]) is no longer supported\");var a=this.length-t;if((void 0===n||n>a)&&(n=a),0n||0>t)||t>this.length)throw new RangeError(\"Attempt to write outside buffer bounds\");r||(r=\"utf8\");for(var o=!1;;)switch(r){case\"hex\":return w(this,e,t,n);case\"utf8\":case\"utf-8\":return S(this,e,t,n);case\"ascii\":return T(this,e,t,n);case\"latin1\":case\"binary\":return v(this,e,t,n);case\"base64\":return k(this,e,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return L(this,e,t,n);default:if(o)throw new TypeError(\"Unknown encoding: \"+r);r=(\"\"+r).toLowerCase(),o=!0;}},s.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}};s.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,0>e?(e+=n,0>e&&(e=0)):e>n&&(e=n),0>t?(t+=n,0>t&&(t=0)):t>n&&(t=n),t>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e],a=1,o=0;++o>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e+--t],a=1;0>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var a=this[e],o=1,d=0;++d=o&&(a-=r(2,8*t)),a},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var a=t,o=1,d=this[e+--a];0=o&&(d-=r(2,8*t)),d},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),J.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),J.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),J.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),J.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,n,a){if(e=+e,t>>>=0,n>>>=0,!a){var o=r(2,8*n)-1;F(this,e,t,n,o,0)}var d=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!a){var o=r(2,8*n)-1;F(this,e,t,n,o,0)}var d=n-1,s=1;for(this[t+d]=255&e;0<=--d&&(s*=256);)this[t+d]=255&e/s;return t+n},s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);F(this,e,t,n,o-1,-o)}var d=0,s=1,l=0;for(this[t]=255&e;++de&&0===l&&0!==this[t+d-1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},s.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var o=r(2,8*n-1);F(this,e,t,n,o-1,-o)}var d=n-1,s=1,l=0;for(this[t+d]=255&e;0<=--d&&(s*=256);)0>e&&0===l&&0!==this[t+d+1]&&(l=1),this[t+d]=255&(e/s>>0)-l;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||F(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw new TypeError(\"argument should be a Buffer\");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0t)throw new RangeError(\"targetStart out of bounds\");if(0>n||n>=this.length)throw new RangeError(\"Index out of range\");if(0>r)throw new RangeError(\"sourceEnd out of bounds\");r>this.length&&(r=this.length),e.length-ta||\"latin1\"===r)&&(e=a)}}else\"number\"==typeof e&&(e&=255);if(0>t||this.length>>=0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(\"number\"==typeof e)for(o=t;o{\"%%\"===e||(r++,\"%c\"===e&&(a=r))}),e.splice(a,0,n)},n.save=function(e){try{e?n.storage.setItem(\"debug\",e):n.storage.removeItem(\"debug\")}catch(e){}},n.load=r,n.useColors=function(){return!!(\"undefined\"!=typeof window&&window.process&&(\"renderer\"===window.process.type||window.process.__nwjs))||!(\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))&&(\"undefined\"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||\"undefined\"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)&&31<=parseInt(RegExp.$1,10)||\"undefined\"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"))}})(),n.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],n.log=console.debug||console.log||(()=>{}),t.exports=e(\"./common\")(n);const{formatters:o}=t.exports;o.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}).call(this)}).call(this,e(\"_process\"))},{\"./common\":5,_process:12}],5:[function(e,t){t.exports=function(t){function r(e){function t(...e){if(!t.enabled)return;const a=t,o=+new Date,i=o-(n||o);a.diff=i,a.prev=n,a.curr=o,n=o,e[0]=r.coerce(e[0]),\"string\"!=typeof e[0]&&e.unshift(\"%O\");let d=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if(\"%%\"===t)return\"%\";d++;const o=r.formatters[n];if(\"function\"==typeof o){const n=e[d];t=o.call(a,n),e.splice(d,1),d--}return t}),r.formatArgs.call(a,e);const s=a.log||r.log;s.apply(a,e)}let n,o=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=a,t.destroy=r.destroy,Object.defineProperty(t,\"enabled\",{enumerable:!0,configurable:!1,get:()=>null===o?r.enabled(e):o,set:e=>{o=e}}),\"function\"==typeof r.init&&r.init(t),t}function a(e,t){const n=r(this.namespace+(\"undefined\"==typeof t?\":\":t)+e);return n.log=this.log,n}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\\.\\*\\?$/,\"*\")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(o),...r.skips.map(o).map(e=>\"-\"+e)].join(\",\");return r.enable(\"\"),e},r.enable=function(e){r.save(e),r.names=[],r.skips=[];let t;const n=(\"string\"==typeof e?e:\"\").split(/[\\s,]+/),a=n.length;for(t=0;t{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let t=0;for(let n=0;nd&&!l.warned){l.warned=!0;var c=new Error(\"Possible EventEmitter memory leak detected. \"+l.length+\" \"+(t+\" listeners added. Use emitter.setMaxListeners() to increase limit\"));c.name=\"MaxListenersExceededWarning\",c.emitter=e,c.type=t,c.count=l.length,n(c)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function s(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},a=d.bind(r);return a.listener=n,r.wrapFn=a,a}function l(e,t,n){var r=e._events;if(r===void 0)return[];var a=r[t];return void 0===a?[]:\"function\"==typeof a?n?[a.listener||a]:[a]:n?f(a):u(a,a.length)}function c(e){var t=this._events;if(t!==void 0){var n=t[e];if(\"function\"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function u(e,t){for(var n=Array(t),r=0;re||y(e))throw new RangeError(\"The value of \\\"defaultMaxListeners\\\" is out of range. It must be a non-negative number. Received \"+e+\".\");C=e}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if(\"number\"!=typeof e||0>e||y(e))throw new RangeError(\"The value of \\\"n\\\" is out of range. It must be a non-negative number. Received \"+e+\".\");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;no)return this;0===o?n.shift():p(n,o),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit(\"removeListener\",e,s||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,void 0===n)return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var a,o=Object.keys(n);for(r=0;r */o.read=function(t,n,a,o,l){var c,u,p=8*l-o-1,f=(1<>1,_=-7,h=a?l-1:0,b=a?-1:1,d=t[n+h];for(h+=b,c=d&(1<<-_)-1,d>>=-_,_+=p;0<_;c=256*c+t[n+h],h+=b,_-=8);for(u=c&(1<<-_)-1,c>>=-_,_+=o;0<_;u=256*u+t[n+h],h+=b,_-=8);if(0===c)c=1-g;else{if(c===f)return u?NaN:(d?-1:1)*(1/0);u+=r(2,o),c-=g}return(d?-1:1)*u*r(2,c-o)},o.write=function(a,o,l,u,p,f){var h,b,y,g=Math.LN2,_=Math.log,C=8*f-p-1,R=(1<>1,w=23===p?r(2,-24)-r(2,-77):0,S=u?0:f-1,T=u?1:-1,d=0>o||0===o&&0>1/o?1:0;for(o=n(o),isNaN(o)||o===1/0?(b=isNaN(o)?1:0,h=R):(h=t(_(o)/g),1>o*(y=r(2,-h))&&(h--,y*=2),o+=1<=h+E?w/y:w*r(2,1-E),2<=o*y&&(h++,y/=2),h+E>=R?(b=0,h=R):1<=h+E?(b=(o*y-1)*r(2,p),h+=E):(b=o*r(2,E-1)*r(2,p),h=0));8<=p;a[l+S]=255&b,S+=T,b/=256,p-=8);for(h=h<=1.5*a?\"s\":\"\")}var l=24*(60*60000);t.exports=function(e,t){t=t||{};var n=typeof e;if(\"string\"==n&&0 */let n;t.exports=\"function\"==typeof queueMicrotask?queueMicrotask.bind(\"undefined\"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,\"undefined\"==typeof global?\"undefined\"==typeof self?\"undefined\"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){'use strict';var a=e(\"safe-buffer\").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError(\"requested too many random bytes\");var r=a.allocUnsafe(e);if(0n?0:+n,t.length)===t}function i(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function d(e,t,n){return\"number\"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}var s={};r(\"ERR_INVALID_OPT_VALUE\",function(e,t){return\"The value \\\"\"+t+\"\\\" is invalid for option \\\"\"+e+\"\\\"\"},TypeError),r(\"ERR_INVALID_ARG_TYPE\",function(e,t,n){var r;\"string\"==typeof t&&o(t,\"not \")?(r=\"must not be\",t=t.replace(/^not /,\"\")):r=\"must be\";var s;if(i(e,\" argument\"))s=\"The \".concat(e,\" \").concat(r,\" \").concat(a(t,\"type\"));else{var l=d(e,\".\")?\"property\":\"argument\";s=\"The \\\"\".concat(e,\"\\\" \").concat(l,\" \").concat(r,\" \").concat(a(t,\"type\"))}return s+=\". Received type \".concat(typeof n),s},TypeError),r(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\"),r(\"ERR_METHOD_NOT_IMPLEMENTED\",function(e){return\"The \"+e+\" method is not implemented\"}),r(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\"),r(\"ERR_STREAM_DESTROYED\",function(e){return\"Cannot call \"+e+\" after a stream was destroyed\"}),r(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\"),r(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\"),r(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\"),r(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),r(\"ERR_UNKNOWN_ENCODING\",function(e){return\"Unknown encoding: \"+e},TypeError),r(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\"),t.exports.codes=s},{}],16:[function(e,t){(function(n){(function(){'use strict';function r(e){return this instanceof r?void(d.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once(\"end\",a)))):new r(e)}function a(){this._writableState.ended||n.nextTick(o,this)}function o(e){e.end()}var i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var d=e(\"./_stream_readable\"),s=e(\"./_stream_writable\");e(\"inherits\")(r,d);for(var l,c=i(s.prototype),u=0;u>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=p(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function g(e,t){if(x(\"onEofChunk\"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?_(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,h(e)))}}function _(e){var t=e._readableState;x(\"emitReadable\",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(x(\"emitReadable\",t.flowing),t.emittedReadable=!0,n.nextTick(h,e))}function h(e){var t=e._readableState;x(\"emitReadable_\",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(\"readable\"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,S(e)}function m(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(b,e,t))}function b(e,t){for(;!t.reading&&!t.ended&&(t.length=t.length?(n=t.decoder?t.buffer.join(\"\"):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function v(e){var t=e._readableState;x(\"endReadable\",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(k,t,e))}function k(e,t){if(x(\"endReadableNT\",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit(\"end\"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function L(e,t){for(var n=0,r=e.length;n=t.highWaterMark)||t.ended))return x(\"read: emitReadable\",t.length,t.ended),0===t.length&&t.ended?v(this):_(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&v(this),null;var a=t.needReadable;x(\"need readable\",a),(0===t.length||t.length-e>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:\"consume\",value:function(e,t){var n;return eo.length?o.length:e;if(a+=i===o.length?o:o.slice(0,e),e-=i,0===e){i===o.length?(++r,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=o.slice(i));break}++r}return this.length-=r,a}},{key:\"_getBuffer\",value:function(e){var t=u.allocUnsafe(e),r=this.head,a=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),e-=i,0===e){i===o.length?(++a,this.head=r.next?r.next:this.tail=null):(this.head=r,r.data=o.slice(i));break}++a}return this.length-=a,t}},{key:g,value:function(e,t){return f(this,r({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){'use strict';function n(e,t){a(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(\"close\")}function a(e,t){e.emit(\"error\",t)}t.exports={destroy:function(t,o){var i=this,d=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return d||s?(o?o(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!o&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(r,i):(i._writableState.errorEmitted=!0,e.nextTick(n,i,t)):e.nextTick(n,i,t):o?(e.nextTick(r,i),o(t)):e.nextTick(r,i)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(\"error\",t)}}}).call(this)}).call(this,e(\"_process\"))},{_process:12}],24:[function(e,t){'use strict';function n(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),a=0;at.length)throw new u(\"streams\");var a,l=t.map(function(e,n){var d=nd){var s=i?o:\"highWaterMark\";throw new a(s,d)}return t(d)}return e.objectMode?16:16384}}},{\"../../../errors\":15}],28:[function(e,t){t.exports=e(\"events\").EventEmitter},{events:7}],29:[function(e,t,n){n=t.exports=e(\"./lib/_stream_readable.js\"),n.Stream=n,n.Readable=n,n.Writable=e(\"./lib/_stream_writable.js\"),n.Duplex=e(\"./lib/_stream_duplex.js\"),n.Transform=e(\"./lib/_stream_transform.js\"),n.PassThrough=e(\"./lib/_stream_passthrough.js\"),n.finished=e(\"./lib/internal/streams/end-of-stream.js\"),n.pipeline=e(\"./lib/internal/streams/pipeline.js\")},{\"./lib/_stream_duplex.js\":16,\"./lib/_stream_passthrough.js\":17,\"./lib/_stream_readable.js\":18,\"./lib/_stream_transform.js\":19,\"./lib/_stream_writable.js\":20,\"./lib/internal/streams/end-of-stream.js\":24,\"./lib/internal/streams/pipeline.js\":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return i(e,t,n)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var o=e(\"buffer\"),i=o.Buffer;i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=a),a.prototype=Object.create(i.prototype),r(i,a),a.from=function(e,t,n){if(\"number\"==typeof e)throw new TypeError(\"Argument must not be a number\");return i(e,t,n)},a.alloc=function(e,t,n){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");var r=i(e);return void 0===t?r.fill(0):\"string\"==typeof n?r.fill(t,n):r.fill(t),r},a.allocUnsafe=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return i(e)},a.allocUnsafeSlow=function(e){if(\"number\"!=typeof e)throw new TypeError(\"Argument must be a number\");return o.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){'use strict';function r(e){if(!e)return\"utf8\";for(var t;;)switch(e){case\"utf8\":case\"utf-8\":return\"utf8\";case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return\"utf16le\";case\"latin1\":case\"binary\":return\"latin1\";case\"base64\":case\"ascii\":case\"hex\":return e;default:if(t)return;e=(\"\"+e).toLowerCase(),t=!0;}}function a(e){var t=r(e);if(\"string\"!=typeof t&&(m.isEncoding===b||!b(e)))throw new Error(\"Unknown encoding: \"+e);return t||e}function o(e){this.encoding=a(e);var t;switch(this.encoding){case\"utf16le\":this.text=u,this.end=p,t=4;break;case\"utf8\":this.fillLast=c,t=4;break;case\"base64\":this.text=f,this.end=g,t=3;break;default:return this.write=_,void(this.end=h);}this.lastNeed=0,this.lastTotal=0,this.lastChar=m.allocUnsafe(t)}function d(e){if(127>=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e,t,n){var r=t.length-1;if(r=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(\"utf16le\",t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):\"\";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(\"utf16le\",0,n)}return t}function f(e,t){var r=(e.length-t)%3;return 0==r?e.toString(\"base64\",t):(this.lastNeed=3-r,this.lastTotal=3,1==r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(\"base64\",t,e.length-r))}function g(e){var t=e&&e.length?this.write(e):\"\";return this.lastNeed?t+this.lastChar.toString(\"base64\",0,3-this.lastNeed):t}function _(e){return e.toString(this.encoding)}function h(e){return e&&e.length?this.write(e):\"\"}var m=e(\"safe-buffer\").Buffer,b=m.isEncoding||function(e){switch(e=\"\"+e,e&&e.toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":case\"raw\":return!0;default:return!1;}};n.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return\"\";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return\"\";n=this.lastNeed,this.lastNeed=0}else n=0;return n */const a=e(\"debug\")(\"simple-peer\"),o=e(\"get-browser-rtc\"),i=e(\"randombytes\"),d=e(\"readable-stream\"),s=e(\"queue-microtask\"),l=e(\"err-code\"),{Buffer:c}=e(\"buffer\"),u=65536;class p extends d.Duplex{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),this._id=i(4).toString(\"hex\").slice(0,7),this._debug(\"new peer %o\",e),this.channelName=e.initiator?e.channelName||i(20).toString(\"hex\"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||p.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},p.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5000,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&\"object\"==typeof e.wrtc?e.wrtc:o(),!this._wrtc)if(\"undefined\"==typeof window)throw l(new Error(\"No WebRTC support: Specify `opts.wrtc` option in this environment\"),\"ERR_WEBRTC_SUPPORT\");else throw l(new Error(\"No WebRTC support: Not a supported browser\"),\"ERR_WEBRTC_SUPPORT\");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(l(e,\"ERR_PC_CONSTRUCTOR\"))}this._isReactNativeWebrtc=\"number\"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},\"object\"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(l(e,\"ERR_PC_PEER_IDENTITY\"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug(\"initial negotiation\"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once(\"finish\",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&\"open\"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot signal after peer is destroyed\"),\"ERR_DESTROYED\");if(\"string\"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug(\"signal()\"),e.renegotiate&&this.initiator&&(this._debug(\"got request to renegotiate\"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug(\"got request for transceiver\"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],\"offer\"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(l(e,\"ERR_SET_REMOTE_DESCRIPTION\"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(l(new Error(\"signal() called with invalid signal data\"),\"ERR_SIGNALING\"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(\".local\")?r(\"Ignoring unsupported ICE candidate.\"):this.destroy(l(e,\"ERR_ADD_ICE_CANDIDATE\"))})}send(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot send after peer is destroyed\"),\"ERR_DESTROYED\");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot addTransceiver after peer is destroyed\"),\"ERR_DESTROYED\");if(this._debug(\"addTransceiver()\"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(l(e,\"ERR_ADD_TRANSCEIVER\"))}else this.emit(\"signal\",{type:\"transceiverRequest\",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot addStream after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"addStream()\"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot addTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"addTrack()\");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(!r)r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation();else if(r.removed)throw l(new Error(\"Track has been removed. You should enable/disable tracks that you want to re-add.\"),\"ERR_SENDER_REMOVED\");else throw l(new Error(\"Track has already been added to that stream.\"),\"ERR_SENDER_ALREADY_ADDED\")}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot replaceTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"replaceTrack()\");const r=this._senderMap.get(e),a=r?r.get(n):null;if(!a)throw l(new Error(\"Cannot replace track that was never added.\"),\"ERR_TRACK_NOT_ADDED\");t&&this._senderMap.set(t,r),null==a.replaceTrack?this.destroy(l(new Error(\"replaceTrack is not supported in this browser\"),\"ERR_UNSUPPORTED_REPLACETRACK\")):a.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw l(new Error(\"cannot removeTrack after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"removeSender()\");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw l(new Error(\"Cannot remove track that was never added.\"),\"ERR_TRACK_NOT_ADDED\");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){\"NS_ERROR_UNEXPECTED\"===e.name?this._sendersAwaitingStable.push(r):this.destroy(l(e,\"ERR_REMOVE_TRACK\"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot removeStream after peer is destroyed\"),\"ERR_DESTROYED\");this._debug(\"removeSenders()\"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug(\"_needsNegotiation\"),this._batchedNegotiation||(this._batchedNegotiation=!0,s(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug(\"starting batched negotiation\"),this.negotiate()):this._debug(\"non-initiator initial negotiation request discarded\"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw l(new Error(\"cannot negotiate after peer is destroyed\"),\"ERR_DESTROYED\");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"start negotiation\"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug(\"already negotiating, queueing\")):(this._debug(\"requesting negotiation from initiator\"),this.emit(\"signal\",{type:\"renegotiate\",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug(\"destroying (error: %s)\",e&&(e.message||e)),s(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug(\"destroy (error: %s)\",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener(\"finish\",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit(\"error\",e),this.emit(\"close\"),t()}))}_setupData(e){if(!e.channel)return this.destroy(l(new Error(\"Data channel event is missing `channel` property\"),\"ERR_DATA_CHANNEL\"));this._channel=e.channel,this._channel.binaryType=\"arraybuffer\",\"number\"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=u),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(l(t,\"ERR_DATA_CHANNEL\"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&\"closing\"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5000)}_read(){}_write(e,t,n){if(this.destroyed)return n(l(new Error(\"cannot write after peer is destroyed\"),\"ERR_DATA_CHANNEL\"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(l(e,\"ERR_DATA_CHANNEL\"))}this._channel.bufferedAmount>u?(this._debug(\"start backpressure: bufferedAmount %d\",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug(\"write before connect\"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once(\"connect\",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug(\"started iceComplete timeout\"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug(\"iceComplete timeout completed\"),this.emit(\"iceTimeout\"),this.emit(\"_iceComplete\"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug(\"createOffer success\"),this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(l(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(l(e,\"ERR_CREATE_OFFER\"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug(\"signal\"),this.emit(\"signal\",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once(\"_iceComplete\",t))}).catch(e=>{this.destroy(l(e,\"ERR_SET_LOCAL_DESCRIPTION\"))})}).catch(e=>{this.destroy(l(e,\"ERR_CREATE_ANSWER\"))})}_onConnectionStateChange(){this.destroyed||\"failed\"===this._pc.connectionState&&this.destroy(l(new Error(\"Connection failed.\"),\"ERR_CONNECTION_FAILURE\"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug(\"iceStateChange (connection: %s) (gathering: %s)\",e,t),this.emit(\"iceStateChange\",e,t),(\"connected\"===e||\"completed\"===e)&&(this._pcReady=!0,this._maybeReady()),\"failed\"===e&&this.destroy(l(new Error(\"Ice connection failed.\"),\"ERR_ICE_CONNECTION_FAILURE\")),\"closed\"===e&&this.destroy(l(new Error(\"Ice connection closed.\"),\"ERR_ICE_CONNECTION_CLOSED\"))}getStats(e){const t=e=>(\"[object Array]\"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug(\"maybeReady pc %s channel %s\",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},a={},o={};let i=!1;n.forEach(e=>{(\"remotecandidate\"===e.type||\"remote-candidate\"===e.type)&&(r[e.id]=e),(\"localcandidate\"===e.type||\"local-candidate\"===e.type)&&(a[e.id]=e),(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&(o[e.id]=e)});const d=e=>{i=!0;let t=a[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):\"string\"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(\":\"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(\":\")?\"IPv6\":\"IPv4\");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):\"string\"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(\":\"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(\":\")?\"IPv6\":\"IPv4\"),this._debug(\"connect local: %s:%s remote: %s:%s\",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{\"transport\"===e.type&&e.selectedCandidatePairId&&d(o[e.selectedCandidatePairId]),(\"googCandidatePair\"===e.type&&\"true\"===e.googActiveConnection||(\"candidatepair\"===e.type||\"candidate-pair\"===e.type)&&e.selected)&&d(e)}),!i&&(!Object.keys(o).length||Object.keys(a).length))return void setTimeout(e,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(l(e,\"ERR_DATA_CHANNEL\"))}this._chunk=null,this._debug(\"sent chunk from \\\"write before connect\\\"\");const e=this._cb;this._cb=null,e(null)}\"number\"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug(\"connect\"),this.emit(\"connect\")})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>u)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(\"stable\"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug(\"flushing sender queue\",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug(\"flushing negotiation queue\"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug(\"negotiated\"),this.emit(\"negotiated\"))),this._debug(\"signalingStateChange %s\",this._pc.signalingState),this.emit(\"signalingStateChange\",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit(\"signal\",{type:\"candidate\",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit(\"_iceComplete\")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=c.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug(\"ending backpressure: bufferedAmount %d\",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug(\"on channel open\"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug(\"on channel close\"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug(\"on track\"),this.emit(\"track\",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),s(()=>{this._debug(\"on stream\"),this.emit(\"stream\",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]=\"[\"+this._id+\"] \"+e[0],a.apply(null,e)}}p.WEBRTC_SUPPORT=!!o(),p.config={iceServers:[{urls:[\"stun:stun.l.google.com:19302\",\"stun:global.stun.twilio.com:3478\"]}],sdpSemantics:\"unified-plan\"},p.channelConfig={},t.exports=p},{buffer:3,debug:4,\"err-code\":6,\"get-browser-rtc\":8,\"queue-microtask\":13,randombytes:14,\"readable-stream\":29}]},{},[])(\"/\")});", "/**\n * @module sync-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as Y from 'yjs'\n\n/**\n * @typedef {Map} StateMap\n */\n\n/**\n * Core Yjs defines two message types:\n * \u2022 YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.\n * \u2022 YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it\n * received all information from the remote client.\n *\n * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection\n * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both\n * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.\n *\n * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.\n * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies\n * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the\n * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can\n * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.\n * Therefore it is necessary that the client initiates the sync.\n *\n * Construction of a message:\n * [messageType : varUint, message definition..]\n *\n * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!\n *\n * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)\n */\n\nexport const messageYjsSyncStep1 = 0\nexport const messageYjsSyncStep2 = 1\nexport const messageYjsUpdate = 2\n\n/**\n * Create a sync step 1 message based on the state of the current shared document.\n *\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n */\nexport const writeSyncStep1 = (encoder, doc) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep1)\n const sv = Y.encodeStateVector(doc)\n encoding.writeVarUint8Array(encoder, sv)\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Y.Doc} doc\n * @param {Uint8Array} [encodedStateVector]\n */\nexport const writeSyncStep2 = (encoder, doc, encodedStateVector) => {\n encoding.writeVarUint(encoder, messageYjsSyncStep2)\n encoding.writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector))\n}\n\n/**\n * Read SyncStep1 message and reply with SyncStep2.\n *\n * @param {decoding.Decoder} decoder The reply to the received message\n * @param {encoding.Encoder} encoder The received message\n * @param {Y.Doc} doc\n */\nexport const readSyncStep1 = (decoder, encoder, doc) =>\n writeSyncStep2(encoder, doc, decoding.readVarUint8Array(decoder))\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncStep2 = (decoder, doc, transactionOrigin) => {\n try {\n Y.applyUpdate(doc, decoding.readVarUint8Array(decoder), transactionOrigin)\n } catch (error) {\n // This catches errors that are thrown by event handlers\n console.error('Caught error while handling a Yjs update', error)\n }\n}\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {Uint8Array} update\n */\nexport const writeUpdate = (encoder, update) => {\n encoding.writeVarUint(encoder, messageYjsUpdate)\n encoding.writeVarUint8Array(encoder, update)\n}\n\n/**\n * Read and apply Structs and then DeleteStore to a y instance.\n *\n * @param {decoding.Decoder} decoder\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readUpdate = readSyncStep2\n\n/**\n * @param {decoding.Decoder} decoder A message received from another client\n * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.\n * @param {Y.Doc} doc\n * @param {any} transactionOrigin\n */\nexport const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {\n const messageType = decoding.readVarUint(decoder)\n switch (messageType) {\n case messageYjsSyncStep1:\n readSyncStep1(decoder, encoder, doc)\n break\n case messageYjsSyncStep2:\n readSyncStep2(decoder, doc, transactionOrigin)\n break\n case messageYjsUpdate:\n readUpdate(decoder, doc, transactionOrigin)\n break\n default:\n throw new Error('Unknown message type')\n }\n return messageType\n}\n", "/**\n * @module awareness-protocol\n */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as time from 'lib0/time'\nimport * as math from 'lib0/math'\nimport { Observable } from 'lib0/observable'\nimport * as f from 'lib0/function'\nimport * as Y from 'yjs' // eslint-disable-line\n\nexport const outdatedTimeout = 30000\n\n/**\n * @typedef {Object} MetaClientState\n * @property {number} MetaClientState.clock\n * @property {number} MetaClientState.lastUpdated unix timestamp\n */\n\n/**\n * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information\n * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of\n * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.\n *\n * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override\n * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is\n * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that\n * a remote client is offline, it may propagate a message with\n * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a\n * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.\n *\n * Before a client disconnects, it should propagate a `null` state with an updated clock.\n *\n * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.\n *\n * @extends {Observable}\n */\nexport class Awareness extends Observable {\n /**\n * @param {Y.Doc} doc\n */\n constructor (doc) {\n super()\n this.doc = doc\n /**\n * @type {number}\n */\n this.clientID = doc.clientID\n /**\n * Maps from client id to client state\n * @type {Map>}\n */\n this.states = new Map()\n /**\n * @type {Map}\n */\n this.meta = new Map()\n this._checkInterval = /** @type {any} */ (setInterval(() => {\n const now = time.getUnixTime()\n if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(this.clientID)).lastUpdated)) {\n // renew local clock\n this.setLocalState(this.getLocalState())\n }\n /**\n * @type {Array}\n */\n const remove = []\n this.meta.forEach((meta, clientid) => {\n if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {\n remove.push(clientid)\n }\n })\n if (remove.length > 0) {\n removeAwarenessStates(this, remove, 'timeout')\n }\n }, math.floor(outdatedTimeout / 10)))\n doc.on('destroy', () => {\n this.destroy()\n })\n this.setLocalState({})\n }\n\n destroy () {\n this.emit('destroy', [this])\n this.setLocalState(null)\n super.destroy()\n clearInterval(this._checkInterval)\n }\n\n /**\n * @return {Object|null}\n */\n getLocalState () {\n return this.states.get(this.clientID) || null\n }\n\n /**\n * @param {Object|null} state\n */\n setLocalState (state) {\n const clientID = this.clientID\n const currLocalMeta = this.meta.get(clientID)\n const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1\n const prevState = this.states.get(clientID)\n if (state === null) {\n this.states.delete(clientID)\n } else {\n this.states.set(clientID, state)\n }\n this.meta.set(clientID, {\n clock,\n lastUpdated: time.getUnixTime()\n })\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n if (state === null) {\n removed.push(clientID)\n } else if (prevState == null) {\n if (state != null) {\n added.push(clientID)\n }\n } else {\n updated.push(clientID)\n if (!f.equalityDeep(prevState, state)) {\n filteredUpdated.push(clientID)\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local'])\n }\n this.emit('update', [{ added, updated, removed }, 'local'])\n }\n\n /**\n * @param {string} field\n * @param {any} value\n */\n setLocalStateField (field, value) {\n const state = this.getLocalState()\n if (state !== null) {\n this.setLocalState({\n ...state,\n [field]: value\n })\n }\n }\n\n /**\n * @return {Map>}\n */\n getStates () {\n return this.states\n }\n}\n\n/**\n * Mark (remote) clients as inactive and remove them from the list of active peers.\n * This change will be propagated to remote clients.\n *\n * @param {Awareness} awareness\n * @param {Array} clients\n * @param {any} origin\n */\nexport const removeAwarenessStates = (awareness, clients, origin) => {\n const removed = []\n for (let i = 0; i < clients.length; i++) {\n const clientID = clients[i]\n if (awareness.states.has(clientID)) {\n awareness.states.delete(clientID)\n if (clientID === awareness.clientID) {\n const curMeta = /** @type {MetaClientState} */ (awareness.meta.get(clientID))\n awareness.meta.set(clientID, {\n clock: curMeta.clock + 1,\n lastUpdated: time.getUnixTime()\n })\n }\n removed.push(clientID)\n }\n }\n if (removed.length > 0) {\n awareness.emit('change', [{ added: [], updated: [], removed }, origin])\n awareness.emit('update', [{ added: [], updated: [], removed }, origin])\n }\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Array} clients\n * @return {Uint8Array}\n */\nexport const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {\n const len = clients.length\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = clients[i]\n const state = states.get(clientID) || null\n const clock = /** @type {MetaClientState} */ (awareness.meta.get(clientID)).clock\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(state))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * Modify the content of an awareness update before re-encoding it to an awareness update.\n *\n * This might be useful when you have a central server that wants to ensure that clients\n * cant hijack somebody elses identity.\n *\n * @param {Uint8Array} update\n * @param {function(any):any} modify\n * @return {Uint8Array}\n */\nexport const modifyAwarenessUpdate = (update, modify) => {\n const decoder = decoding.createDecoder(update)\n const encoder = encoding.createEncoder()\n const len = decoding.readVarUint(decoder)\n encoding.writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const modifiedState = modify(state)\n encoding.writeVarUint(encoder, clientID)\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarString(encoder, JSON.stringify(modifiedState))\n }\n return encoding.toUint8Array(encoder)\n}\n\n/**\n * @param {Awareness} awareness\n * @param {Uint8Array} update\n * @param {any} origin This will be added to the emitted change event\n */\nexport const applyAwarenessUpdate = (awareness, update, origin) => {\n const decoder = decoding.createDecoder(update)\n const timestamp = time.getUnixTime()\n const added = []\n const updated = []\n const filteredUpdated = []\n const removed = []\n const len = decoding.readVarUint(decoder)\n for (let i = 0; i < len; i++) {\n const clientID = decoding.readVarUint(decoder)\n let clock = decoding.readVarUint(decoder)\n const state = JSON.parse(decoding.readVarString(decoder))\n const clientMeta = awareness.meta.get(clientID)\n const prevState = awareness.states.get(clientID)\n const currClock = clientMeta === undefined ? 0 : clientMeta.clock\n if (currClock < clock || (currClock === clock && state === null && awareness.states.has(clientID))) {\n if (state === null) {\n // never let a remote client remove this local state\n if (clientID === awareness.clientID && awareness.getLocalState() != null) {\n // remote client removed the local state. Do not remote state. Broadcast a message indicating\n // that this client still exists by increasing the clock\n clock++\n } else {\n awareness.states.delete(clientID)\n }\n } else {\n awareness.states.set(clientID, state)\n }\n awareness.meta.set(clientID, {\n clock,\n lastUpdated: timestamp\n })\n if (clientMeta === undefined && state !== null) {\n added.push(clientID)\n } else if (clientMeta !== undefined && state === null) {\n removed.push(clientID)\n } else if (state !== null) {\n if (!f.equalityDeep(state, prevState)) {\n filteredUpdated.push(clientID)\n }\n updated.push(clientID)\n }\n }\n }\n if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {\n awareness.emit('change', [{\n added, updated: filteredUpdated, removed\n }, origin])\n }\n if (added.length > 0 || updated.length > 0 || removed.length > 0) {\n awareness.emit('update', [{\n added, updated, removed\n }, origin])\n }\n}\n", "/* eslint-env browser */\n\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport * as promise from 'lib0/promise'\nimport * as error from 'lib0/error'\nimport * as string from 'lib0/string'\n\n/**\n * @param {string} secret\n * @param {string} roomName\n * @return {PromiseLike}\n */\nexport const deriveKey = (secret, roomName) => {\n const secretBuffer = string.encodeUtf8(secret).buffer\n const salt = string.encodeUtf8(roomName).buffer\n return crypto.subtle.importKey(\n 'raw',\n secretBuffer,\n 'PBKDF2',\n false,\n ['deriveKey']\n ).then(keyMaterial =>\n crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: 100000,\n hash: 'SHA-256'\n },\n keyMaterial,\n {\n name: 'AES-GCM',\n length: 256\n },\n true,\n ['encrypt', 'decrypt']\n )\n )\n}\n\n/**\n * @param {Uint8Array} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted, base64 encoded message\n */\nexport const encrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const iv = crypto.getRandomValues(new Uint8Array(12))\n return crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n data\n ).then(cipher => {\n const encryptedDataEncoder = encoding.createEncoder()\n encoding.writeVarString(encryptedDataEncoder, 'AES-GCM')\n encoding.writeVarUint8Array(encryptedDataEncoder, iv)\n encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher))\n return encoding.toUint8Array(encryptedDataEncoder)\n })\n}\n\n/**\n * @param {Object} data data to be encrypted\n * @param {CryptoKey?} key\n * @return {PromiseLike} encrypted data, if key is provided\n */\nexport const encryptJson = (data, key) => {\n const dataEncoder = encoding.createEncoder()\n encoding.writeAny(dataEncoder, data)\n return encrypt(encoding.toUint8Array(dataEncoder), key)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted buffer\n */\nexport const decrypt = (data, key) => {\n if (!key) {\n return /** @type {PromiseLike} */ (promise.resolve(data))\n }\n const dataDecoder = decoding.createDecoder(data)\n const algorithm = decoding.readVarString(dataDecoder)\n if (algorithm !== 'AES-GCM') {\n promise.reject(error.create('Unknown encryption algorithm'))\n }\n const iv = decoding.readVarUint8Array(dataDecoder)\n const cipher = decoding.readVarUint8Array(dataDecoder)\n return crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n cipher\n ).then(data => new Uint8Array(data))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {CryptoKey?} key\n * @return {PromiseLike} decrypted object\n */\nexport const decryptJson = (data, key) =>\n decrypt(data, key).then(decryptedValue =>\n decoding.readAny(decoding.createDecoder(new Uint8Array(decryptedValue)))\n )\n", "import * as ws from 'lib0/websocket'\nimport * as map from 'lib0/map'\nimport * as error from 'lib0/error'\nimport * as random from 'lib0/random'\nimport * as encoding from 'lib0/encoding'\nimport * as decoding from 'lib0/decoding'\nimport { ObservableV2 } from 'lib0/observable'\nimport * as logging from 'lib0/logging'\nimport * as promise from 'lib0/promise'\nimport * as bc from 'lib0/broadcastchannel'\nimport * as buffer from 'lib0/buffer'\nimport * as math from 'lib0/math'\nimport { createMutex } from 'lib0/mutex'\n\nimport * as Y from 'yjs' // eslint-disable-line\nimport Peer from 'simple-peer/simplepeer.min.js'\n\nimport * as syncProtocol from 'y-protocols/sync'\nimport * as awarenessProtocol from 'y-protocols/awareness'\n\nimport * as cryptoutils from './crypto.js'\n\nconst log = logging.createModuleLogger('y-webrtc')\n\nconst messageSync = 0\nconst messageQueryAwareness = 3\nconst messageAwareness = 1\nconst messageBcPeerId = 4\n\n/**\n * @type {Map}\n */\nconst signalingConns = new Map()\n\n/**\n * @type {Map}\n */\nconst rooms = new Map()\n\n/**\n * @param {Room} room\n */\nconst checkIsSynced = room => {\n let synced = true\n room.webrtcConns.forEach(peer => {\n if (!peer.synced) {\n synced = false\n }\n })\n if ((!synced && room.synced) || (synced && !room.synced)) {\n room.synced = synced\n room.provider.emit('synced', [{ synced }])\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with all peers')\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} buf\n * @param {function} syncedCallback\n * @return {encoding.Encoder?}\n */\nconst readMessage = (room, buf, syncedCallback) => {\n const decoder = decoding.createDecoder(buf)\n const encoder = encoding.createEncoder()\n const messageType = decoding.readVarUint(decoder)\n if (room === undefined) {\n return null\n }\n const awareness = room.awareness\n const doc = room.doc\n let sendReply = false\n switch (messageType) {\n case messageSync: {\n encoding.writeVarUint(encoder, messageSync)\n const syncMessageType = syncProtocol.readSyncMessage(decoder, encoder, doc, room)\n if (syncMessageType === syncProtocol.messageYjsSyncStep2 && !room.synced) {\n syncedCallback()\n }\n if (syncMessageType === syncProtocol.messageYjsSyncStep1) {\n sendReply = true\n }\n break\n }\n case messageQueryAwareness:\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())))\n sendReply = true\n break\n case messageAwareness:\n awarenessProtocol.applyAwarenessUpdate(awareness, decoding.readVarUint8Array(decoder), room)\n break\n case messageBcPeerId: {\n const add = decoding.readUint8(decoder) === 1\n const peerName = decoding.readVarString(decoder)\n if (peerName !== room.peerId && ((room.bcConns.has(peerName) && !add) || (!room.bcConns.has(peerName) && add))) {\n const removed = []\n const added = []\n if (add) {\n room.bcConns.add(peerName)\n added.push(peerName)\n } else {\n room.bcConns.delete(peerName)\n removed.push(peerName)\n }\n room.provider.emit('peers', [{\n added,\n removed,\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n broadcastBcPeerId(room)\n }\n break\n }\n default:\n console.error('Unable to compute message')\n return encoder\n }\n if (!sendReply) {\n // nothing has been written, no answer created\n return null\n }\n return encoder\n}\n\n/**\n * @param {WebrtcConn} peerConn\n * @param {Uint8Array} buf\n * @return {encoding.Encoder?}\n */\nconst readPeerMessage = (peerConn, buf) => {\n const room = peerConn.room\n log('received message from ', logging.BOLD, peerConn.remotePeerId, logging.GREY, ' (', room.name, ')', logging.UNBOLD, logging.UNCOLOR)\n return readMessage(room, buf, () => {\n peerConn.synced = true\n log('synced ', logging.BOLD, room.name, logging.UNBOLD, ' with ', logging.BOLD, peerConn.remotePeerId)\n checkIsSynced(room)\n })\n}\n\n/**\n * @param {WebrtcConn} webrtcConn\n * @param {encoding.Encoder} encoder\n */\nconst sendWebrtcConn = (webrtcConn, encoder) => {\n log('send message to ', logging.BOLD, webrtcConn.remotePeerId, logging.UNBOLD, logging.GREY, ' (', webrtcConn.room.name, ')', logging.UNCOLOR)\n try {\n webrtcConn.peer.send(encoding.toUint8Array(encoder))\n } catch (e) {}\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastWebrtcConn = (room, m) => {\n log('broadcast message in ', logging.BOLD, room.name, logging.UNBOLD)\n room.webrtcConns.forEach(conn => {\n try {\n conn.peer.send(m)\n } catch (e) {}\n })\n}\n\nexport class WebrtcConn {\n /**\n * @param {SignalingConn} signalingConn\n * @param {boolean} initiator\n * @param {string} remotePeerId\n * @param {Room} room\n */\n constructor (signalingConn, initiator, remotePeerId, room) {\n log('establishing connection to ', logging.BOLD, remotePeerId)\n this.room = room\n this.remotePeerId = remotePeerId\n this.glareToken = undefined\n this.closed = false\n this.connected = false\n this.synced = false\n /**\n * @type {any}\n */\n this.peer = new Peer({ initiator, ...room.provider.peerOpts })\n this.peer.on('signal', signal => {\n if (this.glareToken === undefined) {\n // add some randomness to the timestamp of the offer\n this.glareToken = Date.now() + Math.random()\n }\n publishSignalingMessage(signalingConn, room, { to: remotePeerId, from: room.peerId, type: 'signal', token: this.glareToken, signal })\n })\n this.peer.on('connect', () => {\n log('connected to ', logging.BOLD, remotePeerId)\n this.connected = true\n // send sync step 1\n const provider = room.provider\n const doc = provider.doc\n const awareness = room.awareness\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeSyncStep1(encoder, doc)\n sendWebrtcConn(this, encoder)\n const awarenessStates = awareness.getStates()\n if (awarenessStates.size > 0) {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageAwareness)\n encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, Array.from(awarenessStates.keys())))\n sendWebrtcConn(this, encoder)\n }\n })\n this.peer.on('close', () => {\n this.connected = false\n this.closed = true\n if (room.webrtcConns.has(this.remotePeerId)) {\n room.webrtcConns.delete(this.remotePeerId)\n room.provider.emit('peers', [{\n removed: [this.remotePeerId],\n added: [],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n }\n checkIsSynced(room)\n this.peer.destroy()\n log('closed connection to ', logging.BOLD, remotePeerId)\n announceSignalingInfo(room)\n })\n this.peer.on('error', err => {\n log('Error in connection to ', logging.BOLD, remotePeerId, ': ', err)\n announceSignalingInfo(room)\n })\n this.peer.on('data', data => {\n const answer = readPeerMessage(this, data)\n if (answer !== null) {\n sendWebrtcConn(this, answer)\n }\n })\n }\n\n destroy () {\n this.peer.destroy()\n }\n}\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastBcMessage = (room, m) => cryptoutils.encrypt(m, room.key).then(data =>\n room.mux(() =>\n bc.publish(room.name, data)\n )\n)\n\n/**\n * @param {Room} room\n * @param {Uint8Array} m\n */\nconst broadcastRoomMessage = (room, m) => {\n if (room.bcconnected) {\n broadcastBcMessage(room, m)\n }\n broadcastWebrtcConn(room, m)\n}\n\n/**\n * @param {Room} room\n */\nconst announceSignalingInfo = room => {\n signalingConns.forEach(conn => {\n // only subscribe if connection is established, otherwise the conn automatically subscribes to all rooms\n if (conn.connected) {\n conn.send({ type: 'subscribe', topics: [room.name] })\n if (room.webrtcConns.size < room.provider.maxConns) {\n publishSignalingMessage(conn, room, { type: 'announce', from: room.peerId })\n }\n }\n })\n}\n\n/**\n * @param {Room} room\n */\nconst broadcastBcPeerId = room => {\n if (room.provider.filterBcConns) {\n // broadcast peerId via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 1)\n encoding.writeVarString(encoderPeerIdBc, room.peerId)\n broadcastBcMessage(room, encoding.toUint8Array(encoderPeerIdBc))\n }\n}\n\nexport class Room {\n /**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n */\n constructor (doc, provider, name, key) {\n /**\n * Do not assume that peerId is unique. This is only meant for sending signaling messages.\n *\n * @type {string}\n */\n this.peerId = random.uuidv4()\n this.doc = doc\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = provider.awareness\n this.provider = provider\n this.synced = false\n this.name = name\n // @todo make key secret by scoping\n this.key = key\n /**\n * @type {Map}\n */\n this.webrtcConns = new Map()\n /**\n * @type {Set}\n */\n this.bcConns = new Set()\n this.mux = createMutex()\n this.bcconnected = false\n /**\n * @param {ArrayBuffer} data\n */\n this._bcSubscriber = data =>\n cryptoutils.decrypt(new Uint8Array(data), key).then(m =>\n this.mux(() => {\n const reply = readMessage(this, m, () => {})\n if (reply) {\n broadcastBcMessage(this, encoding.toUint8Array(reply))\n }\n })\n )\n /**\n * Listens to Yjs updates and sends them to remote peers\n *\n * @param {Uint8Array} update\n * @param {any} _origin\n */\n this._docUpdateHandler = (update, _origin) => {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, messageSync)\n syncProtocol.writeUpdate(encoder, update)\n broadcastRoomMessage(this, encoding.toUint8Array(encoder))\n }\n /**\n * Listens to Awareness updates and sends them to remote peers\n *\n * @param {any} changed\n * @param {any} _origin\n */\n this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {\n const changedClients = added.concat(updated).concat(removed)\n const encoderAwareness = encoding.createEncoder()\n encoding.writeVarUint(encoderAwareness, messageAwareness)\n encoding.writeVarUint8Array(encoderAwareness, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients))\n broadcastRoomMessage(this, encoding.toUint8Array(encoderAwareness))\n }\n\n this._beforeUnloadHandler = () => {\n awarenessProtocol.removeAwarenessStates(this.awareness, [doc.clientID], 'window unload')\n rooms.forEach(room => {\n room.disconnect()\n })\n }\n\n if (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', this._beforeUnloadHandler)\n } else if (typeof process !== 'undefined') {\n process.on('exit', this._beforeUnloadHandler)\n }\n }\n\n connect () {\n this.doc.on('update', this._docUpdateHandler)\n this.awareness.on('update', this._awarenessUpdateHandler)\n // signal through all available signaling connections\n announceSignalingInfo(this)\n const roomName = this.name\n bc.subscribe(roomName, this._bcSubscriber)\n this.bcconnected = true\n // broadcast peerId via broadcastchannel\n broadcastBcPeerId(this)\n // write sync step 1\n const encoderSync = encoding.createEncoder()\n encoding.writeVarUint(encoderSync, messageSync)\n syncProtocol.writeSyncStep1(encoderSync, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderSync))\n // broadcast local state\n const encoderState = encoding.createEncoder()\n encoding.writeVarUint(encoderState, messageSync)\n syncProtocol.writeSyncStep2(encoderState, this.doc)\n broadcastBcMessage(this, encoding.toUint8Array(encoderState))\n // write queryAwareness\n const encoderAwarenessQuery = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness)\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessQuery))\n // broadcast local awareness state\n const encoderAwarenessState = encoding.createEncoder()\n encoding.writeVarUint(encoderAwarenessState, messageAwareness)\n encoding.writeVarUint8Array(encoderAwarenessState, awarenessProtocol.encodeAwarenessUpdate(this.awareness, [this.doc.clientID]))\n broadcastBcMessage(this, encoding.toUint8Array(encoderAwarenessState))\n }\n\n disconnect () {\n // signal through all available signaling connections\n signalingConns.forEach(conn => {\n if (conn.connected) {\n conn.send({ type: 'unsubscribe', topics: [this.name] })\n }\n })\n awarenessProtocol.removeAwarenessStates(this.awareness, [this.doc.clientID], 'disconnect')\n // broadcast peerId removal via broadcastchannel\n const encoderPeerIdBc = encoding.createEncoder()\n encoding.writeVarUint(encoderPeerIdBc, messageBcPeerId)\n encoding.writeUint8(encoderPeerIdBc, 0) // remove peerId from other bc peers\n encoding.writeVarString(encoderPeerIdBc, this.peerId)\n broadcastBcMessage(this, encoding.toUint8Array(encoderPeerIdBc))\n\n bc.unsubscribe(this.name, this._bcSubscriber)\n this.bcconnected = false\n this.doc.off('update', this._docUpdateHandler)\n this.awareness.off('update', this._awarenessUpdateHandler)\n this.webrtcConns.forEach(conn => conn.destroy())\n }\n\n destroy () {\n this.disconnect()\n if (typeof window !== 'undefined') {\n window.removeEventListener('beforeunload', this._beforeUnloadHandler)\n } else if (typeof process !== 'undefined') {\n process.off('exit', this._beforeUnloadHandler)\n }\n }\n}\n\n/**\n * @param {Y.Doc} doc\n * @param {WebrtcProvider} provider\n * @param {string} name\n * @param {CryptoKey|null} key\n * @return {Room}\n */\nconst openRoom = (doc, provider, name, key) => {\n // there must only be one room\n if (rooms.has(name)) {\n throw error.create(`A Yjs Doc connected to room \"${name}\" already exists!`)\n }\n const room = new Room(doc, provider, name, key)\n rooms.set(name, /** @type {Room} */ (room))\n return room\n}\n\n/**\n * @param {SignalingConn} conn\n * @param {Room} room\n * @param {any} data\n */\nconst publishSignalingMessage = (conn, room, data) => {\n if (room.key) {\n cryptoutils.encryptJson(data, room.key).then(data => {\n conn.send({ type: 'publish', topic: room.name, data: buffer.toBase64(data) })\n })\n } else {\n conn.send({ type: 'publish', topic: room.name, data })\n }\n}\n\nexport class SignalingConn extends ws.WebsocketClient {\n constructor (url) {\n super(url)\n /**\n * @type {Set}\n */\n this.providers = new Set()\n this.on('connect', () => {\n log(`connected (${url})`)\n const topics = Array.from(rooms.keys())\n this.send({ type: 'subscribe', topics })\n rooms.forEach(room =>\n publishSignalingMessage(this, room, { type: 'announce', from: room.peerId })\n )\n })\n this.on('message', m => {\n switch (m.type) {\n case 'publish': {\n const roomName = m.topic\n const room = rooms.get(roomName)\n if (room == null || typeof roomName !== 'string') {\n return\n }\n const execMessage = data => {\n const webrtcConns = room.webrtcConns\n const peerId = room.peerId\n if (data == null || data.from === peerId || (data.to !== undefined && data.to !== peerId) || room.bcConns.has(data.from)) {\n // ignore messages that are not addressed to this conn, or from clients that are connected via broadcastchannel\n return\n }\n const emitPeerChange = webrtcConns.has(data.from)\n ? () => {}\n : () =>\n room.provider.emit('peers', [{\n removed: [],\n added: [data.from],\n webrtcPeers: Array.from(room.webrtcConns.keys()),\n bcPeers: Array.from(room.bcConns)\n }])\n switch (data.type) {\n case 'announce':\n if (webrtcConns.size < room.provider.maxConns) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, true, data.from, room))\n emitPeerChange()\n }\n break\n case 'signal':\n if (data.signal.type === 'offer') {\n const existingConn = webrtcConns.get(data.from)\n if (existingConn) {\n const remoteToken = data.token\n const localToken = existingConn.glareToken\n if (localToken && localToken > remoteToken) {\n log('offer rejected: ', data.from)\n return\n }\n // if we don't reject the offer, we will be accepting it and answering it\n existingConn.glareToken = undefined\n }\n }\n if (data.signal.type === 'answer') {\n log('offer answered by: ', data.from)\n const existingConn = webrtcConns.get(data.from)\n existingConn.glareToken = undefined\n }\n if (data.to === peerId) {\n map.setIfUndefined(webrtcConns, data.from, () => new WebrtcConn(this, false, data.from, room)).peer.signal(data.signal)\n emitPeerChange()\n }\n break\n }\n }\n if (room.key) {\n if (typeof m.data === 'string') {\n cryptoutils.decryptJson(buffer.fromBase64(m.data), room.key).then(execMessage)\n }\n } else {\n execMessage(m.data)\n }\n }\n }\n })\n this.on('disconnect', () => log(`disconnect (${url})`))\n }\n}\n\n/**\n * @typedef {Object} ProviderOptions\n * @property {Array} [signaling]\n * @property {string} [password]\n * @property {awarenessProtocol.Awareness} [awareness]\n * @property {number} [maxConns]\n * @property {boolean} [filterBcConns]\n * @property {any} [peerOpts]\n */\n\n/**\n * @param {WebrtcProvider} provider\n */\nconst emitStatus = provider => {\n provider.emit('status', [{\n connected: provider.connected\n }])\n}\n\n/**\n * @typedef {Object} WebrtcProviderEvents\n * @property {function({connected:boolean}):void} WebrtcProviderEvent.status\n * @property {function({synced:boolean}):void} WebrtcProviderEvent.synced\n * @property {function({added:Array,removed:Array,webrtcPeers:Array,bcPeers:Array}):void} WebrtcProviderEvent.peers\n */\n\n/**\n * @extends ObservableV2\n */\nexport class WebrtcProvider extends ObservableV2 {\n /**\n * @param {string} roomName\n * @param {Y.Doc} doc\n * @param {ProviderOptions?} opts\n */\n constructor (\n roomName,\n doc,\n {\n signaling = ['wss://y-webrtc-eu.fly.dev'],\n password = null,\n awareness = new awarenessProtocol.Awareness(doc),\n maxConns = 20 + math.floor(random.rand() * 15), // the random factor reduces the chance that n clients form a cluster\n filterBcConns = true,\n peerOpts = {} // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts\n } = {}\n ) {\n super()\n this.roomName = roomName\n this.doc = doc\n this.filterBcConns = filterBcConns\n /**\n * @type {awarenessProtocol.Awareness}\n */\n this.awareness = awareness\n this.shouldConnect = false\n this.signalingUrls = signaling\n this.signalingConns = []\n this.maxConns = maxConns\n this.peerOpts = peerOpts\n /**\n * @type {PromiseLike}\n */\n this.key = password ? cryptoutils.deriveKey(password, roomName) : /** @type {PromiseLike} */ (promise.resolve(null))\n /**\n * @type {Room|null}\n */\n this.room = null\n this.key.then(key => {\n this.room = openRoom(doc, this, roomName, key)\n if (this.shouldConnect) {\n this.room.connect()\n } else {\n this.room.disconnect()\n }\n emitStatus(this)\n })\n this.connect()\n this.destroy = this.destroy.bind(this)\n doc.on('destroy', this.destroy)\n }\n\n /**\n * Indicates whether the provider is looking for other peers.\n *\n * Other peers can be found via signaling servers or via broadcastchannel (cross browser-tab\n * communication). You never know when you are connected to all peers. You also don't know if\n * there are other peers. connected doesn't mean that you are connected to any physical peers\n * working on the same resource as you. It does not change unless you call provider.disconnect()\n *\n * `this.on('status', (event) => { console.log(event.connected) })`\n *\n * @type {boolean}\n */\n get connected () {\n return this.room !== null && this.shouldConnect\n }\n\n connect () {\n this.shouldConnect = true\n this.signalingUrls.forEach(url => {\n const signalingConn = map.setIfUndefined(signalingConns, url, () => new SignalingConn(url))\n this.signalingConns.push(signalingConn)\n signalingConn.providers.add(this)\n })\n if (this.room) {\n this.room.connect()\n emitStatus(this)\n }\n }\n\n disconnect () {\n this.shouldConnect = false\n this.signalingConns.forEach(conn => {\n conn.providers.delete(this)\n if (conn.providers.size === 0) {\n conn.destroy()\n signalingConns.delete(conn.url)\n }\n })\n if (this.room) {\n this.room.disconnect()\n emitStatus(this)\n }\n }\n\n destroy () {\n this.doc.off('destroy', this.destroy)\n // need to wait for key before deleting room\n this.key.then(() => {\n /** @type {Room} */ (this.room).destroy()\n rooms.delete(this.roomName)\n })\n super.destroy()\n }\n}\n", "/* eslint-env browser */\n\n/**\n * Helpers to work with IndexedDB.\n *\n * @module indexeddb\n */\n\nimport * as promise from './promise.js'\nimport * as error from './error.js'\n\n/* c8 ignore start */\n\n/**\n * IDB Request to Promise transformer\n *\n * @param {IDBRequest} request\n * @return {Promise}\n */\nexport const rtop = request => promise.create((resolve, reject) => {\n // @ts-ignore\n request.onerror = event => reject(new Error(event.target.error))\n // @ts-ignore\n request.onsuccess = event => resolve(event.target.result)\n})\n\n/**\n * @param {string} name\n * @param {function(IDBDatabase):any} initDB Called when the database is first created\n * @return {Promise}\n */\nexport const openDB = (name, initDB) => promise.create((resolve, reject) => {\n const request = indexedDB.open(name)\n /**\n * @param {any} event\n */\n request.onupgradeneeded = event => initDB(event.target.result)\n /**\n * @param {any} event\n */\n request.onerror = event => reject(error.create(event.target.error))\n /**\n * @param {any} event\n */\n request.onsuccess = event => {\n /**\n * @type {IDBDatabase}\n */\n const db = event.target.result\n db.onversionchange = () => { db.close() }\n resolve(db)\n }\n})\n\n/**\n * @param {string} name\n */\nexport const deleteDB = name => rtop(indexedDB.deleteDatabase(name))\n\n/**\n * @param {IDBDatabase} db\n * @param {Array|Array>} definitions\n */\nexport const createStores = (db, definitions) => definitions.forEach(d =>\n // @ts-ignore\n db.createObjectStore.apply(db, d)\n)\n\n/**\n * @param {IDBDatabase} db\n * @param {Array} stores\n * @param {\"readwrite\"|\"readonly\"} [access]\n * @return {Array}\n */\nexport const transact = (db, stores, access = 'readwrite') => {\n const transaction = db.transaction(stores, access)\n return stores.map(store => getStore(transaction, store))\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @return {Promise}\n */\nexport const count = (store, range) =>\n rtop(store.count(range))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | Array } key\n * @return {Promise>}\n */\nexport const get = (store, key) =>\n rtop(store.get(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key\n */\nexport const del = (store, key) =>\n rtop(store.delete(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} [key]\n */\nexport const put = (store, item, key) =>\n rtop(store.put(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} key\n * @return {Promise}\n */\nexport const add = (store, item, key) =>\n rtop(store.add(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date} item\n * @return {Promise} Returns the generated key\n */\nexport const addAutoKey = (store, item) =>\n rtop(store.add(item))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAll = (store, range, limit) =>\n rtop(store.getAll(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeys = (store, range, limit) =>\n rtop(store.getAllKeys(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} query\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n * @return {Promise}\n */\nexport const queryFirst = (store, query, direction) => {\n /**\n * @type {any}\n */\n let first = null\n return iterateKeys(store, query, key => {\n first = key\n return false\n }, direction).then(() => first)\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getLastKey = (store, range = null) => queryFirst(store, range, 'prev')\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getFirstKey = (store, range = null) => queryFirst(store, range, 'next')\n\n/**\n * @typedef KeyValuePair\n * @type {Object}\n * @property {any} k key\n * @property {any} v Value\n */\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeysValues = (store, range, limit) =>\n // @ts-ignore\n promise.all([getAllKeys(store, range, limit), getAll(store, range, limit)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] })))\n\n/**\n * @param {any} request\n * @param {function(IDBCursorWithValue):void|boolean|Promise} f\n * @return {Promise}\n */\nconst iterateOnRequest = (request, f) => promise.create((resolve, reject) => {\n request.onerror = reject\n /**\n * @param {any} event\n */\n request.onsuccess = async event => {\n const cursor = event.target.result\n if (cursor === null || (await f(cursor)) === false) {\n return resolve()\n }\n cursor.continue()\n }\n})\n\n/**\n * Iterate on keys and values\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any,any):void|boolean|Promise} f Callback that receives (value, key)\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterate = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openCursor(keyrange, direction), cursor => f(cursor.value, cursor.key))\n\n/**\n * Iterate on the keys (no values)\n *\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any):void|boolean|Promise} f callback that receives the key\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterateKeys = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openKeyCursor(keyrange, direction), cursor => f(cursor.key))\n\n/**\n * Open store from transaction\n * @param {IDBTransaction} t\n * @param {String} store\n * @returns {IDBObjectStore}\n */\nexport const getStore = (t, store) => t.objectStore(store)\n\n/**\n * @param {any} lower\n * @param {any} upper\n * @param {boolean} lowerOpen\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen)\n\n/**\n * @param {any} upper\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen)\n\n/**\n * @param {any} lower\n * @param {boolean} lowerOpen\n */\nexport const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen)\n\n/* c8 ignore stop */\n", "import * as Y from 'yjs'\nimport * as idb from 'lib0/indexeddb'\nimport * as promise from 'lib0/promise'\nimport { Observable } from 'lib0/observable'\n\nconst customStoreName = 'custom'\nconst updatesStoreName = 'updates'\n\nexport const PREFERRED_TRIM_SIZE = 500\n\n/**\n * @param {IndexeddbPersistence} idbPersistence\n * @param {function(IDBObjectStore):void} [beforeApplyUpdatesCallback]\n * @param {function(IDBObjectStore):void} [afterApplyUpdatesCallback]\n */\nexport const fetchUpdates = (idbPersistence, beforeApplyUpdatesCallback = () => {}, afterApplyUpdatesCallback = () => {}) => {\n const [updatesStore] = idb.transact(/** @type {IDBDatabase} */ (idbPersistence.db), [updatesStoreName]) // , 'readonly')\n return idb.getAll(updatesStore, idb.createIDBKeyRangeLowerBound(idbPersistence._dbref, false)).then(updates => {\n if (!idbPersistence._destroyed) {\n beforeApplyUpdatesCallback(updatesStore)\n Y.transact(idbPersistence.doc, () => {\n updates.forEach(val => Y.applyUpdate(idbPersistence.doc, val))\n }, idbPersistence, false)\n afterApplyUpdatesCallback(updatesStore)\n }\n })\n .then(() => idb.getLastKey(updatesStore).then(lastKey => { idbPersistence._dbref = lastKey + 1 }))\n .then(() => idb.count(updatesStore).then(cnt => { idbPersistence._dbsize = cnt }))\n .then(() => updatesStore)\n}\n\n/**\n * @param {IndexeddbPersistence} idbPersistence\n * @param {boolean} forceStore\n */\nexport const storeState = (idbPersistence, forceStore = true) =>\n fetchUpdates(idbPersistence)\n .then(updatesStore => {\n if (forceStore || idbPersistence._dbsize >= PREFERRED_TRIM_SIZE) {\n idb.addAutoKey(updatesStore, Y.encodeStateAsUpdate(idbPersistence.doc))\n .then(() => idb.del(updatesStore, idb.createIDBKeyRangeUpperBound(idbPersistence._dbref, true)))\n .then(() => idb.count(updatesStore).then(cnt => { idbPersistence._dbsize = cnt }))\n }\n })\n\n/**\n * @param {string} name\n */\nexport const clearDocument = name => idb.deleteDB(name)\n\n/**\n * @extends Observable\n */\nexport class IndexeddbPersistence extends Observable {\n /**\n * @param {string} name\n * @param {Y.Doc} doc\n */\n constructor (name, doc) {\n super()\n this.doc = doc\n this.name = name\n this._dbref = 0\n this._dbsize = 0\n this._destroyed = false\n /**\n * @type {IDBDatabase|null}\n */\n this.db = null\n this.synced = false\n this._db = idb.openDB(name, db =>\n idb.createStores(db, [\n ['updates', { autoIncrement: true }],\n ['custom']\n ])\n )\n /**\n * @type {Promise}\n */\n this.whenSynced = promise.create(resolve => this.on('synced', () => resolve(this)))\n\n this._db.then(db => {\n this.db = db\n /**\n * @param {IDBObjectStore} updatesStore\n */\n const beforeApplyUpdatesCallback = (updatesStore) => idb.addAutoKey(updatesStore, Y.encodeStateAsUpdate(doc))\n const afterApplyUpdatesCallback = () => {\n if (this._destroyed) return this\n this.synced = true\n this.emit('synced', [this])\n }\n fetchUpdates(this, beforeApplyUpdatesCallback, afterApplyUpdatesCallback)\n })\n /**\n * Timeout in ms untill data is merged and persisted in idb.\n */\n this._storeTimeout = 1000\n /**\n * @type {any}\n */\n this._storeTimeoutId = null\n /**\n * @param {Uint8Array} update\n * @param {any} origin\n */\n this._storeUpdate = (update, origin) => {\n if (this.db && origin !== this) {\n const [updatesStore] = idb.transact(/** @type {IDBDatabase} */ (this.db), [updatesStoreName])\n idb.addAutoKey(updatesStore, update)\n if (++this._dbsize >= PREFERRED_TRIM_SIZE) {\n // debounce store call\n if (this._storeTimeoutId !== null) {\n clearTimeout(this._storeTimeoutId)\n }\n this._storeTimeoutId = setTimeout(() => {\n storeState(this, false)\n this._storeTimeoutId = null\n }, this._storeTimeout)\n }\n }\n }\n doc.on('update', this._storeUpdate)\n this.destroy = this.destroy.bind(this)\n doc.on('destroy', this.destroy)\n }\n\n destroy () {\n if (this._storeTimeoutId) {\n clearTimeout(this._storeTimeoutId)\n }\n this.doc.off('update', this._storeUpdate)\n this.doc.off('destroy', this.destroy)\n this._destroyed = true\n return this._db.then(db => {\n db.close()\n })\n }\n\n /**\n * Destroys this instance and removes all data from indexeddb.\n *\n * @return {Promise}\n */\n clearData () {\n return this.destroy().then(() => {\n idb.deleteDB(this.name)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @return {Promise}\n */\n get (key) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName], 'readonly')\n return idb.get(custom, key)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @param {String | number | ArrayBuffer | Date} value\n * @return {Promise}\n */\n set (key, value) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName])\n return idb.put(custom, value, key)\n })\n }\n\n /**\n * @param {String | number | ArrayBuffer | Date} key\n * @return {Promise}\n */\n del (key) {\n return this._db.then(db => {\n const [custom] = idb.transact(db, [customStoreName])\n return idb.del(custom, key)\n })\n }\n}\n", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}\n\n/*# sourceMappingURL=quill.core.css.map*/", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}.ql-bubble.ql-toolbar:after,.ql-bubble .ql-toolbar:after{clear:both;content:'';display:table}.ql-bubble.ql-toolbar button,.ql-bubble .ql-toolbar button{background:none;border:none;cursor:pointer;display:inline-block;float:left;height:24px;padding:3px 5px;width:28px}.ql-bubble.ql-toolbar button svg,.ql-bubble .ql-toolbar button svg{float:left;height:100%}.ql-bubble.ql-toolbar button:active:hover,.ql-bubble .ql-toolbar button:active:hover{outline:none}.ql-bubble.ql-toolbar input.ql-image[type=file],.ql-bubble .ql-toolbar input.ql-image[type=file]{display:none}.ql-bubble.ql-toolbar button:hover,.ql-bubble .ql-toolbar button:hover,.ql-bubble.ql-toolbar button:focus,.ql-bubble .ql-toolbar button:focus,.ql-bubble.ql-toolbar button.ql-active,.ql-bubble .ql-toolbar button.ql-active,.ql-bubble.ql-toolbar .ql-picker-label:hover,.ql-bubble .ql-toolbar .ql-picker-label:hover,.ql-bubble.ql-toolbar .ql-picker-label.ql-active,.ql-bubble .ql-toolbar .ql-picker-label.ql-active,.ql-bubble.ql-toolbar .ql-picker-item:hover,.ql-bubble .ql-toolbar .ql-picker-item:hover,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected{color:#fff}.ql-bubble.ql-toolbar button:hover .ql-fill,.ql-bubble .ql-toolbar button:hover .ql-fill,.ql-bubble.ql-toolbar button:focus .ql-fill,.ql-bubble .ql-toolbar button:focus .ql-fill,.ql-bubble.ql-toolbar button.ql-active .ql-fill,.ql-bubble .ql-toolbar button.ql-active .ql-fill,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-fill,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-fill,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-fill,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-fill,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-bubble.ql-toolbar button:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar button:focus .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:focus .ql-stroke.ql-fill,.ql-bubble.ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill{fill:#fff}.ql-bubble.ql-toolbar button:hover .ql-stroke,.ql-bubble .ql-toolbar button:hover .ql-stroke,.ql-bubble.ql-toolbar button:focus .ql-stroke,.ql-bubble .ql-toolbar button:focus .ql-stroke,.ql-bubble.ql-toolbar button.ql-active .ql-stroke,.ql-bubble .ql-toolbar button.ql-active .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-bubble.ql-toolbar button:hover .ql-stroke-miter,.ql-bubble .ql-toolbar button:hover .ql-stroke-miter,.ql-bubble.ql-toolbar button:focus .ql-stroke-miter,.ql-bubble .ql-toolbar button:focus .ql-stroke-miter,.ql-bubble.ql-toolbar button.ql-active .ql-stroke-miter,.ql-bubble .ql-toolbar button.ql-active .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-bubble.ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-bubble .ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter{stroke:#fff}@media (pointer:coarse){.ql-bubble.ql-toolbar button:hover:not(.ql-active),.ql-bubble .ql-toolbar button:hover:not(.ql-active){color:#ccc}.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill{fill:#ccc}.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-bubble.ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter,.ql-bubble .ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter{stroke:#ccc}}.ql-bubble{box-sizing:border-box}.ql-bubble *{box-sizing:border-box}.ql-bubble .ql-hidden{display:none}.ql-bubble .ql-out-bottom,.ql-bubble .ql-out-top{visibility:hidden}.ql-bubble .ql-tooltip{position:absolute;transform:translateY(10px)}.ql-bubble .ql-tooltip a{cursor:pointer;text-decoration:none}.ql-bubble .ql-tooltip.ql-flip{transform:translateY(-10px)}.ql-bubble .ql-formats{display:inline-block;vertical-align:middle}.ql-bubble .ql-formats:after{clear:both;content:'';display:table}.ql-bubble .ql-stroke{fill:none;stroke:#ccc;stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.ql-bubble .ql-stroke-miter{fill:none;stroke:#ccc;stroke-miterlimit:10;stroke-width:2}.ql-bubble .ql-fill,.ql-bubble .ql-stroke.ql-fill{fill:#ccc}.ql-bubble .ql-empty{fill:none}.ql-bubble .ql-even{fill-rule:evenodd}.ql-bubble .ql-thin,.ql-bubble .ql-stroke.ql-thin{stroke-width:1}.ql-bubble .ql-transparent{opacity:.4}.ql-bubble .ql-direction svg:last-child{display:none}.ql-bubble .ql-direction.ql-active svg:last-child{display:inline}.ql-bubble .ql-direction.ql-active svg:first-child{display:none}.ql-bubble .ql-editor h1{font-size:2em}.ql-bubble .ql-editor h2{font-size:1.5em}.ql-bubble .ql-editor h3{font-size:1.17em}.ql-bubble .ql-editor h4{font-size:1em}.ql-bubble .ql-editor h5{font-size:.83em}.ql-bubble .ql-editor h6{font-size:.67em}.ql-bubble .ql-editor a{text-decoration:underline}.ql-bubble .ql-editor blockquote{border-left:4px solid #ccc;margin-bottom:5px;margin-top:5px;padding-left:16px}.ql-bubble .ql-editor code,.ql-bubble .ql-editor .ql-code-block-container{background-color:#f0f0f0;border-radius:3px}.ql-bubble .ql-editor .ql-code-block-container{margin-bottom:5px;margin-top:5px;padding:5px 10px}.ql-bubble .ql-editor code{font-size:85%;padding:2px 4px}.ql-bubble .ql-editor .ql-code-block-container{background-color:#23241f;color:#f8f8f2;overflow:visible}.ql-bubble .ql-editor img{max-width:100%}.ql-bubble .ql-picker{color:#ccc;display:inline-block;float:left;font-size:14px;font-weight:500;height:24px;position:relative;vertical-align:middle}.ql-bubble .ql-picker-label{cursor:pointer;display:inline-block;height:100%;padding-left:8px;padding-right:2px;position:relative;width:100%}.ql-bubble .ql-picker-label::before{display:inline-block;line-height:22px}.ql-bubble .ql-picker-options{background-color:#444;display:none;min-width:100%;padding:4px 8px;position:absolute;white-space:nowrap}.ql-bubble .ql-picker-options .ql-picker-item{cursor:pointer;display:block;padding-bottom:5px;padding-top:5px}.ql-bubble .ql-picker.ql-expanded .ql-picker-label{color:#777;z-index:2}.ql-bubble .ql-picker.ql-expanded .ql-picker-label .ql-fill{fill:#777}.ql-bubble .ql-picker.ql-expanded .ql-picker-label .ql-stroke{stroke:#777}.ql-bubble .ql-picker.ql-expanded .ql-picker-options{display:block;margin-top:-1px;top:100%;z-index:1}.ql-bubble .ql-color-picker,.ql-bubble .ql-icon-picker{width:28px}.ql-bubble .ql-color-picker .ql-picker-label,.ql-bubble .ql-icon-picker .ql-picker-label{padding:2px 4px}.ql-bubble .ql-color-picker .ql-picker-label svg,.ql-bubble .ql-icon-picker .ql-picker-label svg{right:4px}.ql-bubble .ql-icon-picker .ql-picker-options{padding:4px 0}.ql-bubble .ql-icon-picker .ql-picker-item{height:24px;width:24px;padding:2px 4px}.ql-bubble .ql-color-picker .ql-picker-options{padding:3px 5px;width:152px}.ql-bubble .ql-color-picker .ql-picker-item{border:1px solid transparent;float:left;height:16px;margin:2px;padding:0;width:16px}.ql-bubble .ql-picker:not(.ql-color-picker):not(.ql-icon-picker) svg{position:absolute;margin-top:-9px;right:0;top:50%;width:18px}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-font .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-size .ql-picker-label[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-label]:not([data-label=''])::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-label]:not([data-label=''])::before{content:attr(data-label)}.ql-bubble .ql-picker.ql-header{width:98px}.ql-bubble .ql-picker.ql-header .ql-picker-label::before,.ql-bubble .ql-picker.ql-header .ql-picker-item::before{content:'Normal'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"1\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{content:'Heading 1'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"2\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{content:'Heading 2'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"3\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{content:'Heading 3'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"4\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{content:'Heading 4'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"5\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{content:'Heading 5'}.ql-bubble .ql-picker.ql-header .ql-picker-label[data-value=\"6\"]::before,.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{content:'Heading 6'}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{font-size:2em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{font-size:1.5em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{font-size:1.17em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{font-size:1em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{font-size:.83em}.ql-bubble .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{font-size:.67em}.ql-bubble .ql-picker.ql-font{width:108px}.ql-bubble .ql-picker.ql-font .ql-picker-label::before,.ql-bubble .ql-picker.ql-font .ql-picker-item::before{content:'Sans Serif'}.ql-bubble .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{content:'Serif'}.ql-bubble .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{content:'Monospace'}.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{font-family:Georgia,Times New Roman,serif}.ql-bubble .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{font-family:Monaco,Courier New,monospace}.ql-bubble .ql-picker.ql-size{width:98px}.ql-bubble .ql-picker.ql-size .ql-picker-label::before,.ql-bubble .ql-picker.ql-size .ql-picker-item::before{content:'Normal'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=small]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=small]::before{content:'Small'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=large]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=large]::before{content:'Large'}.ql-bubble .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{content:'Huge'}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=small]::before{font-size:10px}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=large]::before{font-size:18px}.ql-bubble .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{font-size:32px}.ql-bubble .ql-color-picker.ql-background .ql-picker-item{background-color:#fff}.ql-bubble .ql-color-picker.ql-color .ql-picker-item{background-color:#000}.ql-code-block-container{position:relative}.ql-code-block-container .ql-ui{right:5px;top:5px}.ql-bubble .ql-toolbar .ql-formats{margin:8px 12px 8px 0}.ql-bubble .ql-toolbar .ql-formats:first-child{margin-left:12px}.ql-bubble .ql-color-picker svg{margin:1px}.ql-bubble .ql-color-picker .ql-picker-item.ql-selected,.ql-bubble .ql-color-picker .ql-picker-item:hover{border-color:#fff}.ql-bubble .ql-tooltip{background-color:#444;border-radius:25px;color:#fff}.ql-bubble .ql-tooltip-arrow{border-left:6px solid transparent;border-right:6px solid transparent;content:\" \";display:block;left:50%;margin-left:-6px;position:absolute}.ql-bubble .ql-tooltip:not(.ql-flip) .ql-tooltip-arrow{border-bottom:6px solid #444;top:-6px}.ql-bubble .ql-tooltip.ql-flip .ql-tooltip-arrow{border-top:6px solid #444;bottom:-6px}.ql-bubble .ql-tooltip.ql-editing .ql-tooltip-editor{display:block}.ql-bubble .ql-tooltip.ql-editing .ql-formats{visibility:hidden}.ql-bubble .ql-tooltip-editor{display:none}.ql-bubble .ql-tooltip-editor input[type=text]{background:transparent;border:none;color:#fff;font-size:13px;height:100%;outline:none;padding:10px 20px;position:absolute;width:100%}.ql-bubble .ql-tooltip-editor a{top:10px;position:absolute;right:20px}.ql-bubble .ql-tooltip-editor a:before{color:#ccc;content:\"\\00D7\";font-size:16px;font-weight:bold}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close){position:relative;white-space:nowrap}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::before{background-color:#444;border-radius:15px;top:-5px;font-size:12px;color:#fff;content:attr(href);font-weight:normal;overflow:hidden;padding:5px 15px;text-decoration:none;z-index:1}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::after{border-top:6px solid #444;border-left:6px solid transparent;border-right:6px solid transparent;top:0;content:\" \";height:0;width:0}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::before,.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close)::after{left:0;margin-left:50%;position:absolute;transform:translate(-50%,-100%);transition:visibility 0s ease 200ms;visibility:hidden}.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close):hover::before,.ql-container.ql-bubble:not(.ql-disabled) a:not(.ql-close):hover::after{visibility:visible}\n\n/*# sourceMappingURL=quill.bubble.css.map*/", "/*!\n * Quill Editor v2.0.2\n * https://quilljs.com\n * Copyright (c) 2017-2024, Slab\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */\n.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:100%;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container:not(.ql-disabled) li[data-list=checked] > .ql-ui,.ql-container:not(.ql-disabled) li[data-list=unchecked] > .ql-ui{cursor:pointer}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor > *{cursor:text}.ql-editor p,.ql-editor ol,.ql-editor pre,.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{margin:0;padding:0}@supports (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-set:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor p,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6{counter-reset:list-0 list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor table{border-collapse:collapse}.ql-editor td{border:1px solid #000;padding:2px 5px}.ql-editor ol{padding-left:1.5em}.ql-editor li{list-style-type:none;padding-left:1.5em;position:relative}.ql-editor li > .ql-ui:before{display:inline-block;margin-left:-1.5em;margin-right:.3em;text-align:right;white-space:nowrap;width:1.2em}.ql-editor li[data-list=checked] > .ql-ui,.ql-editor li[data-list=unchecked] > .ql-ui{color:#777}.ql-editor li[data-list=bullet] > .ql-ui:before{content:'\\2022'}.ql-editor li[data-list=checked] > .ql-ui:before{content:'\\2611'}.ql-editor li[data-list=unchecked] > .ql-ui:before{content:'\\2610'}@supports (counter-set:none){.ql-editor li[data-list]{counter-set:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list]{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered]{counter-increment:list-0}.ql-editor li[data-list=ordered] > .ql-ui:before{content:counter(list-0, decimal) '. '}.ql-editor li[data-list=ordered].ql-indent-1{counter-increment:list-1}.ql-editor li[data-list=ordered].ql-indent-1 > .ql-ui:before{content:counter(list-1, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-set:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-2{counter-increment:list-2}.ql-editor li[data-list=ordered].ql-indent-2 > .ql-ui:before{content:counter(list-2, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-set:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-3{counter-increment:list-3}.ql-editor li[data-list=ordered].ql-indent-3 > .ql-ui:before{content:counter(list-3, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-set:list-4 list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-4{counter-increment:list-4}.ql-editor li[data-list=ordered].ql-indent-4 > .ql-ui:before{content:counter(list-4, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-set:list-5 list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-5{counter-increment:list-5}.ql-editor li[data-list=ordered].ql-indent-5 > .ql-ui:before{content:counter(list-5, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-set:list-6 list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-6{counter-increment:list-6}.ql-editor li[data-list=ordered].ql-indent-6 > .ql-ui:before{content:counter(list-6, decimal) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-set:list-7 list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-6{counter-reset:list-7 list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-7{counter-increment:list-7}.ql-editor li[data-list=ordered].ql-indent-7 > .ql-ui:before{content:counter(list-7, lower-alpha) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-set:list-8 list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-7{counter-reset:list-8 list-9}}.ql-editor li[data-list=ordered].ql-indent-8{counter-increment:list-8}.ql-editor li[data-list=ordered].ql-indent-8 > .ql-ui:before{content:counter(list-8, lower-roman) '. '}@supports (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-set:list-9}}@supports not (counter-set:none){.ql-editor li[data-list].ql-indent-8{counter-reset:list-9}}.ql-editor li[data-list=ordered].ql-indent-9{counter-increment:list-9}.ql-editor li[data-list=ordered].ql-indent-9 > .ql-ui:before{content:counter(list-9, decimal) '. '}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor li.ql-direction-rtl{padding-right:1.5em}.ql-editor li.ql-direction-rtl > .ql-ui:before{margin-left:.3em;margin-right:-1.5em;text-align:left}.ql-editor table{table-layout:fixed;width:100%}.ql-editor table td{outline:none}.ql-editor .ql-code-block-container{font-family:monospace}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor .ql-ui{position:absolute}.ql-editor.ql-blank::before{color:rgba(0,0,0,0.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}.ql-snow.ql-toolbar:after,.ql-snow .ql-toolbar:after{clear:both;content:'';display:table}.ql-snow.ql-toolbar button,.ql-snow .ql-toolbar button{background:none;border:none;cursor:pointer;display:inline-block;float:left;height:24px;padding:3px 5px;width:28px}.ql-snow.ql-toolbar button svg,.ql-snow .ql-toolbar button svg{float:left;height:100%}.ql-snow.ql-toolbar button:active:hover,.ql-snow .ql-toolbar button:active:hover{outline:none}.ql-snow.ql-toolbar input.ql-image[type=file],.ql-snow .ql-toolbar input.ql-image[type=file]{display:none}.ql-snow.ql-toolbar button:hover,.ql-snow .ql-toolbar button:hover,.ql-snow.ql-toolbar button:focus,.ql-snow .ql-toolbar button:focus,.ql-snow.ql-toolbar button.ql-active,.ql-snow .ql-toolbar button.ql-active,.ql-snow.ql-toolbar .ql-picker-label:hover,.ql-snow .ql-toolbar .ql-picker-label:hover,.ql-snow.ql-toolbar .ql-picker-label.ql-active,.ql-snow .ql-toolbar .ql-picker-label.ql-active,.ql-snow.ql-toolbar .ql-picker-item:hover,.ql-snow .ql-toolbar .ql-picker-item:hover,.ql-snow.ql-toolbar .ql-picker-item.ql-selected,.ql-snow .ql-toolbar .ql-picker-item.ql-selected{color:#06c}.ql-snow.ql-toolbar button:hover .ql-fill,.ql-snow .ql-toolbar button:hover .ql-fill,.ql-snow.ql-toolbar button:focus .ql-fill,.ql-snow .ql-toolbar button:focus .ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow.ql-toolbar button:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill{fill:#06c}.ql-snow.ql-toolbar button:hover .ql-stroke,.ql-snow .ql-toolbar button:hover .ql-stroke,.ql-snow.ql-toolbar button:focus .ql-stroke,.ql-snow .ql-toolbar button:focus .ql-stroke,.ql-snow.ql-toolbar button.ql-active .ql-stroke,.ql-snow .ql-toolbar button.ql-active .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow.ql-toolbar button:hover .ql-stroke-miter,.ql-snow .ql-toolbar button:hover .ql-stroke-miter,.ql-snow.ql-toolbar button:focus .ql-stroke-miter,.ql-snow .ql-toolbar button:focus .ql-stroke-miter,.ql-snow.ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter{stroke:#06c}@media (pointer:coarse){.ql-snow.ql-toolbar button:hover:not(.ql-active),.ql-snow .ql-toolbar button:hover:not(.ql-active){color:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill{fill:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter{stroke:#444}}.ql-snow{box-sizing:border-box}.ql-snow *{box-sizing:border-box}.ql-snow .ql-hidden{display:none}.ql-snow .ql-out-bottom,.ql-snow .ql-out-top{visibility:hidden}.ql-snow .ql-tooltip{position:absolute;transform:translateY(10px)}.ql-snow .ql-tooltip a{cursor:pointer;text-decoration:none}.ql-snow .ql-tooltip.ql-flip{transform:translateY(-10px)}.ql-snow .ql-formats{display:inline-block;vertical-align:middle}.ql-snow .ql-formats:after{clear:both;content:'';display:table}.ql-snow .ql-stroke{fill:none;stroke:#444;stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.ql-snow .ql-stroke-miter{fill:none;stroke:#444;stroke-miterlimit:10;stroke-width:2}.ql-snow .ql-fill,.ql-snow .ql-stroke.ql-fill{fill:#444}.ql-snow .ql-empty{fill:none}.ql-snow .ql-even{fill-rule:evenodd}.ql-snow .ql-thin,.ql-snow .ql-stroke.ql-thin{stroke-width:1}.ql-snow .ql-transparent{opacity:.4}.ql-snow .ql-direction svg:last-child{display:none}.ql-snow .ql-direction.ql-active svg:last-child{display:inline}.ql-snow .ql-direction.ql-active svg:first-child{display:none}.ql-snow .ql-editor h1{font-size:2em}.ql-snow .ql-editor h2{font-size:1.5em}.ql-snow .ql-editor h3{font-size:1.17em}.ql-snow .ql-editor h4{font-size:1em}.ql-snow .ql-editor h5{font-size:.83em}.ql-snow .ql-editor h6{font-size:.67em}.ql-snow .ql-editor a{text-decoration:underline}.ql-snow .ql-editor blockquote{border-left:4px solid #ccc;margin-bottom:5px;margin-top:5px;padding-left:16px}.ql-snow .ql-editor code,.ql-snow .ql-editor .ql-code-block-container{background-color:#f0f0f0;border-radius:3px}.ql-snow .ql-editor .ql-code-block-container{margin-bottom:5px;margin-top:5px;padding:5px 10px}.ql-snow .ql-editor code{font-size:85%;padding:2px 4px}.ql-snow .ql-editor .ql-code-block-container{background-color:#23241f;color:#f8f8f2;overflow:visible}.ql-snow .ql-editor img{max-width:100%}.ql-snow .ql-picker{color:#444;display:inline-block;float:left;font-size:14px;font-weight:500;height:24px;position:relative;vertical-align:middle}.ql-snow .ql-picker-label{cursor:pointer;display:inline-block;height:100%;padding-left:8px;padding-right:2px;position:relative;width:100%}.ql-snow .ql-picker-label::before{display:inline-block;line-height:22px}.ql-snow .ql-picker-options{background-color:#fff;display:none;min-width:100%;padding:4px 8px;position:absolute;white-space:nowrap}.ql-snow .ql-picker-options .ql-picker-item{cursor:pointer;display:block;padding-bottom:5px;padding-top:5px}.ql-snow .ql-picker.ql-expanded .ql-picker-label{color:#ccc;z-index:2}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-fill{fill:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-stroke{stroke:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-options{display:block;margin-top:-1px;top:100%;z-index:1}.ql-snow .ql-color-picker,.ql-snow .ql-icon-picker{width:28px}.ql-snow .ql-color-picker .ql-picker-label,.ql-snow .ql-icon-picker .ql-picker-label{padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-label svg,.ql-snow .ql-icon-picker .ql-picker-label svg{right:4px}.ql-snow .ql-icon-picker .ql-picker-options{padding:4px 0}.ql-snow .ql-icon-picker .ql-picker-item{height:24px;width:24px;padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-options{padding:3px 5px;width:152px}.ql-snow .ql-color-picker .ql-picker-item{border:1px solid transparent;float:left;height:16px;margin:2px;padding:0;width:16px}.ql-snow .ql-picker:not(.ql-color-picker):not(.ql-icon-picker) svg{position:absolute;margin-top:-9px;right:0;top:50%;width:18px}.ql-snow .ql-picker.ql-header .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-font .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-label]:not([data-label=''])::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-label]:not([data-label=''])::before{content:attr(data-label)}.ql-snow .ql-picker.ql-header{width:98px}.ql-snow .ql-picker.ql-header .ql-picker-label::before,.ql-snow .ql-picker.ql-header .ql-picker-item::before{content:'Normal'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"1\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{content:'Heading 1'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"2\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{content:'Heading 2'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"3\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{content:'Heading 3'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"4\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{content:'Heading 4'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"5\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{content:'Heading 5'}.ql-snow .ql-picker.ql-header .ql-picker-label[data-value=\"6\"]::before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{content:'Heading 6'}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"1\"]::before{font-size:2em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"2\"]::before{font-size:1.5em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"3\"]::before{font-size:1.17em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"4\"]::before{font-size:1em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"5\"]::before{font-size:.83em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value=\"6\"]::before{font-size:.67em}.ql-snow .ql-picker.ql-font{width:108px}.ql-snow .ql-picker.ql-font .ql-picker-label::before,.ql-snow .ql-picker.ql-font .ql-picker-item::before{content:'Sans Serif'}.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{content:'Serif'}.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{content:'Monospace'}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before{font-family:Georgia,Times New Roman,serif}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before{font-family:Monaco,Courier New,monospace}.ql-snow .ql-picker.ql-size{width:98px}.ql-snow .ql-picker.ql-size .ql-picker-label::before,.ql-snow .ql-picker.ql-size .ql-picker-item::before{content:'Normal'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before{content:'Small'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before{content:'Large'}.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{content:'Huge'}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before{font-size:10px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before{font-size:18px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before{font-size:32px}.ql-snow .ql-color-picker.ql-background .ql-picker-item{background-color:#fff}.ql-snow .ql-color-picker.ql-color .ql-picker-item{background-color:#000}.ql-code-block-container{position:relative}.ql-code-block-container .ql-ui{right:5px;top:5px}.ql-toolbar.ql-snow{border:1px solid #ccc;box-sizing:border-box;font-family:'Helvetica Neue','Helvetica','Arial',sans-serif;padding:8px}.ql-toolbar.ql-snow .ql-formats{margin-right:15px}.ql-toolbar.ql-snow .ql-picker-label{border:1px solid transparent}.ql-toolbar.ql-snow .ql-picker-options{border:1px solid transparent;box-shadow:rgba(0,0,0,0.2) 0 2px 8px}.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-label{border-color:#ccc}.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options{border-color:#ccc}.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item.ql-selected,.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item:hover{border-color:#000}.ql-toolbar.ql-snow + .ql-container.ql-snow{border-top:0}.ql-snow .ql-tooltip{background-color:#fff;border:1px solid #ccc;box-shadow:0 0 5px #ddd;color:#444;padding:5px 12px;white-space:nowrap}.ql-snow .ql-tooltip::before{content:\"Visit URL:\";line-height:26px;margin-right:8px}.ql-snow .ql-tooltip input[type=text]{display:none;border:1px solid #ccc;font-size:13px;height:26px;margin:0;padding:3px 5px;width:170px}.ql-snow .ql-tooltip a.ql-preview{display:inline-block;max-width:200px;overflow-x:hidden;text-overflow:ellipsis;vertical-align:top}.ql-snow .ql-tooltip a.ql-action::after{border-right:1px solid #ccc;content:'Edit';margin-left:16px;padding-right:8px}.ql-snow .ql-tooltip a.ql-remove::before{content:'Remove';margin-left:8px}.ql-snow .ql-tooltip a{line-height:26px}.ql-snow .ql-tooltip.ql-editing a.ql-preview,.ql-snow .ql-tooltip.ql-editing a.ql-remove{display:none}.ql-snow .ql-tooltip.ql-editing input[type=text]{display:inline-block}.ql-snow .ql-tooltip.ql-editing a.ql-action::after{border-right:0;content:'Save';padding-right:0}.ql-snow .ql-tooltip[data-mode=link]::before{content:\"Enter link:\"}.ql-snow .ql-tooltip[data-mode=formula]::before{content:\"Enter formula:\"}.ql-snow .ql-tooltip[data-mode=video]::before{content:\"Enter video:\"}.ql-snow a{color:#06c}.ql-container.ql-snow{border:1px solid #ccc}\n\n/*# sourceMappingURL=quill.snow.css.map*/", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n", "/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n", "/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n", "/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n", "/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n", "import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n", "import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n", "import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n", "/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n", "import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n", "import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n", "import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n", "import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n", "import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n", "import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n", "import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n", "import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n", "import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n", "/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n", "import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n", "import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n", "import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n", "import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n", "import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n", "import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignMergeValue;\n", "import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n", "/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nexport default toPlainObject;\n", "import assignMergeValue from './_assignMergeValue.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\nimport copyArray from './_copyArray.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\nimport isBuffer from './isBuffer.js';\nimport isFunction from './isFunction.js';\nimport isObject from './isObject.js';\nimport isPlainObject from './isPlainObject.js';\nimport isTypedArray from './isTypedArray.js';\nimport safeGet from './_safeGet.js';\nimport toPlainObject from './toPlainObject.js';\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nexport default baseMergeDeep;\n", "import Stack from './_Stack.js';\nimport assignMergeValue from './_assignMergeValue.js';\nimport baseFor from './_baseFor.js';\nimport baseMergeDeep from './_baseMergeDeep.js';\nimport isObject from './isObject.js';\nimport keysIn from './keysIn.js';\nimport safeGet from './_safeGet.js';\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nexport default baseMerge;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import baseMerge from './_baseMerge.js';\nimport createAssigner from './_createAssigner.js';\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nexport default merge;\n", "/**\n * @license\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"es\" -o ./`\n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\nexport { default as add } from './add.js';\nexport { default as after } from './after.js';\nexport { default as ary } from './ary.js';\nexport { default as assign } from './assign.js';\nexport { default as assignIn } from './assignIn.js';\nexport { default as assignInWith } from './assignInWith.js';\nexport { default as assignWith } from './assignWith.js';\nexport { default as at } from './at.js';\nexport { default as attempt } from './attempt.js';\nexport { default as before } from './before.js';\nexport { default as bind } from './bind.js';\nexport { default as bindAll } from './bindAll.js';\nexport { default as bindKey } from './bindKey.js';\nexport { default as camelCase } from './camelCase.js';\nexport { default as capitalize } from './capitalize.js';\nexport { default as castArray } from './castArray.js';\nexport { default as ceil } from './ceil.js';\nexport { default as chain } from './chain.js';\nexport { default as chunk } from './chunk.js';\nexport { default as clamp } from './clamp.js';\nexport { default as clone } from './clone.js';\nexport { default as cloneDeep } from './cloneDeep.js';\nexport { default as cloneDeepWith } from './cloneDeepWith.js';\nexport { default as cloneWith } from './cloneWith.js';\nexport { default as commit } from './commit.js';\nexport { default as compact } from './compact.js';\nexport { default as concat } from './concat.js';\nexport { default as cond } from './cond.js';\nexport { default as conforms } from './conforms.js';\nexport { default as conformsTo } from './conformsTo.js';\nexport { default as constant } from './constant.js';\nexport { default as countBy } from './countBy.js';\nexport { default as create } from './create.js';\nexport { default as curry } from './curry.js';\nexport { default as curryRight } from './curryRight.js';\nexport { default as debounce } from './debounce.js';\nexport { default as deburr } from './deburr.js';\nexport { default as defaultTo } from './defaultTo.js';\nexport { default as defaults } from './defaults.js';\nexport { default as defaultsDeep } from './defaultsDeep.js';\nexport { default as defer } from './defer.js';\nexport { default as delay } from './delay.js';\nexport { default as difference } from './difference.js';\nexport { default as differenceBy } from './differenceBy.js';\nexport { default as differenceWith } from './differenceWith.js';\nexport { default as divide } from './divide.js';\nexport { default as drop } from './drop.js';\nexport { default as dropRight } from './dropRight.js';\nexport { default as dropRightWhile } from './dropRightWhile.js';\nexport { default as dropWhile } from './dropWhile.js';\nexport { default as each } from './each.js';\nexport { default as eachRight } from './eachRight.js';\nexport { default as endsWith } from './endsWith.js';\nexport { default as entries } from './entries.js';\nexport { default as entriesIn } from './entriesIn.js';\nexport { default as eq } from './eq.js';\nexport { default as escape } from './escape.js';\nexport { default as escapeRegExp } from './escapeRegExp.js';\nexport { default as every } from './every.js';\nexport { default as extend } from './extend.js';\nexport { default as extendWith } from './extendWith.js';\nexport { default as fill } from './fill.js';\nexport { default as filter } from './filter.js';\nexport { default as find } from './find.js';\nexport { default as findIndex } from './findIndex.js';\nexport { default as findKey } from './findKey.js';\nexport { default as findLast } from './findLast.js';\nexport { default as findLastIndex } from './findLastIndex.js';\nexport { default as findLastKey } from './findLastKey.js';\nexport { default as first } from './first.js';\nexport { default as flatMap } from './flatMap.js';\nexport { default as flatMapDeep } from './flatMapDeep.js';\nexport { default as flatMapDepth } from './flatMapDepth.js';\nexport { default as flatten } from './flatten.js';\nexport { default as flattenDeep } from './flattenDeep.js';\nexport { default as flattenDepth } from './flattenDepth.js';\nexport { default as flip } from './flip.js';\nexport { default as floor } from './floor.js';\nexport { default as flow } from './flow.js';\nexport { default as flowRight } from './flowRight.js';\nexport { default as forEach } from './forEach.js';\nexport { default as forEachRight } from './forEachRight.js';\nexport { default as forIn } from './forIn.js';\nexport { default as forInRight } from './forInRight.js';\nexport { default as forOwn } from './forOwn.js';\nexport { default as forOwnRight } from './forOwnRight.js';\nexport { default as fromPairs } from './fromPairs.js';\nexport { default as functions } from './functions.js';\nexport { default as functionsIn } from './functionsIn.js';\nexport { default as get } from './get.js';\nexport { default as groupBy } from './groupBy.js';\nexport { default as gt } from './gt.js';\nexport { default as gte } from './gte.js';\nexport { default as has } from './has.js';\nexport { default as hasIn } from './hasIn.js';\nexport { default as head } from './head.js';\nexport { default as identity } from './identity.js';\nexport { default as inRange } from './inRange.js';\nexport { default as includes } from './includes.js';\nexport { default as indexOf } from './indexOf.js';\nexport { default as initial } from './initial.js';\nexport { default as intersection } from './intersection.js';\nexport { default as intersectionBy } from './intersectionBy.js';\nexport { default as intersectionWith } from './intersectionWith.js';\nexport { default as invert } from './invert.js';\nexport { default as invertBy } from './invertBy.js';\nexport { default as invoke } from './invoke.js';\nexport { default as invokeMap } from './invokeMap.js';\nexport { default as isArguments } from './isArguments.js';\nexport { default as isArray } from './isArray.js';\nexport { default as isArrayBuffer } from './isArrayBuffer.js';\nexport { default as isArrayLike } from './isArrayLike.js';\nexport { default as isArrayLikeObject } from './isArrayLikeObject.js';\nexport { default as isBoolean } from './isBoolean.js';\nexport { default as isBuffer } from './isBuffer.js';\nexport { default as isDate } from './isDate.js';\nexport { default as isElement } from './isElement.js';\nexport { default as isEmpty } from './isEmpty.js';\nexport { default as isEqual } from './isEqual.js';\nexport { default as isEqualWith } from './isEqualWith.js';\nexport { default as isError } from './isError.js';\nexport { default as isFinite } from './isFinite.js';\nexport { default as isFunction } from './isFunction.js';\nexport { default as isInteger } from './isInteger.js';\nexport { default as isLength } from './isLength.js';\nexport { default as isMap } from './isMap.js';\nexport { default as isMatch } from './isMatch.js';\nexport { default as isMatchWith } from './isMatchWith.js';\nexport { default as isNaN } from './isNaN.js';\nexport { default as isNative } from './isNative.js';\nexport { default as isNil } from './isNil.js';\nexport { default as isNull } from './isNull.js';\nexport { default as isNumber } from './isNumber.js';\nexport { default as isObject } from './isObject.js';\nexport { default as isObjectLike } from './isObjectLike.js';\nexport { default as isPlainObject } from './isPlainObject.js';\nexport { default as isRegExp } from './isRegExp.js';\nexport { default as isSafeInteger } from './isSafeInteger.js';\nexport { default as isSet } from './isSet.js';\nexport { default as isString } from './isString.js';\nexport { default as isSymbol } from './isSymbol.js';\nexport { default as isTypedArray } from './isTypedArray.js';\nexport { default as isUndefined } from './isUndefined.js';\nexport { default as isWeakMap } from './isWeakMap.js';\nexport { default as isWeakSet } from './isWeakSet.js';\nexport { default as iteratee } from './iteratee.js';\nexport { default as join } from './join.js';\nexport { default as kebabCase } from './kebabCase.js';\nexport { default as keyBy } from './keyBy.js';\nexport { default as keys } from './keys.js';\nexport { default as keysIn } from './keysIn.js';\nexport { default as last } from './last.js';\nexport { default as lastIndexOf } from './lastIndexOf.js';\nexport { default as lodash } from './wrapperLodash.js';\nexport { default as lowerCase } from './lowerCase.js';\nexport { default as lowerFirst } from './lowerFirst.js';\nexport { default as lt } from './lt.js';\nexport { default as lte } from './lte.js';\nexport { default as map } from './map.js';\nexport { default as mapKeys } from './mapKeys.js';\nexport { default as mapValues } from './mapValues.js';\nexport { default as matches } from './matches.js';\nexport { default as matchesProperty } from './matchesProperty.js';\nexport { default as max } from './max.js';\nexport { default as maxBy } from './maxBy.js';\nexport { default as mean } from './mean.js';\nexport { default as meanBy } from './meanBy.js';\nexport { default as memoize } from './memoize.js';\nexport { default as merge } from './merge.js';\nexport { default as mergeWith } from './mergeWith.js';\nexport { default as method } from './method.js';\nexport { default as methodOf } from './methodOf.js';\nexport { default as min } from './min.js';\nexport { default as minBy } from './minBy.js';\nexport { default as mixin } from './mixin.js';\nexport { default as multiply } from './multiply.js';\nexport { default as negate } from './negate.js';\nexport { default as next } from './next.js';\nexport { default as noop } from './noop.js';\nexport { default as now } from './now.js';\nexport { default as nth } from './nth.js';\nexport { default as nthArg } from './nthArg.js';\nexport { default as omit } from './omit.js';\nexport { default as omitBy } from './omitBy.js';\nexport { default as once } from './once.js';\nexport { default as orderBy } from './orderBy.js';\nexport { default as over } from './over.js';\nexport { default as overArgs } from './overArgs.js';\nexport { default as overEvery } from './overEvery.js';\nexport { default as overSome } from './overSome.js';\nexport { default as pad } from './pad.js';\nexport { default as padEnd } from './padEnd.js';\nexport { default as padStart } from './padStart.js';\nexport { default as parseInt } from './parseInt.js';\nexport { default as partial } from './partial.js';\nexport { default as partialRight } from './partialRight.js';\nexport { default as partition } from './partition.js';\nexport { default as pick } from './pick.js';\nexport { default as pickBy } from './pickBy.js';\nexport { default as plant } from './plant.js';\nexport { default as property } from './property.js';\nexport { default as propertyOf } from './propertyOf.js';\nexport { default as pull } from './pull.js';\nexport { default as pullAll } from './pullAll.js';\nexport { default as pullAllBy } from './pullAllBy.js';\nexport { default as pullAllWith } from './pullAllWith.js';\nexport { default as pullAt } from './pullAt.js';\nexport { default as random } from './random.js';\nexport { default as range } from './range.js';\nexport { default as rangeRight } from './rangeRight.js';\nexport { default as rearg } from './rearg.js';\nexport { default as reduce } from './reduce.js';\nexport { default as reduceRight } from './reduceRight.js';\nexport { default as reject } from './reject.js';\nexport { default as remove } from './remove.js';\nexport { default as repeat } from './repeat.js';\nexport { default as replace } from './replace.js';\nexport { default as rest } from './rest.js';\nexport { default as result } from './result.js';\nexport { default as reverse } from './reverse.js';\nexport { default as round } from './round.js';\nexport { default as sample } from './sample.js';\nexport { default as sampleSize } from './sampleSize.js';\nexport { default as set } from './set.js';\nexport { default as setWith } from './setWith.js';\nexport { default as shuffle } from './shuffle.js';\nexport { default as size } from './size.js';\nexport { default as slice } from './slice.js';\nexport { default as snakeCase } from './snakeCase.js';\nexport { default as some } from './some.js';\nexport { default as sortBy } from './sortBy.js';\nexport { default as sortedIndex } from './sortedIndex.js';\nexport { default as sortedIndexBy } from './sortedIndexBy.js';\nexport { default as sortedIndexOf } from './sortedIndexOf.js';\nexport { default as sortedLastIndex } from './sortedLastIndex.js';\nexport { default as sortedLastIndexBy } from './sortedLastIndexBy.js';\nexport { default as sortedLastIndexOf } from './sortedLastIndexOf.js';\nexport { default as sortedUniq } from './sortedUniq.js';\nexport { default as sortedUniqBy } from './sortedUniqBy.js';\nexport { default as split } from './split.js';\nexport { default as spread } from './spread.js';\nexport { default as startCase } from './startCase.js';\nexport { default as startsWith } from './startsWith.js';\nexport { default as stubArray } from './stubArray.js';\nexport { default as stubFalse } from './stubFalse.js';\nexport { default as stubObject } from './stubObject.js';\nexport { default as stubString } from './stubString.js';\nexport { default as stubTrue } from './stubTrue.js';\nexport { default as subtract } from './subtract.js';\nexport { default as sum } from './sum.js';\nexport { default as sumBy } from './sumBy.js';\nexport { default as tail } from './tail.js';\nexport { default as take } from './take.js';\nexport { default as takeRight } from './takeRight.js';\nexport { default as takeRightWhile } from './takeRightWhile.js';\nexport { default as takeWhile } from './takeWhile.js';\nexport { default as tap } from './tap.js';\nexport { default as template } from './template.js';\nexport { default as templateSettings } from './templateSettings.js';\nexport { default as throttle } from './throttle.js';\nexport { default as thru } from './thru.js';\nexport { default as times } from './times.js';\nexport { default as toArray } from './toArray.js';\nexport { default as toFinite } from './toFinite.js';\nexport { default as toInteger } from './toInteger.js';\nexport { default as toIterator } from './toIterator.js';\nexport { default as toJSON } from './toJSON.js';\nexport { default as toLength } from './toLength.js';\nexport { default as toLower } from './toLower.js';\nexport { default as toNumber } from './toNumber.js';\nexport { default as toPairs } from './toPairs.js';\nexport { default as toPairsIn } from './toPairsIn.js';\nexport { default as toPath } from './toPath.js';\nexport { default as toPlainObject } from './toPlainObject.js';\nexport { default as toSafeInteger } from './toSafeInteger.js';\nexport { default as toString } from './toString.js';\nexport { default as toUpper } from './toUpper.js';\nexport { default as transform } from './transform.js';\nexport { default as trim } from './trim.js';\nexport { default as trimEnd } from './trimEnd.js';\nexport { default as trimStart } from './trimStart.js';\nexport { default as truncate } from './truncate.js';\nexport { default as unary } from './unary.js';\nexport { default as unescape } from './unescape.js';\nexport { default as union } from './union.js';\nexport { default as unionBy } from './unionBy.js';\nexport { default as unionWith } from './unionWith.js';\nexport { default as uniq } from './uniq.js';\nexport { default as uniqBy } from './uniqBy.js';\nexport { default as uniqWith } from './uniqWith.js';\nexport { default as uniqueId } from './uniqueId.js';\nexport { default as unset } from './unset.js';\nexport { default as unzip } from './unzip.js';\nexport { default as unzipWith } from './unzipWith.js';\nexport { default as update } from './update.js';\nexport { default as updateWith } from './updateWith.js';\nexport { default as upperCase } from './upperCase.js';\nexport { default as upperFirst } from './upperFirst.js';\nexport { default as value } from './value.js';\nexport { default as valueOf } from './valueOf.js';\nexport { default as values } from './values.js';\nexport { default as valuesIn } from './valuesIn.js';\nexport { default as without } from './without.js';\nexport { default as words } from './words.js';\nexport { default as wrap } from './wrap.js';\nexport { default as wrapperAt } from './wrapperAt.js';\nexport { default as wrapperChain } from './wrapperChain.js';\nexport { default as wrapperCommit } from './commit.js';\nexport { default as wrapperLodash } from './wrapperLodash.js';\nexport { default as wrapperNext } from './next.js';\nexport { default as wrapperPlant } from './plant.js';\nexport { default as wrapperReverse } from './wrapperReverse.js';\nexport { default as wrapperToIterator } from './toIterator.js';\nexport { default as wrapperValue } from './wrapperValue.js';\nexport { default as xor } from './xor.js';\nexport { default as xorBy } from './xorBy.js';\nexport { default as xorWith } from './xorWith.js';\nexport { default as zip } from './zip.js';\nexport { default as zipObject } from './zipObject.js';\nexport { default as zipObjectDeep } from './zipObjectDeep.js';\nexport { default as zipWith } from './zipWith.js';\nexport { default } from './lodash.default.js';\n", "enum Scope {\n TYPE = (1 << 2) - 1, // 0011 Lower two bits\n LEVEL = ((1 << 2) - 1) << 2, // 1100 Higher two bits\n\n ATTRIBUTE = (1 << 0) | LEVEL, // 1101\n BLOT = (1 << 1) | LEVEL, // 1110\n INLINE = (1 << 2) | TYPE, // 0111\n BLOCK = (1 << 3) | TYPE, // 1011\n\n BLOCK_BLOT = BLOCK & BLOT, // 1010\n INLINE_BLOT = INLINE & BLOT, // 0110\n BLOCK_ATTRIBUTE = BLOCK & ATTRIBUTE, // 1001\n INLINE_ATTRIBUTE = INLINE & ATTRIBUTE, // 0101\n\n ANY = TYPE | LEVEL,\n}\n\nexport default Scope;\n", "import Scope from '../scope.js';\n\nexport interface AttributorOptions {\n scope?: Scope;\n whitelist?: string[];\n}\n\nexport default class Attributor {\n public static keys(node: HTMLElement): string[] {\n return Array.from(node.attributes).map((item: Attr) => item.name);\n }\n\n public scope: Scope;\n public whitelist: string[] | undefined;\n\n constructor(\n public readonly attrName: string,\n public readonly keyName: string,\n options: AttributorOptions = {},\n ) {\n const attributeBit = Scope.TYPE & Scope.ATTRIBUTE;\n this.scope =\n options.scope != null\n ? // Ignore type bits, force attribute bit\n (options.scope & Scope.LEVEL) | attributeBit\n : Scope.ATTRIBUTE;\n if (options.whitelist != null) {\n this.whitelist = options.whitelist;\n }\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n node.setAttribute(this.keyName, value);\n return true;\n }\n\n public canAdd(_node: HTMLElement, value: any): boolean {\n if (this.whitelist == null) {\n return true;\n }\n if (typeof value === 'string') {\n return this.whitelist.indexOf(value.replace(/[\"']/g, '')) > -1;\n } else {\n return this.whitelist.indexOf(value) > -1;\n }\n }\n\n public remove(node: HTMLElement): void {\n node.removeAttribute(this.keyName);\n }\n\n public value(node: HTMLElement): any {\n const value = node.getAttribute(this.keyName);\n if (this.canAdd(node, value) && value) {\n return value;\n }\n return '';\n }\n}\n", "export default class ParchmentError extends Error {\n public message: string;\n public name: string;\n public stack!: string;\n\n constructor(message: string) {\n message = '[Parchment] ' + message;\n super(message);\n this.message = message;\n this.name = this.constructor.name;\n }\n}\n", "import Attributor from './attributor/attributor.js';\nimport {\n type Blot,\n type BlotConstructor,\n type Root,\n} from './blot/abstract/blot.js';\nimport ParchmentError from './error.js';\nimport Scope from './scope.js';\n\nexport type RegistryDefinition = Attributor | BlotConstructor;\n\nexport interface RegistryInterface {\n create(scroll: Root, input: Node | string | Scope, value?: any): Blot;\n query(query: string | Node | Scope, scope: Scope): RegistryDefinition | null;\n register(...definitions: any[]): any;\n}\n\nexport default class Registry implements RegistryInterface {\n public static blots = new WeakMap();\n\n public static find(node?: Node | null, bubble = false): Blot | null {\n if (node == null) {\n return null;\n }\n if (this.blots.has(node)) {\n return this.blots.get(node) || null;\n }\n if (bubble) {\n let parentNode: Node | null = null;\n try {\n parentNode = node.parentNode;\n } catch (err) {\n // Probably hit a permission denied error.\n // A known case is in Firefox, event targets can be anonymous DIVs\n // inside an input element.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=208427\n return null;\n }\n return this.find(parentNode, bubble);\n }\n return null;\n }\n\n private attributes: { [key: string]: Attributor } = {};\n private classes: { [key: string]: BlotConstructor } = {};\n private tags: { [key: string]: BlotConstructor } = {};\n private types: { [key: string]: RegistryDefinition } = {};\n\n public create(scroll: Root, input: Node | string | Scope, value?: any): Blot {\n const match = this.query(input);\n if (match == null) {\n throw new ParchmentError(`Unable to create ${input} blot`);\n }\n const blotClass = match as BlotConstructor;\n const node =\n // @ts-expect-error Fix me later\n input instanceof Node || input.nodeType === Node.TEXT_NODE\n ? input\n : blotClass.create(value);\n\n const blot = new blotClass(scroll, node as Node, value);\n Registry.blots.set(blot.domNode, blot);\n return blot;\n }\n\n public find(node: Node | null, bubble = false): Blot | null {\n return Registry.find(node, bubble);\n }\n\n public query(\n query: string | Node | Scope,\n scope: Scope = Scope.ANY,\n ): RegistryDefinition | null {\n let match;\n if (typeof query === 'string') {\n match = this.types[query] || this.attributes[query];\n // @ts-expect-error Fix me later\n } else if (query instanceof Text || query.nodeType === Node.TEXT_NODE) {\n match = this.types.text;\n } else if (typeof query === 'number') {\n if (query & Scope.LEVEL & Scope.BLOCK) {\n match = this.types.block;\n } else if (query & Scope.LEVEL & Scope.INLINE) {\n match = this.types.inline;\n }\n } else if (query instanceof Element) {\n const names = (query.getAttribute('class') || '').split(/\\s+/);\n names.some((name) => {\n match = this.classes[name];\n if (match) {\n return true;\n }\n return false;\n });\n match = match || this.tags[query.tagName];\n }\n if (match == null) {\n return null;\n }\n if (\n 'scope' in match &&\n scope & Scope.LEVEL & match.scope &&\n scope & Scope.TYPE & match.scope\n ) {\n return match;\n }\n return null;\n }\n\n public register(...definitions: RegistryDefinition[]): RegistryDefinition[] {\n return definitions.map((definition) => {\n const isBlot = 'blotName' in definition;\n const isAttr = 'attrName' in definition;\n if (!isBlot && !isAttr) {\n throw new ParchmentError('Invalid definition');\n } else if (isBlot && definition.blotName === 'abstract') {\n throw new ParchmentError('Cannot register abstract class');\n }\n const key = isBlot\n ? definition.blotName\n : isAttr\n ? definition.attrName\n : (undefined as never); // already handled by above checks\n this.types[key] = definition;\n\n if (isAttr) {\n if (typeof definition.keyName === 'string') {\n this.attributes[definition.keyName] = definition;\n }\n } else if (isBlot) {\n if (definition.className) {\n this.classes[definition.className] = definition;\n }\n if (definition.tagName) {\n if (Array.isArray(definition.tagName)) {\n definition.tagName = definition.tagName.map((tagName: string) => {\n return tagName.toUpperCase();\n });\n } else {\n definition.tagName = definition.tagName.toUpperCase();\n }\n const tagNames = Array.isArray(definition.tagName)\n ? definition.tagName\n : [definition.tagName];\n tagNames.forEach((tag: string) => {\n if (this.tags[tag] == null || definition.className == null) {\n this.tags[tag] = definition;\n }\n });\n }\n }\n return definition;\n });\n }\n}\n", "import Attributor from './attributor.js';\n\nfunction match(node: HTMLElement, prefix: string): string[] {\n const className = node.getAttribute('class') || '';\n return className\n .split(/\\s+/)\n .filter((name) => name.indexOf(`${prefix}-`) === 0);\n}\n\nclass ClassAttributor extends Attributor {\n public static keys(node: HTMLElement): string[] {\n return (node.getAttribute('class') || '')\n .split(/\\s+/)\n .map((name) => name.split('-').slice(0, -1).join('-'));\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n this.remove(node);\n node.classList.add(`${this.keyName}-${value}`);\n return true;\n }\n\n public remove(node: HTMLElement): void {\n const matches = match(node, this.keyName);\n matches.forEach((name) => {\n node.classList.remove(name);\n });\n if (node.classList.length === 0) {\n node.removeAttribute('class');\n }\n }\n\n public value(node: HTMLElement): any {\n const result = match(node, this.keyName)[0] || '';\n const value = result.slice(this.keyName.length + 1); // +1 for hyphen\n return this.canAdd(node, value) ? value : '';\n }\n}\n\nexport default ClassAttributor;\n", "import Attributor from './attributor.js';\n\nfunction camelize(name: string): string {\n const parts = name.split('-');\n const rest = parts\n .slice(1)\n .map((part: string) => part[0].toUpperCase() + part.slice(1))\n .join('');\n return parts[0] + rest;\n}\n\nclass StyleAttributor extends Attributor {\n public static keys(node: HTMLElement): string[] {\n return (node.getAttribute('style') || '').split(';').map((value) => {\n const arr = value.split(':');\n return arr[0].trim();\n });\n }\n\n public add(node: HTMLElement, value: any): boolean {\n if (!this.canAdd(node, value)) {\n return false;\n }\n // @ts-expect-error Fix me later\n node.style[camelize(this.keyName)] = value;\n return true;\n }\n\n public remove(node: HTMLElement): void {\n // @ts-expect-error Fix me later\n node.style[camelize(this.keyName)] = '';\n if (!node.getAttribute('style')) {\n node.removeAttribute('style');\n }\n }\n\n public value(node: HTMLElement): any {\n // @ts-expect-error Fix me later\n const value = node.style[camelize(this.keyName)];\n return this.canAdd(node, value) ? value : '';\n }\n}\n\nexport default StyleAttributor;\n", "import type { Formattable } from '../blot/abstract/blot.js';\nimport Registry from '../registry.js';\nimport Scope from '../scope.js';\nimport Attributor from './attributor.js';\nimport ClassAttributor from './class.js';\nimport StyleAttributor from './style.js';\n\nclass AttributorStore {\n private attributes: { [key: string]: Attributor } = {};\n private domNode: HTMLElement;\n\n constructor(domNode: HTMLElement) {\n this.domNode = domNode;\n this.build();\n }\n\n public attribute(attribute: Attributor, value: any): void {\n // verb\n if (value) {\n if (attribute.add(this.domNode, value)) {\n if (attribute.value(this.domNode) != null) {\n this.attributes[attribute.attrName] = attribute;\n } else {\n delete this.attributes[attribute.attrName];\n }\n }\n } else {\n attribute.remove(this.domNode);\n delete this.attributes[attribute.attrName];\n }\n }\n\n public build(): void {\n this.attributes = {};\n const blot = Registry.find(this.domNode);\n if (blot == null) {\n return;\n }\n const attributes = Attributor.keys(this.domNode);\n const classes = ClassAttributor.keys(this.domNode);\n const styles = StyleAttributor.keys(this.domNode);\n attributes\n .concat(classes)\n .concat(styles)\n .forEach((name) => {\n const attr = blot.scroll.query(name, Scope.ATTRIBUTE);\n if (attr instanceof Attributor) {\n this.attributes[attr.attrName] = attr;\n }\n });\n }\n\n public copy(target: Formattable): void {\n Object.keys(this.attributes).forEach((key) => {\n const value = this.attributes[key].value(this.domNode);\n target.format(key, value);\n });\n }\n\n public move(target: Formattable): void {\n this.copy(target);\n Object.keys(this.attributes).forEach((key) => {\n this.attributes[key].remove(this.domNode);\n });\n this.attributes = {};\n }\n\n public values(): { [key: string]: any } {\n return Object.keys(this.attributes).reduce(\n (attributes: { [key: string]: any }, name: string) => {\n attributes[name] = this.attributes[name].value(this.domNode);\n return attributes;\n },\n {},\n );\n }\n}\n\nexport default AttributorStore;\n", "import ParchmentError from '../../error.js';\nimport Registry from '../../registry.js';\nimport Scope from '../../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Parent,\n Root,\n} from './blot.js';\n\nclass ShadowBlot implements Blot {\n public static blotName = 'abstract';\n public static className: string;\n public static requiredContainer: BlotConstructor;\n public static scope: Scope;\n public static tagName: string | string[];\n\n public static create(rawValue?: unknown): Node {\n if (this.tagName == null) {\n throw new ParchmentError('Blot definition missing tagName');\n }\n let node: HTMLElement;\n let value: string | number | undefined;\n if (Array.isArray(this.tagName)) {\n if (typeof rawValue === 'string') {\n value = rawValue.toUpperCase();\n if (parseInt(value, 10).toString() === value) {\n value = parseInt(value, 10);\n }\n } else if (typeof rawValue === 'number') {\n value = rawValue;\n }\n if (typeof value === 'number') {\n node = document.createElement(this.tagName[value - 1]);\n } else if (value && this.tagName.indexOf(value) > -1) {\n node = document.createElement(value);\n } else {\n node = document.createElement(this.tagName[0]);\n }\n } else {\n node = document.createElement(this.tagName);\n }\n if (this.className) {\n node.classList.add(this.className);\n }\n return node;\n }\n\n public prev: Blot | null;\n public next: Blot | null;\n // @ts-expect-error Fix me later\n public parent: Parent;\n\n // Hack for accessing inherited static methods\n get statics(): any {\n return this.constructor;\n }\n constructor(\n public scroll: Root,\n public domNode: Node,\n ) {\n Registry.blots.set(domNode, this);\n this.prev = null;\n this.next = null;\n }\n\n public attach(): void {\n // Nothing to do\n }\n\n public clone(): Blot {\n const domNode = this.domNode.cloneNode(false);\n return this.scroll.create(domNode);\n }\n\n public detach(): void {\n if (this.parent != null) {\n this.parent.removeChild(this);\n }\n Registry.blots.delete(this.domNode);\n }\n\n public deleteAt(index: number, length: number): void {\n const blot = this.isolate(index, length);\n blot.remove();\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n const blot = this.isolate(index, length);\n if (this.scroll.query(name, Scope.BLOT) != null && value) {\n blot.wrap(name, value);\n } else if (this.scroll.query(name, Scope.ATTRIBUTE) != null) {\n const parent = this.scroll.create(this.statics.scope) as Parent &\n Formattable;\n blot.wrap(parent);\n parent.format(name, value);\n }\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n const blot =\n def == null\n ? this.scroll.create('text', value)\n : this.scroll.create(value, def);\n const ref = this.split(index);\n this.parent.insertBefore(blot, ref || undefined);\n }\n\n public isolate(index: number, length: number): Blot {\n const target = this.split(index);\n if (target == null) {\n throw new Error('Attempt to isolate at end');\n }\n target.split(length);\n return target;\n }\n\n public length(): number {\n return 1;\n }\n\n public offset(root: Blot = this.parent): number {\n if (this.parent == null || this === root) {\n return 0;\n }\n return this.parent.children.offset(this) + this.parent.offset(root);\n }\n\n public optimize(_context?: { [key: string]: any }): void {\n if (\n this.statics.requiredContainer &&\n !(this.parent instanceof this.statics.requiredContainer)\n ) {\n this.wrap(this.statics.requiredContainer.blotName);\n }\n }\n\n public remove(): void {\n if (this.domNode.parentNode != null) {\n this.domNode.parentNode.removeChild(this.domNode);\n }\n this.detach();\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement =\n typeof name === 'string' ? this.scroll.create(name, value) : name;\n if (this.parent != null) {\n this.parent.insertBefore(replacement, this.next || undefined);\n this.remove();\n }\n return replacement;\n }\n\n public split(index: number, _force?: boolean): Blot | null {\n return index === 0 ? this : this.next;\n }\n\n public update(\n _mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n // Nothing to do by default\n }\n\n public wrap(name: string | Parent, value?: any): Parent {\n const wrapper =\n typeof name === 'string'\n ? (this.scroll.create(name, value) as Parent)\n : name;\n if (this.parent != null) {\n this.parent.insertBefore(wrapper, this.next || undefined);\n }\n if (typeof wrapper.appendChild !== 'function') {\n throw new ParchmentError(`Cannot wrap ${name}`);\n }\n wrapper.appendChild(this);\n return wrapper;\n }\n}\n\nexport default ShadowBlot;\n", "import Scope from '../../scope.js';\nimport type { Leaf } from './blot.js';\nimport ShadowBlot from './shadow.js';\n\nclass LeafBlot extends ShadowBlot implements Leaf {\n public static scope = Scope.INLINE_BLOT;\n\n /**\n * Returns the value represented by domNode if it is this Blot's type\n * No checking that domNode can represent this Blot type is required so\n * applications needing it should check externally before calling.\n */\n public static value(_domNode: Node): any {\n return true;\n }\n\n /**\n * Given location represented by node and offset from DOM Selection Range,\n * return index to that location.\n */\n public index(node: Node, offset: number): number {\n if (\n this.domNode === node ||\n this.domNode.compareDocumentPosition(node) &\n Node.DOCUMENT_POSITION_CONTAINED_BY\n ) {\n return Math.min(offset, 1);\n }\n return -1;\n }\n\n /**\n * Given index to location within blot, return node and offset representing\n * that location, consumable by DOM Selection Range\n */\n public position(index: number, _inclusive?: boolean): [Node, number] {\n const childNodes: Node[] = Array.from(this.parent.domNode.childNodes);\n let offset = childNodes.indexOf(this.domNode);\n if (index > 0) {\n offset += 1;\n }\n return [this.parent.domNode, offset];\n }\n\n /**\n * Return value represented by this blot\n * Should not change without interaction from API or\n * user change detectable by update()\n */\n public value(): any {\n return {\n [this.statics.blotName]: this.statics.value(this.domNode) || true,\n };\n }\n}\n\nexport default LeafBlot;\n", "import type LinkedNode from './linked-node.js';\n\nclass LinkedList {\n public head: T | null;\n public tail: T | null;\n public length: number;\n\n constructor() {\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n public append(...nodes: T[]): void {\n this.insertBefore(nodes[0], null);\n if (nodes.length > 1) {\n const rest = nodes.slice(1);\n this.append(...rest);\n }\n }\n\n public at(index: number): T | null {\n const next = this.iterator();\n let cur = next();\n while (cur && index > 0) {\n index -= 1;\n cur = next();\n }\n return cur;\n }\n\n public contains(node: T): boolean {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n if (cur === node) {\n return true;\n }\n cur = next();\n }\n return false;\n }\n\n public indexOf(node: T): number {\n const next = this.iterator();\n let cur = next();\n let index = 0;\n while (cur) {\n if (cur === node) {\n return index;\n }\n index += 1;\n cur = next();\n }\n return -1;\n }\n\n public insertBefore(node: T | null, refNode: T | null): void {\n if (node == null) {\n return;\n }\n this.remove(node);\n node.next = refNode;\n if (refNode != null) {\n node.prev = refNode.prev;\n if (refNode.prev != null) {\n refNode.prev.next = node;\n }\n refNode.prev = node;\n if (refNode === this.head) {\n this.head = node;\n }\n } else if (this.tail != null) {\n this.tail.next = node;\n node.prev = this.tail;\n this.tail = node;\n } else {\n node.prev = null;\n this.head = this.tail = node;\n }\n this.length += 1;\n }\n\n public offset(target: T): number {\n let index = 0;\n let cur = this.head;\n while (cur != null) {\n if (cur === target) {\n return index;\n }\n index += cur.length();\n cur = cur.next as T;\n }\n return -1;\n }\n\n public remove(node: T): void {\n if (!this.contains(node)) {\n return;\n }\n if (node.prev != null) {\n node.prev.next = node.next;\n }\n if (node.next != null) {\n node.next.prev = node.prev;\n }\n if (node === this.head) {\n this.head = node.next as T;\n }\n if (node === this.tail) {\n this.tail = node.prev as T;\n }\n this.length -= 1;\n }\n\n public iterator(curNode: T | null = this.head): () => T | null {\n // TODO use yield when we can\n return (): T | null => {\n const ret = curNode;\n if (curNode != null) {\n curNode = curNode.next as T;\n }\n return ret;\n };\n }\n\n public find(index: number, inclusive = false): [T | null, number] {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n const length = cur.length();\n if (\n index < length ||\n (inclusive &&\n index === length &&\n (cur.next == null || cur.next.length() !== 0))\n ) {\n return [cur, index];\n }\n index -= length;\n cur = next();\n }\n return [null, 0];\n }\n\n public forEach(callback: (cur: T) => void): void {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n callback(cur);\n cur = next();\n }\n }\n\n public forEachAt(\n index: number,\n length: number,\n callback: (cur: T, offset: number, length: number) => void,\n ): void {\n if (length <= 0) {\n return;\n }\n const [startNode, offset] = this.find(index);\n let curIndex = index - offset;\n const next = this.iterator(startNode);\n let cur = next();\n while (cur && curIndex < index + length) {\n const curLength = cur.length();\n if (index > curIndex) {\n callback(\n cur,\n index - curIndex,\n Math.min(length, curIndex + curLength - index),\n );\n } else {\n callback(cur, 0, Math.min(curLength, index + length - curIndex));\n }\n curIndex += curLength;\n cur = next();\n }\n }\n\n public map(callback: (cur: T) => any): any[] {\n return this.reduce((memo: T[], cur: T) => {\n memo.push(callback(cur));\n return memo;\n }, []);\n }\n\n public reduce(callback: (memo: M, cur: T) => M, memo: M): M {\n const next = this.iterator();\n let cur = next();\n while (cur) {\n memo = callback(memo, cur);\n cur = next();\n }\n return memo;\n }\n}\n\nexport default LinkedList;\n", "import LinkedList from '../../collection/linked-list.js';\nimport ParchmentError from '../../error.js';\nimport Scope from '../../scope.js';\nimport type { Blot, BlotConstructor, Parent, Root } from './blot.js';\nimport ShadowBlot from './shadow.js';\n\nfunction makeAttachedBlot(node: Node, scroll: Root): Blot {\n const found = scroll.find(node);\n if (found) return found;\n try {\n return scroll.create(node);\n } catch (e) {\n const blot = scroll.create(Scope.INLINE);\n Array.from(node.childNodes).forEach((child: Node) => {\n blot.domNode.appendChild(child);\n });\n if (node.parentNode) {\n node.parentNode.replaceChild(blot.domNode, node);\n }\n blot.attach();\n return blot;\n }\n}\n\nclass ParentBlot extends ShadowBlot implements Parent {\n /**\n * Whitelist array of Blots that can be direct children.\n */\n public static allowedChildren?: BlotConstructor[];\n\n /**\n * Default child blot to be inserted if this blot becomes empty.\n */\n public static defaultChild?: BlotConstructor;\n public static uiClass = '';\n\n public children!: LinkedList;\n public domNode!: HTMLElement;\n public uiNode: HTMLElement | null = null;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.build();\n }\n\n public appendChild(other: Blot): void {\n this.insertBefore(other);\n }\n\n public attach(): void {\n super.attach();\n this.children.forEach((child) => {\n child.attach();\n });\n }\n\n public attachUI(node: HTMLElement): void {\n if (this.uiNode != null) {\n this.uiNode.remove();\n }\n this.uiNode = node;\n if (ParentBlot.uiClass) {\n this.uiNode.classList.add(ParentBlot.uiClass);\n }\n this.uiNode.setAttribute('contenteditable', 'false');\n this.domNode.insertBefore(this.uiNode, this.domNode.firstChild);\n }\n\n /**\n * Called during construction, should fill its own children LinkedList.\n */\n public build(): void {\n this.children = new LinkedList();\n // Need to be reversed for if DOM nodes already in order\n Array.from(this.domNode.childNodes)\n .filter((node: Node) => node !== this.uiNode)\n .reverse()\n .forEach((node: Node) => {\n try {\n const child = makeAttachedBlot(node, this.scroll);\n this.insertBefore(child, this.children.head || undefined);\n } catch (err) {\n if (err instanceof ParchmentError) {\n return;\n } else {\n throw err;\n }\n }\n });\n }\n\n public deleteAt(index: number, length: number): void {\n if (index === 0 && length === this.length()) {\n return this.remove();\n }\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.deleteAt(offset, childLength);\n });\n }\n\n public descendant(\n criteria: new (...args: any[]) => T,\n index: number,\n ): [T | null, number];\n public descendant(\n criteria: (blot: Blot) => boolean,\n index: number,\n ): [Blot | null, number];\n public descendant(criteria: any, index = 0): [Blot | null, number] {\n const [child, offset] = this.children.find(index);\n if (\n (criteria.blotName == null && criteria(child)) ||\n (criteria.blotName != null && child instanceof criteria)\n ) {\n return [child as any, offset];\n } else if (child instanceof ParentBlot) {\n return child.descendant(criteria, offset);\n } else {\n return [null, -1];\n }\n }\n\n public descendants(\n criteria: new (...args: any[]) => T,\n index?: number,\n length?: number,\n ): T[];\n public descendants(\n criteria: (blot: Blot) => boolean,\n index?: number,\n length?: number,\n ): Blot[];\n public descendants(\n criteria: any,\n index = 0,\n length: number = Number.MAX_VALUE,\n ): Blot[] {\n let descendants: Blot[] = [];\n let lengthLeft = length;\n this.children.forEachAt(\n index,\n length,\n (child: Blot, childIndex: number, childLength: number) => {\n if (\n (criteria.blotName == null && criteria(child)) ||\n (criteria.blotName != null && child instanceof criteria)\n ) {\n descendants.push(child);\n }\n if (child instanceof ParentBlot) {\n descendants = descendants.concat(\n child.descendants(criteria, childIndex, lengthLeft),\n );\n }\n lengthLeft -= childLength;\n },\n );\n return descendants;\n }\n\n public detach(): void {\n this.children.forEach((child) => {\n child.detach();\n });\n super.detach();\n }\n\n public enforceAllowedChildren(): void {\n let done = false;\n this.children.forEach((child: Blot) => {\n if (done) {\n return;\n }\n const allowed = this.statics.allowedChildren.some(\n (def: BlotConstructor) => child instanceof def,\n );\n if (allowed) {\n return;\n }\n if (child.statics.scope === Scope.BLOCK_BLOT) {\n if (child.next != null) {\n this.splitAfter(child);\n }\n if (child.prev != null) {\n this.splitAfter(child.prev);\n }\n child.parent.unwrap();\n done = true;\n } else if (child instanceof ParentBlot) {\n child.unwrap();\n } else {\n child.remove();\n }\n });\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n this.children.forEachAt(index, length, (child, offset, childLength) => {\n child.formatAt(offset, childLength, name, value);\n });\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n const [child, offset] = this.children.find(index);\n if (child) {\n child.insertAt(offset, value, def);\n } else {\n const blot =\n def == null\n ? this.scroll.create('text', value)\n : this.scroll.create(value, def);\n this.appendChild(blot);\n }\n }\n\n public insertBefore(childBlot: Blot, refBlot?: Blot | null): void {\n if (childBlot.parent != null) {\n childBlot.parent.children.remove(childBlot);\n }\n let refDomNode: Node | null = null;\n this.children.insertBefore(childBlot, refBlot || null);\n childBlot.parent = this;\n if (refBlot != null) {\n refDomNode = refBlot.domNode;\n }\n if (\n this.domNode.parentNode !== childBlot.domNode ||\n this.domNode.nextSibling !== refDomNode\n ) {\n this.domNode.insertBefore(childBlot.domNode, refDomNode);\n }\n childBlot.attach();\n }\n\n public length(): number {\n return this.children.reduce((memo, child) => {\n return memo + child.length();\n }, 0);\n }\n\n public moveChildren(targetParent: Parent, refNode?: Blot | null): void {\n this.children.forEach((child) => {\n targetParent.insertBefore(child, refNode);\n });\n }\n\n public optimize(context?: { [key: string]: any }): void {\n super.optimize(context);\n this.enforceAllowedChildren();\n if (this.uiNode != null && this.uiNode !== this.domNode.firstChild) {\n this.domNode.insertBefore(this.uiNode, this.domNode.firstChild);\n }\n if (this.children.length === 0) {\n if (this.statics.defaultChild != null) {\n const child = this.scroll.create(this.statics.defaultChild.blotName);\n this.appendChild(child);\n // TODO double check if necessary\n // child.optimize(context);\n } else {\n this.remove();\n }\n }\n }\n\n public path(index: number, inclusive = false): [Blot, number][] {\n const [child, offset] = this.children.find(index, inclusive);\n const position: [Blot, number][] = [[this, index]];\n if (child instanceof ParentBlot) {\n return position.concat(child.path(offset, inclusive));\n } else if (child != null) {\n position.push([child, offset]);\n }\n return position;\n }\n\n public removeChild(child: Blot): void {\n this.children.remove(child);\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement =\n typeof name === 'string' ? this.scroll.create(name, value) : name;\n if (replacement instanceof ParentBlot) {\n this.moveChildren(replacement);\n }\n return super.replaceWith(replacement);\n }\n\n public split(index: number, force = false): Blot | null {\n if (!force) {\n if (index === 0) {\n return this;\n }\n if (index === this.length()) {\n return this.next;\n }\n }\n const after = this.clone() as ParentBlot;\n if (this.parent) {\n this.parent.insertBefore(after, this.next || undefined);\n }\n this.children.forEachAt(index, this.length(), (child, offset, _length) => {\n const split = child.split(offset, force);\n if (split != null) {\n after.appendChild(split);\n }\n });\n return after;\n }\n\n public splitAfter(child: Blot): Parent {\n const after = this.clone() as ParentBlot;\n while (child.next != null) {\n after.appendChild(child.next);\n }\n if (this.parent) {\n this.parent.insertBefore(after, this.next || undefined);\n }\n return after;\n }\n\n public unwrap(): void {\n if (this.parent) {\n this.moveChildren(this.parent, this.next || undefined);\n }\n this.remove();\n }\n\n public update(\n mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n const addedNodes: Node[] = [];\n const removedNodes: Node[] = [];\n mutations.forEach((mutation) => {\n if (mutation.target === this.domNode && mutation.type === 'childList') {\n addedNodes.push(...mutation.addedNodes);\n removedNodes.push(...mutation.removedNodes);\n }\n });\n removedNodes.forEach((node: Node) => {\n // Check node has actually been removed\n // One exception is Chrome does not immediately remove IFRAMEs\n // from DOM but MutationRecord is correct in its reported removal\n if (\n node.parentNode != null &&\n // @ts-expect-error Fix me later\n node.tagName !== 'IFRAME' &&\n document.body.compareDocumentPosition(node) &\n Node.DOCUMENT_POSITION_CONTAINED_BY\n ) {\n return;\n }\n const blot = this.scroll.find(node);\n if (blot == null) {\n return;\n }\n if (\n blot.domNode.parentNode == null ||\n blot.domNode.parentNode === this.domNode\n ) {\n blot.detach();\n }\n });\n addedNodes\n .filter((node) => {\n return node.parentNode === this.domNode && node !== this.uiNode;\n })\n .sort((a, b) => {\n if (a === b) {\n return 0;\n }\n if (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) {\n return 1;\n }\n return -1;\n })\n .forEach((node) => {\n let refBlot: Blot | null = null;\n if (node.nextSibling != null) {\n refBlot = this.scroll.find(node.nextSibling);\n }\n const blot = makeAttachedBlot(node, this.scroll);\n if (blot.next !== refBlot || blot.next == null) {\n if (blot.parent != null) {\n blot.parent.removeChild(this);\n }\n this.insertBefore(blot, refBlot || undefined);\n }\n });\n this.enforceAllowedChildren();\n }\n}\n\nexport default ParentBlot;\n", "import Attributor from '../attributor/attributor.js';\nimport AttributorStore from '../attributor/store.js';\nimport Scope from '../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Parent,\n Root,\n} from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\nimport ParentBlot from './abstract/parent.js';\n\n// Shallow object comparison\nfunction isEqual(\n obj1: Record,\n obj2: Record,\n): boolean {\n if (Object.keys(obj1).length !== Object.keys(obj2).length) {\n return false;\n }\n for (const prop in obj1) {\n if (obj1[prop] !== obj2[prop]) {\n return false;\n }\n }\n return true;\n}\n\nclass InlineBlot extends ParentBlot implements Formattable {\n public static allowedChildren: BlotConstructor[] = [InlineBlot, LeafBlot];\n public static blotName = 'inline';\n public static scope = Scope.INLINE_BLOT;\n public static tagName: string | string[] = 'SPAN';\n\n static create(value?: unknown) {\n return super.create(value) as HTMLElement;\n }\n\n public static formats(domNode: HTMLElement, scroll: Root): any {\n const match = scroll.query(InlineBlot.blotName);\n if (\n match != null &&\n domNode.tagName === (match as BlotConstructor).tagName\n ) {\n return undefined;\n } else if (typeof this.tagName === 'string') {\n return true;\n } else if (Array.isArray(this.tagName)) {\n return domNode.tagName.toLowerCase();\n }\n return undefined;\n }\n\n protected attributes: AttributorStore;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.attributes = new AttributorStore(this.domNode);\n }\n\n public format(name: string, value: any): void {\n if (name === this.statics.blotName && !value) {\n this.children.forEach((child) => {\n if (!(child instanceof InlineBlot)) {\n child = child.wrap(InlineBlot.blotName, true);\n }\n this.attributes.copy(child as InlineBlot);\n });\n this.unwrap();\n } else {\n const format = this.scroll.query(name, Scope.INLINE);\n if (format == null) {\n return;\n }\n if (format instanceof Attributor) {\n this.attributes.attribute(format, value);\n } else if (\n value &&\n (name !== this.statics.blotName || this.formats()[name] !== value)\n ) {\n this.replaceWith(name, value);\n }\n }\n }\n\n public formats(): { [index: string]: any } {\n const formats = this.attributes.values();\n const format = this.statics.formats(this.domNode, this.scroll);\n if (format != null) {\n formats[this.statics.blotName] = format;\n }\n return formats;\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (\n this.formats()[name] != null ||\n this.scroll.query(name, Scope.ATTRIBUTE)\n ) {\n const blot = this.isolate(index, length) as InlineBlot;\n blot.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n const formats = this.formats();\n if (Object.keys(formats).length === 0) {\n return this.unwrap(); // unformatted span\n }\n const next = this.next;\n if (\n next instanceof InlineBlot &&\n next.prev === this &&\n isEqual(formats, next.formats())\n ) {\n next.moveChildren(this);\n next.remove();\n }\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement = super.replaceWith(name, value) as InlineBlot;\n this.attributes.copy(replacement);\n return replacement;\n }\n\n public update(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void {\n super.update(mutations, context);\n const attributeChanged = mutations.some(\n (mutation) =>\n mutation.target === this.domNode && mutation.type === 'attributes',\n );\n if (attributeChanged) {\n this.attributes.build();\n }\n }\n\n public wrap(name: string | Parent, value?: any): Parent {\n const wrapper = super.wrap(name, value);\n if (wrapper instanceof InlineBlot) {\n this.attributes.move(wrapper);\n }\n return wrapper;\n }\n}\n\nexport default InlineBlot;\n", "import Attributor from '../attributor/attributor.js';\nimport AttributorStore from '../attributor/store.js';\nimport Scope from '../scope.js';\nimport type {\n Blot,\n BlotConstructor,\n Formattable,\n Root,\n} from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\nimport ParentBlot from './abstract/parent.js';\nimport InlineBlot from './inline.js';\n\nclass BlockBlot extends ParentBlot implements Formattable {\n public static blotName = 'block';\n public static scope = Scope.BLOCK_BLOT;\n public static tagName: string | string[] = 'P';\n public static allowedChildren: BlotConstructor[] = [\n InlineBlot,\n BlockBlot,\n LeafBlot,\n ];\n\n static create(value?: unknown) {\n return super.create(value) as HTMLElement;\n }\n\n public static formats(domNode: HTMLElement, scroll: Root): any {\n const match = scroll.query(BlockBlot.blotName);\n if (\n match != null &&\n domNode.tagName === (match as BlotConstructor).tagName\n ) {\n return undefined;\n } else if (typeof this.tagName === 'string') {\n return true;\n } else if (Array.isArray(this.tagName)) {\n return domNode.tagName.toLowerCase();\n }\n }\n\n protected attributes: AttributorStore;\n\n constructor(scroll: Root, domNode: Node) {\n super(scroll, domNode);\n this.attributes = new AttributorStore(this.domNode);\n }\n\n public format(name: string, value: any): void {\n const format = this.scroll.query(name, Scope.BLOCK);\n if (format == null) {\n return;\n } else if (format instanceof Attributor) {\n this.attributes.attribute(format, value);\n } else if (name === this.statics.blotName && !value) {\n this.replaceWith(BlockBlot.blotName);\n } else if (\n value &&\n (name !== this.statics.blotName || this.formats()[name] !== value)\n ) {\n this.replaceWith(name, value);\n }\n }\n\n public formats(): { [index: string]: any } {\n const formats = this.attributes.values();\n const format = this.statics.formats(this.domNode, this.scroll);\n if (format != null) {\n formats[this.statics.blotName] = format;\n }\n return formats;\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (this.scroll.query(name, Scope.BLOCK) != null) {\n this.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n if (def == null || this.scroll.query(value, Scope.INLINE) != null) {\n // Insert text or inline\n super.insertAt(index, value, def);\n } else {\n const after = this.split(index);\n if (after != null) {\n const blot = this.scroll.create(value, def);\n after.parent.insertBefore(blot, after);\n } else {\n throw new Error('Attempt to insertAt after block boundaries');\n }\n }\n }\n\n public replaceWith(name: string | Blot, value?: any): Blot {\n const replacement = super.replaceWith(name, value) as BlockBlot;\n this.attributes.copy(replacement);\n return replacement;\n }\n\n public update(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void {\n super.update(mutations, context);\n const attributeChanged = mutations.some(\n (mutation) =>\n mutation.target === this.domNode && mutation.type === 'attributes',\n );\n if (attributeChanged) {\n this.attributes.build();\n }\n }\n}\n\nexport default BlockBlot;\n", "import Scope from '../../scope.js';\nimport BlockBlot from '../block.js';\nimport ParentBlot from './parent.js';\n\nclass ContainerBlot extends ParentBlot {\n public static blotName = 'container';\n public static scope = Scope.BLOCK_BLOT;\n public static tagName: string | string[];\n\n public prev!: BlockBlot | ContainerBlot | null;\n public next!: BlockBlot | ContainerBlot | null;\n\n public checkMerge(): boolean {\n return (\n this.next !== null && this.next.statics.blotName === this.statics.blotName\n );\n }\n\n public deleteAt(index: number, length: number): void {\n super.deleteAt(index, length);\n this.enforceAllowedChildren();\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n super.formatAt(index, length, name, value);\n this.enforceAllowedChildren();\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n super.insertAt(index, value, def);\n this.enforceAllowedChildren();\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n if (this.children.length > 0 && this.next != null && this.checkMerge()) {\n this.next.moveChildren(this);\n this.next.remove();\n }\n }\n}\n\nexport default ContainerBlot;\n", "import type { Formattable, Root } from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\n\nclass EmbedBlot extends LeafBlot implements Formattable {\n public static formats(_domNode: HTMLElement, _scroll: Root): any {\n return undefined;\n }\n\n public format(name: string, value: any): void {\n // super.formatAt wraps, which is what we want in general,\n // but this allows subclasses to overwrite for formats\n // that just apply to particular embeds\n super.formatAt(0, this.length(), name, value);\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n if (index === 0 && length === this.length()) {\n this.format(name, value);\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n public formats(): { [index: string]: any } {\n return this.statics.formats(this.domNode, this.scroll);\n }\n}\n\nexport default EmbedBlot;\n", "import Registry, { type RegistryDefinition } from '../registry.js';\nimport Scope from '../scope.js';\nimport type { Blot, BlotConstructor, Root } from './abstract/blot.js';\nimport ContainerBlot from './abstract/container.js';\nimport ParentBlot from './abstract/parent.js';\nimport BlockBlot from './block.js';\n\nconst OBSERVER_CONFIG = {\n attributes: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n};\n\nconst MAX_OPTIMIZE_ITERATIONS = 100;\n\nclass ScrollBlot extends ParentBlot implements Root {\n public static blotName = 'scroll';\n public static defaultChild = BlockBlot;\n public static allowedChildren: BlotConstructor[] = [BlockBlot, ContainerBlot];\n public static scope = Scope.BLOCK_BLOT;\n public static tagName = 'DIV';\n\n public observer: MutationObserver;\n\n constructor(\n public registry: Registry,\n node: HTMLDivElement,\n ) {\n // @ts-expect-error scroll is the root with no parent\n super(null, node);\n this.scroll = this;\n this.build();\n this.observer = new MutationObserver((mutations: MutationRecord[]) => {\n this.update(mutations);\n });\n this.observer.observe(this.domNode, OBSERVER_CONFIG);\n this.attach();\n }\n\n public create(input: Node | string | Scope, value?: any): Blot {\n return this.registry.create(this, input, value);\n }\n\n public find(node: Node | null, bubble = false): Blot | null {\n const blot = this.registry.find(node, bubble);\n if (!blot) {\n return null;\n }\n if (blot.scroll === this) {\n return blot;\n }\n return bubble ? this.find(blot.scroll.domNode.parentNode, true) : null;\n }\n\n public query(\n query: string | Node | Scope,\n scope: Scope = Scope.ANY,\n ): RegistryDefinition | null {\n return this.registry.query(query, scope);\n }\n\n public register(...definitions: RegistryDefinition[]) {\n return this.registry.register(...definitions);\n }\n\n public build(): void {\n if (this.scroll == null) {\n return;\n }\n super.build();\n }\n\n public detach(): void {\n super.detach();\n this.observer.disconnect();\n }\n\n public deleteAt(index: number, length: number): void {\n this.update();\n if (index === 0 && length === this.length()) {\n this.children.forEach((child) => {\n child.remove();\n });\n } else {\n super.deleteAt(index, length);\n }\n }\n\n public formatAt(\n index: number,\n length: number,\n name: string,\n value: any,\n ): void {\n this.update();\n super.formatAt(index, length, name, value);\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n this.update();\n super.insertAt(index, value, def);\n }\n\n public optimize(context?: { [key: string]: any }): void;\n public optimize(\n mutations: MutationRecord[],\n context: { [key: string]: any },\n ): void;\n public optimize(mutations: any = [], context: any = {}): void {\n super.optimize(context);\n const mutationsMap = context.mutationsMap || new WeakMap();\n // We must modify mutations directly, cannot make copy and then modify\n let records = Array.from(this.observer.takeRecords());\n // Array.push currently seems to be implemented by a non-tail recursive function\n // so we cannot just mutations.push.apply(mutations, this.observer.takeRecords());\n while (records.length > 0) {\n mutations.push(records.pop());\n }\n const mark = (blot: Blot | null, markParent = true): void => {\n if (blot == null || blot === this) {\n return;\n }\n if (blot.domNode.parentNode == null) {\n return;\n }\n if (!mutationsMap.has(blot.domNode)) {\n mutationsMap.set(blot.domNode, []);\n }\n if (markParent) {\n mark(blot.parent);\n }\n };\n const optimize = (blot: Blot): void => {\n // Post-order traversal\n if (!mutationsMap.has(blot.domNode)) {\n return;\n }\n if (blot instanceof ParentBlot) {\n blot.children.forEach(optimize);\n }\n mutationsMap.delete(blot.domNode);\n blot.optimize(context);\n };\n let remaining = mutations;\n for (let i = 0; remaining.length > 0; i += 1) {\n if (i >= MAX_OPTIMIZE_ITERATIONS) {\n throw new Error('[Parchment] Maximum optimize iterations reached');\n }\n remaining.forEach((mutation: MutationRecord) => {\n const blot = this.find(mutation.target, true);\n if (blot == null) {\n return;\n }\n if (blot.domNode === mutation.target) {\n if (mutation.type === 'childList') {\n mark(this.find(mutation.previousSibling, false));\n Array.from(mutation.addedNodes).forEach((node: Node) => {\n const child = this.find(node, false);\n mark(child, false);\n if (child instanceof ParentBlot) {\n child.children.forEach((grandChild: Blot) => {\n mark(grandChild, false);\n });\n }\n });\n } else if (mutation.type === 'attributes') {\n mark(blot.prev);\n }\n }\n mark(blot);\n });\n this.children.forEach(optimize);\n remaining = Array.from(this.observer.takeRecords());\n records = remaining.slice();\n while (records.length > 0) {\n mutations.push(records.pop());\n }\n }\n }\n\n public update(\n mutations?: MutationRecord[],\n context: { [key: string]: any } = {},\n ): void {\n mutations = mutations || this.observer.takeRecords();\n const mutationsMap = new WeakMap();\n mutations\n .map((mutation: MutationRecord) => {\n const blot = this.find(mutation.target, true);\n if (blot == null) {\n return null;\n }\n if (mutationsMap.has(blot.domNode)) {\n mutationsMap.get(blot.domNode).push(mutation);\n return null;\n } else {\n mutationsMap.set(blot.domNode, [mutation]);\n return blot;\n }\n })\n .forEach((blot: Blot | null) => {\n if (blot != null && blot !== this && mutationsMap.has(blot.domNode)) {\n blot.update(mutationsMap.get(blot.domNode) || [], context);\n }\n });\n context.mutationsMap = mutationsMap;\n if (mutationsMap.has(this.domNode)) {\n super.update(mutationsMap.get(this.domNode), context);\n }\n this.optimize(mutations, context);\n }\n}\n\nexport default ScrollBlot;\n", "import Scope from '../scope.js';\nimport type { Blot, Leaf, Root } from './abstract/blot.js';\nimport LeafBlot from './abstract/leaf.js';\n\nclass TextBlot extends LeafBlot implements Leaf {\n public static readonly blotName = 'text';\n public static scope = Scope.INLINE_BLOT;\n\n public static create(value: string): Text {\n return document.createTextNode(value);\n }\n\n public static value(domNode: Text): string {\n return domNode.data;\n }\n\n public domNode!: Text;\n protected text: string;\n\n constructor(scroll: Root, node: Node) {\n super(scroll, node);\n this.text = this.statics.value(this.domNode);\n }\n\n public deleteAt(index: number, length: number): void {\n this.domNode.data = this.text =\n this.text.slice(0, index) + this.text.slice(index + length);\n }\n\n public index(node: Node, offset: number): number {\n if (this.domNode === node) {\n return offset;\n }\n return -1;\n }\n\n public insertAt(index: number, value: string, def?: any): void {\n if (def == null) {\n this.text = this.text.slice(0, index) + value + this.text.slice(index);\n this.domNode.data = this.text;\n } else {\n super.insertAt(index, value, def);\n }\n }\n\n public length(): number {\n return this.text.length;\n }\n\n public optimize(context: { [key: string]: any }): void {\n super.optimize(context);\n this.text = this.statics.value(this.domNode);\n if (this.text.length === 0) {\n this.remove();\n } else if (this.next instanceof TextBlot && this.next.prev === this) {\n this.insertAt(this.length(), (this.next as TextBlot).value());\n this.next.remove();\n }\n }\n\n public position(index: number, _inclusive = false): [Node, number] {\n return [this.domNode, index];\n }\n\n public split(index: number, force = false): Blot | null {\n if (!force) {\n if (index === 0) {\n return this;\n }\n if (index === this.length()) {\n return this.next;\n }\n }\n const after = this.scroll.create(this.domNode.splitText(index));\n this.parent.insertBefore(after, this.next || undefined);\n this.text = this.statics.value(this.domNode);\n return after;\n }\n\n public update(\n mutations: MutationRecord[],\n _context: { [key: string]: any },\n ): void {\n if (\n mutations.some((mutation) => {\n return (\n mutation.type === 'characterData' && mutation.target === this.domNode\n );\n })\n ) {\n this.text = this.statics.value(this.domNode);\n }\n }\n\n public value(): string {\n return this.text;\n }\n}\n\nexport default TextBlot;\n", "/**\n * This library modifies the diff-patch-match library by Neil Fraser\n * by removing the patch and match functionality and certain advanced\n * options in the diff function. The original license is as follows:\n *\n * ===\n *\n * Diff Match and Patch\n *\n * Copyright 2006 Google Inc.\n * http://code.google.com/p/google-diff-match-patch/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The data structure representing a diff is an array of tuples:\n * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]\n * which means: delete 'Hello', add 'Goodbye' and keep ' world.'\n */\nvar DIFF_DELETE = -1;\nvar DIFF_INSERT = 1;\nvar DIFF_EQUAL = 0;\n\n/**\n * Find the differences between two texts. Simplifies the problem by stripping\n * any common prefix or suffix off the texts before diffing.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {Int|Object} [cursor_pos] Edit position in text1 or object with more info\n * @param {boolean} [cleanup] Apply semantic cleanup before returning.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_main(text1, text2, cursor_pos, cleanup, _fix_unicode) {\n // Check for equality\n if (text1 === text2) {\n if (text1) {\n return [[DIFF_EQUAL, text1]];\n }\n return [];\n }\n\n if (cursor_pos != null) {\n var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos);\n if (editdiff) {\n return editdiff;\n }\n }\n\n // Trim off common prefix (speedup).\n var commonlength = diff_commonPrefix(text1, text2);\n var commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n\n // Trim off common suffix (speedup).\n commonlength = diff_commonSuffix(text1, text2);\n var commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n\n // Compute the diff on the middle block.\n var diffs = diff_compute_(text1, text2);\n\n // Restore the prefix and suffix.\n if (commonprefix) {\n diffs.unshift([DIFF_EQUAL, commonprefix]);\n }\n if (commonsuffix) {\n diffs.push([DIFF_EQUAL, commonsuffix]);\n }\n diff_cleanupMerge(diffs, _fix_unicode);\n if (cleanup) {\n diff_cleanupSemantic(diffs);\n }\n return diffs;\n}\n\n/**\n * Find the differences between two texts. Assumes that the texts do not\n * have any common prefix or suffix.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_compute_(text1, text2) {\n var diffs;\n\n if (!text1) {\n // Just add some text (speedup).\n return [[DIFF_INSERT, text2]];\n }\n\n if (!text2) {\n // Just delete some text (speedup).\n return [[DIFF_DELETE, text1]];\n }\n\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n var i = longtext.indexOf(shorttext);\n if (i !== -1) {\n // Shorter text is inside the longer text (speedup).\n diffs = [\n [DIFF_INSERT, longtext.substring(0, i)],\n [DIFF_EQUAL, shorttext],\n [DIFF_INSERT, longtext.substring(i + shorttext.length)],\n ];\n // Swap insertions for deletions if diff is reversed.\n if (text1.length > text2.length) {\n diffs[0][0] = diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n\n if (shorttext.length === 1) {\n // Single character string.\n // After the previous speedup, the character can't be an equality.\n return [\n [DIFF_DELETE, text1],\n [DIFF_INSERT, text2],\n ];\n }\n\n // Check to see if the problem can be split in two.\n var hm = diff_halfMatch_(text1, text2);\n if (hm) {\n // A half-match was found, sort out the return data.\n var text1_a = hm[0];\n var text1_b = hm[1];\n var text2_a = hm[2];\n var text2_b = hm[3];\n var mid_common = hm[4];\n // Send both pairs off for separate processing.\n var diffs_a = diff_main(text1_a, text2_a);\n var diffs_b = diff_main(text1_b, text2_b);\n // Merge the results.\n return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);\n }\n\n return diff_bisect_(text1, text2);\n}\n\n/**\n * Find the 'middle snake' of a diff, split the problem in two\n * and return the recursively constructed diff.\n * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @return {Array} Array of diff tuples.\n * @private\n */\nfunction diff_bisect_(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n var max_d = Math.ceil((text1_length + text2_length) / 2);\n var v_offset = max_d;\n var v_length = 2 * max_d;\n var v1 = new Array(v_length);\n var v2 = new Array(v_length);\n // Setting all elements to -1 is faster in Chrome & Firefox than mixing\n // integers and undefined.\n for (var x = 0; x < v_length; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[v_offset + 1] = 0;\n v2[v_offset + 1] = 0;\n var delta = text1_length - text2_length;\n // If the total number of characters is odd, then the front path will collide\n // with the reverse path.\n var front = delta % 2 !== 0;\n // Offsets for start and end of k loop.\n // Prevents mapping of space beyond the grid.\n var k1start = 0;\n var k1end = 0;\n var k2start = 0;\n var k2end = 0;\n for (var d = 0; d < max_d; d++) {\n // Walk the front path one step.\n for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n var k1_offset = v_offset + k1;\n var x1;\n if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) {\n x1 = v1[k1_offset + 1];\n } else {\n x1 = v1[k1_offset - 1] + 1;\n }\n var y1 = x1 - k1;\n while (\n x1 < text1_length &&\n y1 < text2_length &&\n text1.charAt(x1) === text2.charAt(y1)\n ) {\n x1++;\n y1++;\n }\n v1[k1_offset] = x1;\n if (x1 > text1_length) {\n // Ran off the right of the graph.\n k1end += 2;\n } else if (y1 > text2_length) {\n // Ran off the bottom of the graph.\n k1start += 2;\n } else if (front) {\n var k2_offset = v_offset + delta - k1;\n if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) {\n // Mirror x2 onto top-left coordinate system.\n var x2 = text1_length - v2[k2_offset];\n if (x1 >= x2) {\n // Overlap detected.\n return diff_bisectSplit_(text1, text2, x1, y1);\n }\n }\n }\n }\n\n // Walk the reverse path one step.\n for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n var k2_offset = v_offset + k2;\n var x2;\n if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) {\n x2 = v2[k2_offset + 1];\n } else {\n x2 = v2[k2_offset - 1] + 1;\n }\n var y2 = x2 - k2;\n while (\n x2 < text1_length &&\n y2 < text2_length &&\n text1.charAt(text1_length - x2 - 1) ===\n text2.charAt(text2_length - y2 - 1)\n ) {\n x2++;\n y2++;\n }\n v2[k2_offset] = x2;\n if (x2 > text1_length) {\n // Ran off the left of the graph.\n k2end += 2;\n } else if (y2 > text2_length) {\n // Ran off the top of the graph.\n k2start += 2;\n } else if (!front) {\n var k1_offset = v_offset + delta - k2;\n if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) {\n var x1 = v1[k1_offset];\n var y1 = v_offset + x1 - k1_offset;\n // Mirror x2 onto top-left coordinate system.\n x2 = text1_length - x2;\n if (x1 >= x2) {\n // Overlap detected.\n return diff_bisectSplit_(text1, text2, x1, y1);\n }\n }\n }\n }\n }\n // Diff took too long and hit the deadline or\n // number of diffs equals number of characters, no commonality at all.\n return [\n [DIFF_DELETE, text1],\n [DIFF_INSERT, text2],\n ];\n}\n\n/**\n * Given the location of the 'middle snake', split the diff in two parts\n * and recurse.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} x Index of split point in text1.\n * @param {number} y Index of split point in text2.\n * @return {Array} Array of diff tuples.\n */\nfunction diff_bisectSplit_(text1, text2, x, y) {\n var text1a = text1.substring(0, x);\n var text2a = text2.substring(0, y);\n var text1b = text1.substring(x);\n var text2b = text2.substring(y);\n\n // Compute both diffs serially.\n var diffs = diff_main(text1a, text2a);\n var diffsb = diff_main(text1b, text2b);\n\n return diffs.concat(diffsb);\n}\n\n/**\n * Determine the common prefix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the start of each\n * string.\n */\nfunction diff_commonPrefix(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: http://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerstart = 0;\n while (pointermin < pointermid) {\n if (\n text1.substring(pointerstart, pointermid) ==\n text2.substring(pointerstart, pointermid)\n ) {\n pointermin = pointermid;\n pointerstart = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n\n if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) {\n pointermid--;\n }\n\n return pointermid;\n}\n\n/**\n * Determine if the suffix of one string is the prefix of another.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of the first\n * string and the start of the second string.\n * @private\n */\nfunction diff_commonOverlap_(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n // Eliminate the null case.\n if (text1_length == 0 || text2_length == 0) {\n return 0;\n }\n // Truncate the longer string.\n if (text1_length > text2_length) {\n text1 = text1.substring(text1_length - text2_length);\n } else if (text1_length < text2_length) {\n text2 = text2.substring(0, text1_length);\n }\n var text_length = Math.min(text1_length, text2_length);\n // Quick check for the worst case.\n if (text1 == text2) {\n return text_length;\n }\n\n // Start by looking for a single character match\n // and increase length until no match is found.\n // Performance analysis: http://neil.fraser.name/news/2010/11/04/\n var best = 0;\n var length = 1;\n while (true) {\n var pattern = text1.substring(text_length - length);\n var found = text2.indexOf(pattern);\n if (found == -1) {\n return best;\n }\n length += found;\n if (\n found == 0 ||\n text1.substring(text_length - length) == text2.substring(0, length)\n ) {\n best = length;\n length++;\n }\n }\n}\n\n/**\n * Determine the common suffix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of each string.\n */\nfunction diff_commonSuffix(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: http://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerend = 0;\n while (pointermin < pointermid) {\n if (\n text1.substring(text1.length - pointermid, text1.length - pointerend) ==\n text2.substring(text2.length - pointermid, text2.length - pointerend)\n ) {\n pointermin = pointermid;\n pointerend = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n\n if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) {\n pointermid--;\n }\n\n return pointermid;\n}\n\n/**\n * Do the two texts share a substring which is at least half the length of the\n * longer text?\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {Array.} Five element Array, containing the prefix of\n * text1, the suffix of text1, the prefix of text2, the suffix of\n * text2 and the common middle. Or null if there was no match.\n */\nfunction diff_halfMatch_(text1, text2) {\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {\n return null; // Pointless.\n }\n\n /**\n * Does a substring of shorttext exist within longtext such that the substring\n * is at least half the length of longtext?\n * Closure, but does not reference any external variables.\n * @param {string} longtext Longer string.\n * @param {string} shorttext Shorter string.\n * @param {number} i Start index of quarter length substring within longtext.\n * @return {Array.} Five element Array, containing the prefix of\n * longtext, the suffix of longtext, the prefix of shorttext, the suffix\n * of shorttext and the common middle. Or null if there was no match.\n * @private\n */\n function diff_halfMatchI_(longtext, shorttext, i) {\n // Start with a 1/4 length substring at position i as a seed.\n var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));\n var j = -1;\n var best_common = \"\";\n var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;\n while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {\n var prefixLength = diff_commonPrefix(\n longtext.substring(i),\n shorttext.substring(j)\n );\n var suffixLength = diff_commonSuffix(\n longtext.substring(0, i),\n shorttext.substring(0, j)\n );\n if (best_common.length < suffixLength + prefixLength) {\n best_common =\n shorttext.substring(j - suffixLength, j) +\n shorttext.substring(j, j + prefixLength);\n best_longtext_a = longtext.substring(0, i - suffixLength);\n best_longtext_b = longtext.substring(i + prefixLength);\n best_shorttext_a = shorttext.substring(0, j - suffixLength);\n best_shorttext_b = shorttext.substring(j + prefixLength);\n }\n }\n if (best_common.length * 2 >= longtext.length) {\n return [\n best_longtext_a,\n best_longtext_b,\n best_shorttext_a,\n best_shorttext_b,\n best_common,\n ];\n } else {\n return null;\n }\n }\n\n // First check if the second quarter is the seed for a half-match.\n var hm1 = diff_halfMatchI_(\n longtext,\n shorttext,\n Math.ceil(longtext.length / 4)\n );\n // Check again based on the third quarter.\n var hm2 = diff_halfMatchI_(\n longtext,\n shorttext,\n Math.ceil(longtext.length / 2)\n );\n var hm;\n if (!hm1 && !hm2) {\n return null;\n } else if (!hm2) {\n hm = hm1;\n } else if (!hm1) {\n hm = hm2;\n } else {\n // Both matched. Select the longest.\n hm = hm1[4].length > hm2[4].length ? hm1 : hm2;\n }\n\n // A half-match was found, sort out the return data.\n var text1_a, text1_b, text2_a, text2_b;\n if (text1.length > text2.length) {\n text1_a = hm[0];\n text1_b = hm[1];\n text2_a = hm[2];\n text2_b = hm[3];\n } else {\n text2_a = hm[0];\n text2_b = hm[1];\n text1_a = hm[2];\n text1_b = hm[3];\n }\n var mid_common = hm[4];\n return [text1_a, text1_b, text2_a, text2_b, mid_common];\n}\n\n/**\n * Reduce the number of edits by eliminating semantically trivial equalities.\n * @param {!Array.} diffs Array of diff tuples.\n */\nfunction diff_cleanupSemantic(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastequality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Number of characters that changed prior to the equality.\n var length_insertions1 = 0;\n var length_deletions1 = 0;\n // Number of characters that changed after the equality.\n var length_insertions2 = 0;\n var length_deletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) {\n // Equality found.\n equalities[equalitiesLength++] = pointer;\n length_insertions1 = length_insertions2;\n length_deletions1 = length_deletions2;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastequality = diffs[pointer][1];\n } else {\n // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_INSERT) {\n length_insertions2 += diffs[pointer][1].length;\n } else {\n length_deletions2 += diffs[pointer][1].length;\n }\n // Eliminate an equality that is smaller or equal to the edits on both\n // sides of it.\n if (\n lastequality &&\n lastequality.length <=\n Math.max(length_insertions1, length_deletions1) &&\n lastequality.length <= Math.max(length_insertions2, length_deletions2)\n ) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0, [\n DIFF_DELETE,\n lastequality,\n ]);\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n // Throw away the equality we just deleted.\n equalitiesLength--;\n // Throw away the previous equality (it needs to be reevaluated).\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n length_insertions1 = 0; // Reset the counters.\n length_deletions1 = 0;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastequality = null;\n changes = true;\n }\n }\n pointer++;\n }\n\n // Normalize the diff.\n if (changes) {\n diff_cleanupMerge(diffs);\n }\n diff_cleanupSemanticLossless(diffs);\n\n // Find any overlaps between deletions and insertions.\n // e.g: abcxxxxxxdef\n // -> abcxxxdef\n // e.g: xxxabcdefxxx\n // -> defxxxabc\n // Only extract an overlap if it is as big as the edit ahead or behind it.\n pointer = 1;\n while (pointer < diffs.length) {\n if (\n diffs[pointer - 1][0] == DIFF_DELETE &&\n diffs[pointer][0] == DIFF_INSERT\n ) {\n var deletion = diffs[pointer - 1][1];\n var insertion = diffs[pointer][1];\n var overlap_length1 = diff_commonOverlap_(deletion, insertion);\n var overlap_length2 = diff_commonOverlap_(insertion, deletion);\n if (overlap_length1 >= overlap_length2) {\n if (\n overlap_length1 >= deletion.length / 2 ||\n overlap_length1 >= insertion.length / 2\n ) {\n // Overlap found. Insert an equality and trim the surrounding edits.\n diffs.splice(pointer, 0, [\n DIFF_EQUAL,\n insertion.substring(0, overlap_length1),\n ]);\n diffs[pointer - 1][1] = deletion.substring(\n 0,\n deletion.length - overlap_length1\n );\n diffs[pointer + 1][1] = insertion.substring(overlap_length1);\n pointer++;\n }\n } else {\n if (\n overlap_length2 >= deletion.length / 2 ||\n overlap_length2 >= insertion.length / 2\n ) {\n // Reverse overlap found.\n // Insert an equality and swap and trim the surrounding edits.\n diffs.splice(pointer, 0, [\n DIFF_EQUAL,\n deletion.substring(0, overlap_length2),\n ]);\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] = insertion.substring(\n 0,\n insertion.length - overlap_length2\n );\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] = deletion.substring(overlap_length2);\n pointer++;\n }\n }\n pointer++;\n }\n pointer++;\n }\n}\n\nvar nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;\nvar whitespaceRegex_ = /\\s/;\nvar linebreakRegex_ = /[\\r\\n]/;\nvar blanklineEndRegex_ = /\\n\\r?\\n$/;\nvar blanklineStartRegex_ = /^\\r?\\n\\r?\\n/;\n\n/**\n * Look for single edits surrounded on both sides by equalities\n * which can be shifted sideways to align the edit to a word boundary.\n * e.g: The cat came. -> The cat came.\n * @param {!Array.} diffs Array of diff tuples.\n */\nfunction diff_cleanupSemanticLossless(diffs) {\n /**\n * Given two strings, compute a score representing whether the internal\n * boundary falls on logical boundaries.\n * Scores range from 6 (best) to 0 (worst).\n * Closure, but does not reference any external variables.\n * @param {string} one First string.\n * @param {string} two Second string.\n * @return {number} The score.\n * @private\n */\n function diff_cleanupSemanticScore_(one, two) {\n if (!one || !two) {\n // Edges are the best.\n return 6;\n }\n\n // Each port of this function behaves slightly differently due to\n // subtle differences in each language's definition of things like\n // 'whitespace'. Since this function's purpose is largely cosmetic,\n // the choice has been made to use each language's native features\n // rather than force total conformity.\n var char1 = one.charAt(one.length - 1);\n var char2 = two.charAt(0);\n var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_);\n var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_);\n var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_);\n var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_);\n var lineBreak1 = whitespace1 && char1.match(linebreakRegex_);\n var lineBreak2 = whitespace2 && char2.match(linebreakRegex_);\n var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_);\n var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_);\n\n if (blankLine1 || blankLine2) {\n // Five points for blank lines.\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n // Four points for line breaks.\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n // Three points for end of sentences.\n return 3;\n } else if (whitespace1 || whitespace2) {\n // Two points for whitespace.\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n // One point for non-alphanumeric.\n return 1;\n }\n return 0;\n }\n\n var pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (\n diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL\n ) {\n // This is a single edit surrounded by equalities.\n var equality1 = diffs[pointer - 1][1];\n var edit = diffs[pointer][1];\n var equality2 = diffs[pointer + 1][1];\n\n // First, shift the edit as far left as possible.\n var commonOffset = diff_commonSuffix(equality1, edit);\n if (commonOffset) {\n var commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n\n // Second, step character by character right, looking for the best fit.\n var bestEquality1 = equality1;\n var bestEdit = edit;\n var bestEquality2 = equality2;\n var bestScore =\n diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n var score =\n diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n // The >= encourages trailing rather than leading whitespace on edits.\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n\n if (diffs[pointer - 1][1] != bestEquality1) {\n // We have an improvement, save it back to the diff.\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n}\n\n/**\n * Reorder and merge like edit sections. Merge equalities.\n * Any edit section can move as long as it doesn't cross an equality.\n * @param {Array} diffs Array of diff tuples.\n * @param {boolean} fix_unicode Whether to normalize to a unicode-correct diff\n */\nfunction diff_cleanupMerge(diffs, fix_unicode) {\n diffs.push([DIFF_EQUAL, \"\"]); // Add a dummy entry at the end.\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = \"\";\n var text_insert = \"\";\n var commonlength;\n while (pointer < diffs.length) {\n if (pointer < diffs.length - 1 && !diffs[pointer][1]) {\n diffs.splice(pointer, 1);\n continue;\n }\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n var previous_equality = pointer - count_insert - count_delete - 1;\n if (fix_unicode) {\n // prevent splitting of unicode surrogate pairs. when fix_unicode is true,\n // we assume that the old and new text in the diff are complete and correct\n // unicode-encoded JS strings, but the tuple boundaries may fall between\n // surrogate pairs. we fix this by shaving off stray surrogates from the end\n // of the previous equality and the beginning of this equality. this may create\n // empty equalities or a common prefix or suffix. for example, if AB and AC are\n // emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and\n // inserting 'AC', and then the common suffix 'AC' will be eliminated. in this\n // particular case, both equalities go away, we absorb any previous inequalities,\n // and we keep scanning for the next equality before rewriting the tuples.\n if (\n previous_equality >= 0 &&\n ends_with_pair_start(diffs[previous_equality][1])\n ) {\n var stray = diffs[previous_equality][1].slice(-1);\n diffs[previous_equality][1] = diffs[previous_equality][1].slice(\n 0,\n -1\n );\n text_delete = stray + text_delete;\n text_insert = stray + text_insert;\n if (!diffs[previous_equality][1]) {\n // emptied out previous equality, so delete it and include previous delete/insert\n diffs.splice(previous_equality, 1);\n pointer--;\n var k = previous_equality - 1;\n if (diffs[k] && diffs[k][0] === DIFF_INSERT) {\n count_insert++;\n text_insert = diffs[k][1] + text_insert;\n k--;\n }\n if (diffs[k] && diffs[k][0] === DIFF_DELETE) {\n count_delete++;\n text_delete = diffs[k][1] + text_delete;\n k--;\n }\n previous_equality = k;\n }\n }\n if (starts_with_pair_end(diffs[pointer][1])) {\n var stray = diffs[pointer][1].charAt(0);\n diffs[pointer][1] = diffs[pointer][1].slice(1);\n text_delete += stray;\n text_insert += stray;\n }\n }\n if (pointer < diffs.length - 1 && !diffs[pointer][1]) {\n // for empty equality not at end, wait for next equality\n diffs.splice(pointer, 1);\n break;\n }\n if (text_delete.length > 0 || text_insert.length > 0) {\n // note that diff_commonPrefix and diff_commonSuffix are unicode-aware\n if (text_delete.length > 0 && text_insert.length > 0) {\n // Factor out any common prefixes.\n commonlength = diff_commonPrefix(text_insert, text_delete);\n if (commonlength !== 0) {\n if (previous_equality >= 0) {\n diffs[previous_equality][1] += text_insert.substring(\n 0,\n commonlength\n );\n } else {\n diffs.splice(0, 0, [\n DIFF_EQUAL,\n text_insert.substring(0, commonlength),\n ]);\n pointer++;\n }\n text_insert = text_insert.substring(commonlength);\n text_delete = text_delete.substring(commonlength);\n }\n // Factor out any common suffixes.\n commonlength = diff_commonSuffix(text_insert, text_delete);\n if (commonlength !== 0) {\n diffs[pointer][1] =\n text_insert.substring(text_insert.length - commonlength) +\n diffs[pointer][1];\n text_insert = text_insert.substring(\n 0,\n text_insert.length - commonlength\n );\n text_delete = text_delete.substring(\n 0,\n text_delete.length - commonlength\n );\n }\n }\n // Delete the offending records and add the merged ones.\n var n = count_insert + count_delete;\n if (text_delete.length === 0 && text_insert.length === 0) {\n diffs.splice(pointer - n, n);\n pointer = pointer - n;\n } else if (text_delete.length === 0) {\n diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]);\n pointer = pointer - n + 1;\n } else if (text_insert.length === 0) {\n diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]);\n pointer = pointer - n + 1;\n } else {\n diffs.splice(\n pointer - n,\n n,\n [DIFF_DELETE, text_delete],\n [DIFF_INSERT, text_insert]\n );\n pointer = pointer - n + 2;\n }\n }\n if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {\n // Merge this equality with the previous one.\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = \"\";\n text_insert = \"\";\n break;\n }\n }\n if (diffs[diffs.length - 1][1] === \"\") {\n diffs.pop(); // Remove the dummy entry at the end.\n }\n\n // Second pass: look for single edits surrounded on both sides by equalities\n // which can be shifted sideways to eliminate an equality.\n // e.g: ABAC -> ABAC\n var changes = false;\n pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (\n diffs[pointer - 1][0] === DIFF_EQUAL &&\n diffs[pointer + 1][0] === DIFF_EQUAL\n ) {\n // This is a single edit surrounded by equalities.\n if (\n diffs[pointer][1].substring(\n diffs[pointer][1].length - diffs[pointer - 1][1].length\n ) === diffs[pointer - 1][1]\n ) {\n // Shift the edit over the previous equality.\n diffs[pointer][1] =\n diffs[pointer - 1][1] +\n diffs[pointer][1].substring(\n 0,\n diffs[pointer][1].length - diffs[pointer - 1][1].length\n );\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n changes = true;\n } else if (\n diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==\n diffs[pointer + 1][1]\n ) {\n // Shift the edit over the next equality.\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] =\n diffs[pointer][1].substring(diffs[pointer + 1][1].length) +\n diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n changes = true;\n }\n }\n pointer++;\n }\n // If shifts were made, the diff needs reordering and another shift sweep.\n if (changes) {\n diff_cleanupMerge(diffs, fix_unicode);\n }\n}\n\nfunction is_surrogate_pair_start(charCode) {\n return charCode >= 0xd800 && charCode <= 0xdbff;\n}\n\nfunction is_surrogate_pair_end(charCode) {\n return charCode >= 0xdc00 && charCode <= 0xdfff;\n}\n\nfunction starts_with_pair_end(str) {\n return is_surrogate_pair_end(str.charCodeAt(0));\n}\n\nfunction ends_with_pair_start(str) {\n return is_surrogate_pair_start(str.charCodeAt(str.length - 1));\n}\n\nfunction remove_empty_tuples(tuples) {\n var ret = [];\n for (var i = 0; i < tuples.length; i++) {\n if (tuples[i][1].length > 0) {\n ret.push(tuples[i]);\n }\n }\n return ret;\n}\n\nfunction make_edit_splice(before, oldMiddle, newMiddle, after) {\n if (ends_with_pair_start(before) || starts_with_pair_end(after)) {\n return null;\n }\n return remove_empty_tuples([\n [DIFF_EQUAL, before],\n [DIFF_DELETE, oldMiddle],\n [DIFF_INSERT, newMiddle],\n [DIFF_EQUAL, after],\n ]);\n}\n\nfunction find_cursor_edit_diff(oldText, newText, cursor_pos) {\n // note: this runs after equality check has ruled out exact equality\n var oldRange =\n typeof cursor_pos === \"number\"\n ? { index: cursor_pos, length: 0 }\n : cursor_pos.oldRange;\n var newRange = typeof cursor_pos === \"number\" ? null : cursor_pos.newRange;\n // take into account the old and new selection to generate the best diff\n // possible for a text edit. for example, a text change from \"xxx\" to \"xx\"\n // could be a delete or forwards-delete of any one of the x's, or the\n // result of selecting two of the x's and typing \"x\".\n var oldLength = oldText.length;\n var newLength = newText.length;\n if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) {\n // see if we have an insert or delete before or after cursor\n var oldCursor = oldRange.index;\n var oldBefore = oldText.slice(0, oldCursor);\n var oldAfter = oldText.slice(oldCursor);\n var maybeNewCursor = newRange ? newRange.index : null;\n editBefore: {\n // is this an insert or delete right before oldCursor?\n var newCursor = oldCursor + newLength - oldLength;\n if (maybeNewCursor !== null && maybeNewCursor !== newCursor) {\n break editBefore;\n }\n if (newCursor < 0 || newCursor > newLength) {\n break editBefore;\n }\n var newBefore = newText.slice(0, newCursor);\n var newAfter = newText.slice(newCursor);\n if (newAfter !== oldAfter) {\n break editBefore;\n }\n var prefixLength = Math.min(oldCursor, newCursor);\n var oldPrefix = oldBefore.slice(0, prefixLength);\n var newPrefix = newBefore.slice(0, prefixLength);\n if (oldPrefix !== newPrefix) {\n break editBefore;\n }\n var oldMiddle = oldBefore.slice(prefixLength);\n var newMiddle = newBefore.slice(prefixLength);\n return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter);\n }\n editAfter: {\n // is this an insert or delete right after oldCursor?\n if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) {\n break editAfter;\n }\n var cursor = oldCursor;\n var newBefore = newText.slice(0, cursor);\n var newAfter = newText.slice(cursor);\n if (newBefore !== oldBefore) {\n break editAfter;\n }\n var suffixLength = Math.min(oldLength - cursor, newLength - cursor);\n var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength);\n var newSuffix = newAfter.slice(newAfter.length - suffixLength);\n if (oldSuffix !== newSuffix) {\n break editAfter;\n }\n var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength);\n var newMiddle = newAfter.slice(0, newAfter.length - suffixLength);\n return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix);\n }\n }\n if (oldRange.length > 0 && newRange && newRange.length === 0) {\n replaceRange: {\n // see if diff could be a splice of the old selection range\n var oldPrefix = oldText.slice(0, oldRange.index);\n var oldSuffix = oldText.slice(oldRange.index + oldRange.length);\n var prefixLength = oldPrefix.length;\n var suffixLength = oldSuffix.length;\n if (newLength < prefixLength + suffixLength) {\n break replaceRange;\n }\n var newPrefix = newText.slice(0, prefixLength);\n var newSuffix = newText.slice(newLength - suffixLength);\n if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) {\n break replaceRange;\n }\n var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength);\n var newMiddle = newText.slice(prefixLength, newLength - suffixLength);\n return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix);\n }\n }\n\n return null;\n}\n\nfunction diff(text1, text2, cursor_pos, cleanup) {\n // only pass fix_unicode=true at the top level, not when diff_main is\n // recursively invoked\n return diff_main(text1, text2, cursor_pos, cleanup, true);\n}\n\ndiff.INSERT = DIFF_INSERT;\ndiff.DELETE = DIFF_DELETE;\ndiff.EQUAL = DIFF_EQUAL;\n\nmodule.exports = diff;\n", "/**\n * lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/**\n * Adds the key-value `pair` to `map`.\n *\n * @private\n * @param {Object} map The map to modify.\n * @param {Array} pair The key-value pair to add.\n * @returns {Object} Returns `map`.\n */\nfunction addMapEntry(map, pair) {\n // Don't return `map.set` because it's not chainable in IE 11.\n map.set(pair[0], pair[1]);\n return map;\n}\n\n/**\n * Adds `value` to `set`.\n *\n * @private\n * @param {Object} set The set to modify.\n * @param {*} value The value to add.\n * @returns {Object} Returns `set`.\n */\nfunction addSetEntry(set, value) {\n // Don't return `set.add` because it's not chainable in IE 11.\n set.add(value);\n return set;\n}\n\n/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array ? array.length : 0;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n return this.has(key) && delete this.__data__[key];\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n return getMapData(this, key)['delete'](key);\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n getMapData(this, key).set(key, value);\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n this.__data__ = new ListCache(entries);\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n return this.__data__['delete'](key);\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var cache = this.__data__;\n if (cache instanceof ListCache) {\n var pairs = cache.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n return this;\n }\n cache = this.__data__ = new MapCache(pairs);\n }\n cache.set(key, value);\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n // Safari 9 makes `arguments.length` enumerable in strict mode.\n var result = (isArray(value) || isArguments(value))\n ? baseTimes(value.length, String)\n : [];\n\n var length = result.length,\n skipIndexes = !!length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (key == 'length' || isIndex(key, length)))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n object[key] = value;\n }\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @param {boolean} [isFull] Specify a clone including symbols.\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, isDeep, isFull, customizer, key, object, stack) {\n var result;\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n if (isHostObject(value)) {\n return object ? value : {};\n }\n result = initCloneObject(isFunc ? {} : value);\n if (!isDeep) {\n return copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, baseClone, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (!isArr) {\n var props = isFull ? getAllKeys(value) : keys(value);\n }\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));\n });\n return result;\n}\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} prototype The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nfunction baseCreate(proto) {\n return isObject(proto) ? objectCreate(proto) : {};\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n return objectToString.call(value);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var result = new buffer.constructor(buffer.length);\n buffer.copy(result);\n return result;\n}\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\n/**\n * Creates a clone of `map`.\n *\n * @private\n * @param {Object} map The map to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned map.\n */\nfunction cloneMap(map, isDeep, cloneFunc) {\n var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);\n return arrayReduce(array, addMapEntry, new map.constructor);\n}\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\n/**\n * Creates a clone of `set`.\n *\n * @private\n * @param {Object} set The set to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned set.\n */\nfunction cloneSet(set, isDeep, cloneFunc) {\n var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);\n return arrayReduce(array, addSetEntry, new set.constructor);\n}\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\n/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n assignValue(object, key, newValue === undefined ? source[key] : newValue);\n }\n return object;\n}\n\n/**\n * Copies own symbol properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * Creates an array of the own enumerable symbol properties of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11,\n// for data views in Edge < 14, and promises in Node.js.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = objectToString.call(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : undefined;\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {Function} cloneFunc The function to clone values.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, cloneFunc, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return cloneMap(object, isDeep, cloneFunc);\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return cloneSet(object, isDeep, cloneFunc);\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to process.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, true, true);\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nfunction isArguments(value) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&\n (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);\n}\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = cloneDeep;\n", "/**\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright JS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\n/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = isEqual;\n", "import cloneDeep = require('lodash.clonedeep');\nimport isEqual = require('lodash.isequal');\n\ninterface AttributeMap {\n [key: string]: unknown;\n}\n\nnamespace AttributeMap {\n export function compose(\n a: AttributeMap = {},\n b: AttributeMap = {},\n keepNull = false,\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n a = {};\n }\n if (typeof b !== 'object') {\n b = {};\n }\n let attributes = cloneDeep(b);\n if (!keepNull) {\n attributes = Object.keys(attributes).reduce((copy, key) => {\n if (attributes[key] != null) {\n copy[key] = attributes[key];\n }\n return copy;\n }, {});\n }\n for (const key in a) {\n if (a[key] !== undefined && b[key] === undefined) {\n attributes[key] = a[key];\n }\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n\n export function diff(\n a: AttributeMap = {},\n b: AttributeMap = {},\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n a = {};\n }\n if (typeof b !== 'object') {\n b = {};\n }\n const attributes = Object.keys(a)\n .concat(Object.keys(b))\n .reduce((attrs, key) => {\n if (!isEqual(a[key], b[key])) {\n attrs[key] = b[key] === undefined ? null : b[key];\n }\n return attrs;\n }, {});\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n\n export function invert(\n attr: AttributeMap = {},\n base: AttributeMap = {},\n ): AttributeMap {\n attr = attr || {};\n const baseInverted = Object.keys(base).reduce((memo, key) => {\n if (base[key] !== attr[key] && attr[key] !== undefined) {\n memo[key] = base[key];\n }\n return memo;\n }, {});\n return Object.keys(attr).reduce((memo, key) => {\n if (attr[key] !== base[key] && base[key] === undefined) {\n memo[key] = null;\n }\n return memo;\n }, baseInverted);\n }\n\n export function transform(\n a: AttributeMap | undefined,\n b: AttributeMap | undefined,\n priority = false,\n ): AttributeMap | undefined {\n if (typeof a !== 'object') {\n return b;\n }\n if (typeof b !== 'object') {\n return undefined;\n }\n if (!priority) {\n return b; // b simply overwrites us without priority\n }\n const attributes = Object.keys(b).reduce((attrs, key) => {\n if (a[key] === undefined) {\n attrs[key] = b[key]; // null is a valid value\n }\n return attrs;\n }, {});\n return Object.keys(attributes).length > 0 ? attributes : undefined;\n }\n}\n\nexport default AttributeMap;\n", "import AttributeMap from './AttributeMap';\n\ninterface Op {\n // only one property out of {insert, delete, retain} will be present\n insert?: string | Record;\n delete?: number;\n retain?: number | Record;\n\n attributes?: AttributeMap;\n}\n\nnamespace Op {\n export function length(op: Op): number {\n if (typeof op.delete === 'number') {\n return op.delete;\n } else if (typeof op.retain === 'number') {\n return op.retain;\n } else if (typeof op.retain === 'object' && op.retain !== null) {\n return 1;\n } else {\n return typeof op.insert === 'string' ? op.insert.length : 1;\n }\n }\n}\n\nexport default Op;\n", "import Op from './Op';\n\nexport default class Iterator {\n ops: Op[];\n index: number;\n offset: number;\n\n constructor(ops: Op[]) {\n this.ops = ops;\n this.index = 0;\n this.offset = 0;\n }\n\n hasNext(): boolean {\n return this.peekLength() < Infinity;\n }\n\n next(length?: number): Op {\n if (!length) {\n length = Infinity;\n }\n const nextOp = this.ops[this.index];\n if (nextOp) {\n const offset = this.offset;\n const opLength = Op.length(nextOp);\n if (length >= opLength - offset) {\n length = opLength - offset;\n this.index += 1;\n this.offset = 0;\n } else {\n this.offset += length;\n }\n if (typeof nextOp.delete === 'number') {\n return { delete: length };\n } else {\n const retOp: Op = {};\n if (nextOp.attributes) {\n retOp.attributes = nextOp.attributes;\n }\n if (typeof nextOp.retain === 'number') {\n retOp.retain = length;\n } else if (\n typeof nextOp.retain === 'object' &&\n nextOp.retain !== null\n ) {\n // offset should === 0, length should === 1\n retOp.retain = nextOp.retain;\n } else if (typeof nextOp.insert === 'string') {\n retOp.insert = nextOp.insert.substr(offset, length);\n } else {\n // offset should === 0, length should === 1\n retOp.insert = nextOp.insert;\n }\n return retOp;\n }\n } else {\n return { retain: Infinity };\n }\n }\n\n peek(): Op {\n return this.ops[this.index];\n }\n\n peekLength(): number {\n if (this.ops[this.index]) {\n // Should never return 0 if our index is being managed correctly\n return Op.length(this.ops[this.index]) - this.offset;\n } else {\n return Infinity;\n }\n }\n\n peekType(): string {\n const op = this.ops[this.index];\n if (op) {\n if (typeof op.delete === 'number') {\n return 'delete';\n } else if (\n typeof op.retain === 'number' ||\n (typeof op.retain === 'object' && op.retain !== null)\n ) {\n return 'retain';\n } else {\n return 'insert';\n }\n }\n return 'retain';\n }\n\n rest(): Op[] {\n if (!this.hasNext()) {\n return [];\n } else if (this.offset === 0) {\n return this.ops.slice(this.index);\n } else {\n const offset = this.offset;\n const index = this.index;\n const next = this.next();\n const rest = this.ops.slice(this.index);\n this.offset = offset;\n this.index = index;\n return [next].concat(rest);\n }\n }\n}\n", "import * as diff from 'fast-diff';\nimport cloneDeep = require('lodash.clonedeep');\nimport isEqual = require('lodash.isequal');\nimport AttributeMap from './AttributeMap';\nimport Op from './Op';\nimport OpIterator from './OpIterator';\n\nconst NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff()\n\ninterface EmbedHandler {\n compose(a: T, b: T, keepNull: boolean): T;\n invert(a: T, b: T): T;\n transform(a: T, b: T, priority: boolean): T;\n}\n\nconst getEmbedTypeAndData = (\n a: Op['insert'] | Op['retain'],\n b: Op['insert'],\n): [string, unknown, unknown] => {\n if (typeof a !== 'object' || a === null) {\n throw new Error(`cannot retain a ${typeof a}`);\n }\n if (typeof b !== 'object' || b === null) {\n throw new Error(`cannot retain a ${typeof b}`);\n }\n const embedType = Object.keys(a)[0];\n if (!embedType || embedType !== Object.keys(b)[0]) {\n throw new Error(\n `embed types not matched: ${embedType} != ${Object.keys(b)[0]}`,\n );\n }\n return [embedType, a[embedType], b[embedType]];\n};\n\nclass Delta {\n static Op = Op;\n static OpIterator = OpIterator;\n static AttributeMap = AttributeMap;\n private static handlers: { [embedType: string]: EmbedHandler } = {};\n\n static registerEmbed(embedType: string, handler: EmbedHandler): void {\n this.handlers[embedType] = handler;\n }\n\n static unregisterEmbed(embedType: string): void {\n delete this.handlers[embedType];\n }\n\n private static getHandler(embedType: string): EmbedHandler {\n const handler = this.handlers[embedType];\n if (!handler) {\n throw new Error(`no handlers for embed type \"${embedType}\"`);\n }\n return handler;\n }\n\n ops: Op[];\n constructor(ops?: Op[] | { ops: Op[] }) {\n // Assume we are given a well formed ops\n if (Array.isArray(ops)) {\n this.ops = ops;\n } else if (ops != null && Array.isArray(ops.ops)) {\n this.ops = ops.ops;\n } else {\n this.ops = [];\n }\n }\n\n insert(\n arg: string | Record,\n attributes?: AttributeMap | null,\n ): this {\n const newOp: Op = {};\n if (typeof arg === 'string' && arg.length === 0) {\n return this;\n }\n newOp.insert = arg;\n if (\n attributes != null &&\n typeof attributes === 'object' &&\n Object.keys(attributes).length > 0\n ) {\n newOp.attributes = attributes;\n }\n return this.push(newOp);\n }\n\n delete(length: number): this {\n if (length <= 0) {\n return this;\n }\n return this.push({ delete: length });\n }\n\n retain(\n length: number | Record,\n attributes?: AttributeMap | null,\n ): this {\n if (typeof length === 'number' && length <= 0) {\n return this;\n }\n const newOp: Op = { retain: length };\n if (\n attributes != null &&\n typeof attributes === 'object' &&\n Object.keys(attributes).length > 0\n ) {\n newOp.attributes = attributes;\n }\n return this.push(newOp);\n }\n\n push(newOp: Op): this {\n let index = this.ops.length;\n let lastOp = this.ops[index - 1];\n newOp = cloneDeep(newOp);\n if (typeof lastOp === 'object') {\n if (\n typeof newOp.delete === 'number' &&\n typeof lastOp.delete === 'number'\n ) {\n this.ops[index - 1] = { delete: lastOp.delete + newOp.delete };\n return this;\n }\n // Since it does not matter if we insert before or after deleting at the same index,\n // always prefer to insert first\n if (typeof lastOp.delete === 'number' && newOp.insert != null) {\n index -= 1;\n lastOp = this.ops[index - 1];\n if (typeof lastOp !== 'object') {\n this.ops.unshift(newOp);\n return this;\n }\n }\n if (isEqual(newOp.attributes, lastOp.attributes)) {\n if (\n typeof newOp.insert === 'string' &&\n typeof lastOp.insert === 'string'\n ) {\n this.ops[index - 1] = { insert: lastOp.insert + newOp.insert };\n if (typeof newOp.attributes === 'object') {\n this.ops[index - 1].attributes = newOp.attributes;\n }\n return this;\n } else if (\n typeof newOp.retain === 'number' &&\n typeof lastOp.retain === 'number'\n ) {\n this.ops[index - 1] = { retain: lastOp.retain + newOp.retain };\n if (typeof newOp.attributes === 'object') {\n this.ops[index - 1].attributes = newOp.attributes;\n }\n return this;\n }\n }\n }\n if (index === this.ops.length) {\n this.ops.push(newOp);\n } else {\n this.ops.splice(index, 0, newOp);\n }\n return this;\n }\n\n chop(): this {\n const lastOp = this.ops[this.ops.length - 1];\n if (lastOp && typeof lastOp.retain === 'number' && !lastOp.attributes) {\n this.ops.pop();\n }\n return this;\n }\n\n filter(predicate: (op: Op, index: number) => boolean): Op[] {\n return this.ops.filter(predicate);\n }\n\n forEach(predicate: (op: Op, index: number) => void): void {\n this.ops.forEach(predicate);\n }\n\n map(predicate: (op: Op, index: number) => T): T[] {\n return this.ops.map(predicate);\n }\n\n partition(predicate: (op: Op) => boolean): [Op[], Op[]] {\n const passed: Op[] = [];\n const failed: Op[] = [];\n this.forEach((op) => {\n const target = predicate(op) ? passed : failed;\n target.push(op);\n });\n return [passed, failed];\n }\n\n reduce(\n predicate: (accum: T, curr: Op, index: number) => T,\n initialValue: T,\n ): T {\n return this.ops.reduce(predicate, initialValue);\n }\n\n changeLength(): number {\n return this.reduce((length, elem) => {\n if (elem.insert) {\n return length + Op.length(elem);\n } else if (elem.delete) {\n return length - elem.delete;\n }\n return length;\n }, 0);\n }\n\n length(): number {\n return this.reduce((length, elem) => {\n return length + Op.length(elem);\n }, 0);\n }\n\n slice(start = 0, end = Infinity): Delta {\n const ops = [];\n const iter = new OpIterator(this.ops);\n let index = 0;\n while (index < end && iter.hasNext()) {\n let nextOp;\n if (index < start) {\n nextOp = iter.next(start - index);\n } else {\n nextOp = iter.next(end - index);\n ops.push(nextOp);\n }\n index += Op.length(nextOp);\n }\n return new Delta(ops);\n }\n\n compose(other: Delta): Delta {\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n const ops = [];\n const firstOther = otherIter.peek();\n if (\n firstOther != null &&\n typeof firstOther.retain === 'number' &&\n firstOther.attributes == null\n ) {\n let firstLeft = firstOther.retain;\n while (\n thisIter.peekType() === 'insert' &&\n thisIter.peekLength() <= firstLeft\n ) {\n firstLeft -= thisIter.peekLength();\n ops.push(thisIter.next());\n }\n if (firstOther.retain - firstLeft > 0) {\n otherIter.next(firstOther.retain - firstLeft);\n }\n }\n const delta = new Delta(ops);\n while (thisIter.hasNext() || otherIter.hasNext()) {\n if (otherIter.peekType() === 'insert') {\n delta.push(otherIter.next());\n } else if (thisIter.peekType() === 'delete') {\n delta.push(thisIter.next());\n } else {\n const length = Math.min(thisIter.peekLength(), otherIter.peekLength());\n const thisOp = thisIter.next(length);\n const otherOp = otherIter.next(length);\n if (otherOp.retain) {\n const newOp: Op = {};\n if (typeof thisOp.retain === 'number') {\n newOp.retain =\n typeof otherOp.retain === 'number' ? length : otherOp.retain;\n } else {\n if (typeof otherOp.retain === 'number') {\n if (thisOp.retain == null) {\n newOp.insert = thisOp.insert;\n } else {\n newOp.retain = thisOp.retain;\n }\n } else {\n const action = thisOp.retain == null ? 'insert' : 'retain';\n const [embedType, thisData, otherData] = getEmbedTypeAndData(\n thisOp[action],\n otherOp.retain,\n );\n const handler = Delta.getHandler(embedType);\n newOp[action] = {\n [embedType]: handler.compose(\n thisData,\n otherData,\n action === 'retain',\n ),\n };\n }\n }\n // Preserve null when composing with a retain, otherwise remove it for inserts\n const attributes = AttributeMap.compose(\n thisOp.attributes,\n otherOp.attributes,\n typeof thisOp.retain === 'number',\n );\n if (attributes) {\n newOp.attributes = attributes;\n }\n delta.push(newOp);\n\n // Optimization if rest of other is just retain\n if (\n !otherIter.hasNext() &&\n isEqual(delta.ops[delta.ops.length - 1], newOp)\n ) {\n const rest = new Delta(thisIter.rest());\n return delta.concat(rest).chop();\n }\n\n // Other op should be delete, we could be an insert or retain\n // Insert + delete cancels out\n } else if (\n typeof otherOp.delete === 'number' &&\n (typeof thisOp.retain === 'number' ||\n (typeof thisOp.retain === 'object' && thisOp.retain !== null))\n ) {\n delta.push(otherOp);\n }\n }\n }\n return delta.chop();\n }\n\n concat(other: Delta): Delta {\n const delta = new Delta(this.ops.slice());\n if (other.ops.length > 0) {\n delta.push(other.ops[0]);\n delta.ops = delta.ops.concat(other.ops.slice(1));\n }\n return delta;\n }\n\n diff(other: Delta, cursor?: number | diff.CursorInfo): Delta {\n if (this.ops === other.ops) {\n return new Delta();\n }\n const strings = [this, other].map((delta) => {\n return delta\n .map((op) => {\n if (op.insert != null) {\n return typeof op.insert === 'string' ? op.insert : NULL_CHARACTER;\n }\n const prep = delta === other ? 'on' : 'with';\n throw new Error('diff() called ' + prep + ' non-document');\n })\n .join('');\n });\n const retDelta = new Delta();\n const diffResult = diff(strings[0], strings[1], cursor, true);\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n diffResult.forEach((component: diff.Diff) => {\n let length = component[1].length;\n while (length > 0) {\n let opLength = 0;\n switch (component[0]) {\n case diff.INSERT:\n opLength = Math.min(otherIter.peekLength(), length);\n retDelta.push(otherIter.next(opLength));\n break;\n case diff.DELETE:\n opLength = Math.min(length, thisIter.peekLength());\n thisIter.next(opLength);\n retDelta.delete(opLength);\n break;\n case diff.EQUAL:\n opLength = Math.min(\n thisIter.peekLength(),\n otherIter.peekLength(),\n length,\n );\n const thisOp = thisIter.next(opLength);\n const otherOp = otherIter.next(opLength);\n if (isEqual(thisOp.insert, otherOp.insert)) {\n retDelta.retain(\n opLength,\n AttributeMap.diff(thisOp.attributes, otherOp.attributes),\n );\n } else {\n retDelta.push(otherOp).delete(opLength);\n }\n break;\n }\n length -= opLength;\n }\n });\n return retDelta.chop();\n }\n\n eachLine(\n predicate: (\n line: Delta,\n attributes: AttributeMap,\n index: number,\n ) => boolean | void,\n newline = '\\n',\n ): void {\n const iter = new OpIterator(this.ops);\n let line = new Delta();\n let i = 0;\n while (iter.hasNext()) {\n if (iter.peekType() !== 'insert') {\n return;\n }\n const thisOp = iter.peek();\n const start = Op.length(thisOp) - iter.peekLength();\n const index =\n typeof thisOp.insert === 'string'\n ? thisOp.insert.indexOf(newline, start) - start\n : -1;\n if (index < 0) {\n line.push(iter.next());\n } else if (index > 0) {\n line.push(iter.next(index));\n } else {\n if (predicate(line, iter.next(1).attributes || {}, i) === false) {\n return;\n }\n i += 1;\n line = new Delta();\n }\n }\n if (line.length() > 0) {\n predicate(line, {}, i);\n }\n }\n\n invert(base: Delta): Delta {\n const inverted = new Delta();\n this.reduce((baseIndex, op) => {\n if (op.insert) {\n inverted.delete(Op.length(op));\n } else if (typeof op.retain === 'number' && op.attributes == null) {\n inverted.retain(op.retain);\n return baseIndex + op.retain;\n } else if (op.delete || typeof op.retain === 'number') {\n const length = (op.delete || op.retain) as number;\n const slice = base.slice(baseIndex, baseIndex + length);\n slice.forEach((baseOp) => {\n if (op.delete) {\n inverted.push(baseOp);\n } else if (op.retain && op.attributes) {\n inverted.retain(\n Op.length(baseOp),\n AttributeMap.invert(op.attributes, baseOp.attributes),\n );\n }\n });\n return baseIndex + length;\n } else if (typeof op.retain === 'object' && op.retain !== null) {\n const slice = base.slice(baseIndex, baseIndex + 1);\n const baseOp = new OpIterator(slice.ops).next();\n const [embedType, opData, baseOpData] = getEmbedTypeAndData(\n op.retain,\n baseOp.insert,\n );\n const handler = Delta.getHandler(embedType);\n inverted.retain(\n { [embedType]: handler.invert(opData, baseOpData) },\n AttributeMap.invert(op.attributes, baseOp.attributes),\n );\n return baseIndex + 1;\n }\n return baseIndex;\n }, 0);\n return inverted.chop();\n }\n\n transform(index: number, priority?: boolean): number;\n transform(other: Delta, priority?: boolean): Delta;\n transform(arg: number | Delta, priority = false): typeof arg {\n priority = !!priority;\n if (typeof arg === 'number') {\n return this.transformPosition(arg, priority);\n }\n const other: Delta = arg;\n const thisIter = new OpIterator(this.ops);\n const otherIter = new OpIterator(other.ops);\n const delta = new Delta();\n while (thisIter.hasNext() || otherIter.hasNext()) {\n if (\n thisIter.peekType() === 'insert' &&\n (priority || otherIter.peekType() !== 'insert')\n ) {\n delta.retain(Op.length(thisIter.next()));\n } else if (otherIter.peekType() === 'insert') {\n delta.push(otherIter.next());\n } else {\n const length = Math.min(thisIter.peekLength(), otherIter.peekLength());\n const thisOp = thisIter.next(length);\n const otherOp = otherIter.next(length);\n if (thisOp.delete) {\n // Our delete either makes their delete redundant or removes their retain\n continue;\n } else if (otherOp.delete) {\n delta.push(otherOp);\n } else {\n const thisData = thisOp.retain;\n const otherData = otherOp.retain;\n let transformedData: Op['retain'] =\n typeof otherData === 'object' && otherData !== null\n ? otherData\n : length;\n if (\n typeof thisData === 'object' &&\n thisData !== null &&\n typeof otherData === 'object' &&\n otherData !== null\n ) {\n const embedType = Object.keys(thisData)[0];\n if (embedType === Object.keys(otherData)[0]) {\n const handler = Delta.getHandler(embedType);\n if (handler) {\n transformedData = {\n [embedType]: handler.transform(\n thisData[embedType],\n otherData[embedType],\n priority,\n ),\n };\n }\n }\n }\n\n // We retain either their retain or insert\n delta.retain(\n transformedData,\n AttributeMap.transform(\n thisOp.attributes,\n otherOp.attributes,\n priority,\n ),\n );\n }\n }\n }\n return delta.chop();\n }\n\n transformPosition(index: number, priority = false): number {\n priority = !!priority;\n const thisIter = new OpIterator(this.ops);\n let offset = 0;\n while (thisIter.hasNext() && offset <= index) {\n const length = thisIter.peekLength();\n const nextType = thisIter.peekType();\n thisIter.next();\n if (nextType === 'delete') {\n index -= Math.min(length, index - offset);\n continue;\n } else if (nextType === 'insert' && (offset < index || !priority)) {\n index += length;\n }\n offset += length;\n }\n return index;\n }\n}\n\nexport default Delta;\n\nexport { Op, OpIterator, AttributeMap };\n\nif (typeof module === 'object') {\n module.exports = Delta;\n module.exports.default = Delta;\n}\n", "import { EmbedBlot } from 'parchment';\n\nclass Break extends EmbedBlot {\n static value() {\n return undefined;\n }\n\n optimize() {\n if (this.prev || this.next) {\n this.remove();\n }\n }\n\n length() {\n return 0;\n }\n\n value() {\n return '';\n }\n}\nBreak.blotName = 'break';\nBreak.tagName = 'BR';\n\nexport default Break;\n", "import { TextBlot } from 'parchment';\n\nclass Text extends TextBlot {}\n\nfunction escapeText(text: string) {\n return text.replace(/[&<>\"']/g, (s) => {\n // https://lodash.com/docs#escape\n const entityMap: Record = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n };\n return entityMap[s];\n });\n}\n\nexport { Text as default, escapeText };\n", "import { EmbedBlot, InlineBlot, Scope } from 'parchment';\nimport type { BlotConstructor } from 'parchment';\nimport Break from './break.js';\nimport Text from './text.js';\n\nclass Inline extends InlineBlot {\n static allowedChildren: BlotConstructor[] = [Inline, Break, EmbedBlot, Text];\n // Lower index means deeper in the DOM tree, since not found (-1) is for embeds\n static order = [\n 'cursor',\n 'inline', // Must be lower\n 'link', // Chrome wants to be lower\n 'underline',\n 'strike',\n 'italic',\n 'bold',\n 'script',\n 'code', // Must be higher\n ];\n\n static compare(self: string, other: string) {\n const selfIndex = Inline.order.indexOf(self);\n const otherIndex = Inline.order.indexOf(other);\n if (selfIndex >= 0 || otherIndex >= 0) {\n return selfIndex - otherIndex;\n }\n if (self === other) {\n return 0;\n }\n if (self < other) {\n return -1;\n }\n return 1;\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (\n Inline.compare(this.statics.blotName, name) < 0 &&\n this.scroll.query(name, Scope.BLOT)\n ) {\n const blot = this.isolate(index, length);\n if (value) {\n blot.wrap(name, value);\n }\n } else {\n super.formatAt(index, length, name, value);\n }\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n if (\n this.parent instanceof Inline &&\n Inline.compare(this.statics.blotName, this.parent.statics.blotName) > 0\n ) {\n const parent = this.parent.isolate(this.offset(), this.length());\n // @ts-expect-error TODO: make isolate generic\n this.moveChildren(parent);\n parent.wrap(this);\n }\n }\n}\n\nexport default Inline;\n", "import {\n AttributorStore,\n BlockBlot,\n EmbedBlot,\n LeafBlot,\n Scope,\n} from 'parchment';\nimport type { Blot, Parent } from 'parchment';\nimport Delta from 'quill-delta';\nimport Break from './break.js';\nimport Inline from './inline.js';\nimport TextBlot from './text.js';\n\nconst NEWLINE_LENGTH = 1;\n\nclass Block extends BlockBlot {\n cache: { delta?: Delta | null; length?: number } = {};\n\n delta(): Delta {\n if (this.cache.delta == null) {\n this.cache.delta = blockDelta(this);\n }\n return this.cache.delta;\n }\n\n deleteAt(index: number, length: number) {\n super.deleteAt(index, length);\n this.cache = {};\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (length <= 0) return;\n if (this.scroll.query(name, Scope.BLOCK)) {\n if (index + length === this.length()) {\n this.format(name, value);\n }\n } else {\n super.formatAt(\n index,\n Math.min(length, this.length() - index - 1),\n name,\n value,\n );\n }\n this.cache = {};\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (def != null) {\n super.insertAt(index, value, def);\n this.cache = {};\n return;\n }\n if (value.length === 0) return;\n const lines = value.split('\\n');\n const text = lines.shift() as string;\n if (text.length > 0) {\n if (index < this.length() - 1 || this.children.tail == null) {\n super.insertAt(Math.min(index, this.length() - 1), text);\n } else {\n this.children.tail.insertAt(this.children.tail.length(), text);\n }\n this.cache = {};\n }\n // TODO: Fix this next time the file is edited.\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let block: Blot | this = this;\n lines.reduce((lineIndex, line) => {\n // @ts-expect-error Fix me later\n block = block.split(lineIndex, true);\n block.insertAt(0, line);\n return line.length;\n }, index + text.length);\n }\n\n insertBefore(blot: Blot, ref?: Blot | null) {\n const { head } = this.children;\n super.insertBefore(blot, ref);\n if (head instanceof Break) {\n head.remove();\n }\n this.cache = {};\n }\n\n length() {\n if (this.cache.length == null) {\n this.cache.length = super.length() + NEWLINE_LENGTH;\n }\n return this.cache.length;\n }\n\n moveChildren(target: Parent, ref?: Blot | null) {\n super.moveChildren(target, ref);\n this.cache = {};\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n this.cache = {};\n }\n\n path(index: number) {\n return super.path(index, true);\n }\n\n removeChild(child: Blot) {\n super.removeChild(child);\n this.cache = {};\n }\n\n split(index: number, force: boolean | undefined = false): Blot | null {\n if (force && (index === 0 || index >= this.length() - NEWLINE_LENGTH)) {\n const clone = this.clone();\n if (index === 0) {\n this.parent.insertBefore(clone, this);\n return this;\n }\n this.parent.insertBefore(clone, this.next);\n return clone;\n }\n const next = super.split(index, force);\n this.cache = {};\n return next;\n }\n}\nBlock.blotName = 'block';\nBlock.tagName = 'P';\nBlock.defaultChild = Break;\nBlock.allowedChildren = [Break, Inline, EmbedBlot, TextBlot];\n\nclass BlockEmbed extends EmbedBlot {\n attributes: AttributorStore;\n domNode: HTMLElement;\n\n attach() {\n super.attach();\n this.attributes = new AttributorStore(this.domNode);\n }\n\n delta() {\n return new Delta().insert(this.value(), {\n ...this.formats(),\n ...this.attributes.values(),\n });\n }\n\n format(name: string, value: unknown) {\n const attribute = this.scroll.query(name, Scope.BLOCK_ATTRIBUTE);\n if (attribute != null) {\n // @ts-expect-error TODO: Scroll#query() should return Attributor when scope is attribute\n this.attributes.attribute(attribute, value);\n }\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n this.format(name, value);\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (def != null) {\n super.insertAt(index, value, def);\n return;\n }\n const lines = value.split('\\n');\n const text = lines.pop();\n const blocks = lines.map((line) => {\n const block = this.scroll.create(Block.blotName);\n block.insertAt(0, line);\n return block;\n });\n const ref = this.split(index);\n blocks.forEach((block) => {\n this.parent.insertBefore(block, ref);\n });\n if (text) {\n this.parent.insertBefore(this.scroll.create('text', text), ref);\n }\n }\n}\nBlockEmbed.scope = Scope.BLOCK_BLOT;\n// It is important for cursor behavior BlockEmbeds use tags that are block level elements\n\nfunction blockDelta(blot: BlockBlot, filter = true) {\n return blot\n .descendants(LeafBlot)\n .reduce((delta, leaf) => {\n if (leaf.length() === 0) {\n return delta;\n }\n return delta.insert(leaf.value(), bubbleFormats(leaf, {}, filter));\n }, new Delta())\n .insert('\\n', bubbleFormats(blot));\n}\n\nfunction bubbleFormats(\n blot: Blot | null,\n formats: Record = {},\n filter = true,\n): Record {\n if (blot == null) return formats;\n if ('formats' in blot && typeof blot.formats === 'function') {\n formats = {\n ...formats,\n ...blot.formats(),\n };\n if (filter) {\n // exclude syntax highlighting from deltas and getFormat()\n delete formats['code-token'];\n }\n }\n if (\n blot.parent == null ||\n blot.parent.statics.blotName === 'scroll' ||\n blot.parent.statics.scope !== blot.statics.scope\n ) {\n return formats;\n }\n return bubbleFormats(blot.parent, formats, filter);\n}\n\nexport { blockDelta, bubbleFormats, BlockEmbed, Block as default };\n", "import { EmbedBlot, Scope } from 'parchment';\nimport type { Parent, ScrollBlot } from 'parchment';\nimport type Selection from '../core/selection.js';\nimport TextBlot from './text.js';\nimport type { EmbedContextRange } from './embed.js';\n\nclass Cursor extends EmbedBlot {\n static blotName = 'cursor';\n static className = 'ql-cursor';\n static tagName = 'span';\n static CONTENTS = '\\uFEFF'; // Zero width no break space\n\n static value() {\n return undefined;\n }\n\n selection: Selection;\n textNode: Text;\n savedLength: number;\n\n constructor(scroll: ScrollBlot, domNode: HTMLElement, selection: Selection) {\n super(scroll, domNode);\n this.selection = selection;\n this.textNode = document.createTextNode(Cursor.CONTENTS);\n this.domNode.appendChild(this.textNode);\n this.savedLength = 0;\n }\n\n detach() {\n // super.detach() will also clear domNode.__blot\n if (this.parent != null) this.parent.removeChild(this);\n }\n\n format(name: string, value: unknown) {\n if (this.savedLength !== 0) {\n super.format(name, value);\n return;\n }\n // TODO: Fix this next time the file is edited.\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let target: Parent | this = this;\n let index = 0;\n while (target != null && target.statics.scope !== Scope.BLOCK_BLOT) {\n index += target.offset(target.parent);\n target = target.parent;\n }\n if (target != null) {\n this.savedLength = Cursor.CONTENTS.length;\n // @ts-expect-error TODO: allow empty context in Parchment\n target.optimize();\n target.formatAt(index, Cursor.CONTENTS.length, name, value);\n this.savedLength = 0;\n }\n }\n\n index(node: Node, offset: number) {\n if (node === this.textNode) return 0;\n return super.index(node, offset);\n }\n\n length() {\n return this.savedLength;\n }\n\n position(): [Text, number] {\n return [this.textNode, this.textNode.data.length];\n }\n\n remove() {\n super.remove();\n // @ts-expect-error Fix me later\n this.parent = null;\n }\n\n restore(): EmbedContextRange | null {\n if (this.selection.composing || this.parent == null) return null;\n const range = this.selection.getNativeRange();\n // Browser may push down styles/nodes inside the cursor blot.\n // https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#push-down-values\n while (\n this.domNode.lastChild != null &&\n this.domNode.lastChild !== this.textNode\n ) {\n // @ts-expect-error Fix me later\n this.domNode.parentNode.insertBefore(\n this.domNode.lastChild,\n this.domNode,\n );\n }\n\n const prevTextBlot = this.prev instanceof TextBlot ? this.prev : null;\n const prevTextLength = prevTextBlot ? prevTextBlot.length() : 0;\n const nextTextBlot = this.next instanceof TextBlot ? this.next : null;\n // @ts-expect-error TODO: make TextBlot.text public\n const nextText = nextTextBlot ? nextTextBlot.text : '';\n const { textNode } = this;\n // take text from inside this blot and reset it\n const newText = textNode.data.split(Cursor.CONTENTS).join('');\n textNode.data = Cursor.CONTENTS;\n\n // proactively merge TextBlots around cursor so that optimization\n // doesn't lose the cursor. the reason we are here in cursor.restore\n // could be that the user clicked in prevTextBlot or nextTextBlot, or\n // the user typed something.\n let mergedTextBlot;\n if (prevTextBlot) {\n mergedTextBlot = prevTextBlot;\n if (newText || nextTextBlot) {\n prevTextBlot.insertAt(prevTextBlot.length(), newText + nextText);\n if (nextTextBlot) {\n nextTextBlot.remove();\n }\n }\n } else if (nextTextBlot) {\n mergedTextBlot = nextTextBlot;\n nextTextBlot.insertAt(0, newText);\n } else {\n const newTextNode = document.createTextNode(newText);\n mergedTextBlot = this.scroll.create(newTextNode);\n this.parent.insertBefore(mergedTextBlot, this);\n }\n\n this.remove();\n if (range) {\n // calculate selection to restore\n const remapOffset = (node: Node, offset: number) => {\n if (prevTextBlot && node === prevTextBlot.domNode) {\n return offset;\n }\n if (node === textNode) {\n return prevTextLength + offset - 1;\n }\n if (nextTextBlot && node === nextTextBlot.domNode) {\n return prevTextLength + newText.length + offset;\n }\n return null;\n };\n\n const start = remapOffset(range.start.node, range.start.offset);\n const end = remapOffset(range.end.node, range.end.offset);\n if (start !== null && end !== null) {\n return {\n startNode: mergedTextBlot.domNode,\n startOffset: start,\n endNode: mergedTextBlot.domNode,\n endOffset: end,\n };\n }\n }\n return null;\n }\n\n update(mutations: MutationRecord[], context: Record) {\n if (\n mutations.some((mutation) => {\n return (\n mutation.type === 'characterData' && mutation.target === this.textNode\n );\n })\n ) {\n const range = this.restore();\n if (range) context.range = range;\n }\n }\n\n // Avoid .ql-cursor being a descendant of ``.\n // The reason is Safari pushes down `` on text insertion.\n // That will cause DOM nodes not sync with the model.\n //\n // For example ({I} is the caret), given the markup:\n // \\uFEFF{I}\n // When typing a char \"x\", `` will be pushed down inside the `` first:\n // \\uFEFF{I}\n // And then \"x\" will be inserted after ``:\n // \\uFEFFd{I}\n optimize(context?: unknown) {\n // @ts-expect-error Fix me later\n super.optimize(context);\n\n let { parent } = this;\n while (parent) {\n if (parent.domNode.tagName === 'A') {\n this.savedLength = Cursor.CONTENTS.length;\n // @ts-expect-error TODO: make isolate generic\n parent.isolate(this.offset(parent), this.length()).unwrap();\n this.savedLength = 0;\n break;\n }\n parent = parent.parent;\n }\n }\n\n value() {\n return '';\n }\n}\n\nexport default Cursor;\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "import type Quill from '../core.js';\n\nexport default new WeakMap();\n", "const levels = ['error', 'warn', 'log', 'info'] as const;\nexport type DebugLevel = (typeof levels)[number];\nlet level: DebugLevel | false = 'warn';\n\nfunction debug(method: DebugLevel, ...args: unknown[]) {\n if (level) {\n if (levels.indexOf(method) <= levels.indexOf(level)) {\n console[method](...args); // eslint-disable-line no-console\n }\n }\n}\n\nfunction namespace(\n ns: string,\n): Record void> {\n return levels.reduce(\n (logger, method) => {\n logger[method] = debug.bind(console, method, ns);\n return logger;\n },\n {} as Record void>,\n );\n}\n\nnamespace.level = (newLevel: DebugLevel | false) => {\n level = newLevel;\n};\ndebug.level = namespace.level;\n\nexport default namespace;\n", "import { EventEmitter } from 'eventemitter3';\nimport instances from './instances.js';\nimport logger from './logger.js';\n\nconst debug = logger('quill:events');\nconst EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click'];\n\nEVENTS.forEach((eventName) => {\n document.addEventListener(eventName, (...args) => {\n Array.from(document.querySelectorAll('.ql-container')).forEach((node) => {\n const quill = instances.get(node);\n if (quill && quill.emitter) {\n quill.emitter.handleDOM(...args);\n }\n });\n });\n});\n\nclass Emitter extends EventEmitter {\n static events = {\n EDITOR_CHANGE: 'editor-change',\n SCROLL_BEFORE_UPDATE: 'scroll-before-update',\n SCROLL_BLOT_MOUNT: 'scroll-blot-mount',\n SCROLL_BLOT_UNMOUNT: 'scroll-blot-unmount',\n SCROLL_OPTIMIZE: 'scroll-optimize',\n SCROLL_UPDATE: 'scroll-update',\n SCROLL_EMBED_UPDATE: 'scroll-embed-update',\n SELECTION_CHANGE: 'selection-change',\n TEXT_CHANGE: 'text-change',\n COMPOSITION_BEFORE_START: 'composition-before-start',\n COMPOSITION_START: 'composition-start',\n COMPOSITION_BEFORE_END: 'composition-before-end',\n COMPOSITION_END: 'composition-end',\n } as const;\n\n static sources = {\n API: 'api',\n SILENT: 'silent',\n USER: 'user',\n } as const;\n\n protected domListeners: Record;\n\n constructor() {\n super();\n this.domListeners = {};\n this.on('error', debug.error);\n }\n\n emit(...args: unknown[]): boolean {\n debug.log.call(debug, ...args);\n // @ts-expect-error\n return super.emit(...args);\n }\n\n handleDOM(event: Event, ...args: unknown[]) {\n (this.domListeners[event.type] || []).forEach(({ node, handler }) => {\n if (event.target === node || node.contains(event.target as Node)) {\n handler(event, ...args);\n }\n });\n }\n\n listenDOM(eventName: string, node: Node, handler: EventListener) {\n if (!this.domListeners[eventName]) {\n this.domListeners[eventName] = [];\n }\n this.domListeners[eventName].push({ node, handler });\n }\n}\n\nexport type EmitterSource =\n (typeof Emitter.sources)[keyof typeof Emitter.sources];\n\nexport default Emitter;\n", "import { LeafBlot, Scope } from 'parchment';\nimport { cloneDeep, isEqual } from 'lodash-es';\nimport Emitter from './emitter.js';\nimport type { EmitterSource } from './emitter.js';\nimport logger from './logger.js';\nimport type Cursor from '../blots/cursor.js';\nimport type Scroll from '../blots/scroll.js';\n\nconst debug = logger('quill:selection');\n\ntype NativeRange = AbstractRange;\n\ninterface NormalizedRange {\n start: {\n node: NativeRange['startContainer'];\n offset: NativeRange['startOffset'];\n };\n end: { node: NativeRange['endContainer']; offset: NativeRange['endOffset'] };\n native: NativeRange;\n}\n\nexport interface Bounds {\n bottom: number;\n height: number;\n left: number;\n right: number;\n top: number;\n width: number;\n}\n\nexport class Range {\n constructor(\n public index: number,\n public length = 0,\n ) {}\n}\n\nclass Selection {\n scroll: Scroll;\n emitter: Emitter;\n composing: boolean;\n mouseDown: boolean;\n\n root: HTMLElement;\n cursor: Cursor;\n savedRange: Range;\n lastRange: Range | null;\n lastNative: NormalizedRange | null;\n\n constructor(scroll: Scroll, emitter: Emitter) {\n this.emitter = emitter;\n this.scroll = scroll;\n this.composing = false;\n this.mouseDown = false;\n this.root = this.scroll.domNode;\n // @ts-expect-error\n this.cursor = this.scroll.create('cursor', this);\n // savedRange is last non-null range\n this.savedRange = new Range(0, 0);\n this.lastRange = this.savedRange;\n this.lastNative = null;\n this.handleComposition();\n this.handleDragging();\n this.emitter.listenDOM('selectionchange', document, () => {\n if (!this.mouseDown && !this.composing) {\n setTimeout(this.update.bind(this, Emitter.sources.USER), 1);\n }\n });\n this.emitter.on(Emitter.events.SCROLL_BEFORE_UPDATE, () => {\n if (!this.hasFocus()) return;\n const native = this.getNativeRange();\n if (native == null) return;\n if (native.start.node === this.cursor.textNode) return; // cursor.restore() will handle\n this.emitter.once(\n Emitter.events.SCROLL_UPDATE,\n (source, mutations: MutationRecord[]) => {\n try {\n if (\n this.root.contains(native.start.node) &&\n this.root.contains(native.end.node)\n ) {\n this.setNativeRange(\n native.start.node,\n native.start.offset,\n native.end.node,\n native.end.offset,\n );\n }\n const triggeredByTyping = mutations.some(\n (mutation) =>\n mutation.type === 'characterData' ||\n mutation.type === 'childList' ||\n (mutation.type === 'attributes' &&\n mutation.target === this.root),\n );\n this.update(triggeredByTyping ? Emitter.sources.SILENT : source);\n } catch (ignored) {\n // ignore\n }\n },\n );\n });\n this.emitter.on(Emitter.events.SCROLL_OPTIMIZE, (mutations, context) => {\n if (context.range) {\n const { startNode, startOffset, endNode, endOffset } = context.range;\n this.setNativeRange(startNode, startOffset, endNode, endOffset);\n this.update(Emitter.sources.SILENT);\n }\n });\n this.update(Emitter.sources.SILENT);\n }\n\n handleComposition() {\n this.emitter.on(Emitter.events.COMPOSITION_BEFORE_START, () => {\n this.composing = true;\n });\n this.emitter.on(Emitter.events.COMPOSITION_END, () => {\n this.composing = false;\n if (this.cursor.parent) {\n const range = this.cursor.restore();\n if (!range) return;\n setTimeout(() => {\n this.setNativeRange(\n range.startNode,\n range.startOffset,\n range.endNode,\n range.endOffset,\n );\n }, 1);\n }\n });\n }\n\n handleDragging() {\n this.emitter.listenDOM('mousedown', document.body, () => {\n this.mouseDown = true;\n });\n this.emitter.listenDOM('mouseup', document.body, () => {\n this.mouseDown = false;\n this.update(Emitter.sources.USER);\n });\n }\n\n focus() {\n if (this.hasFocus()) return;\n this.root.focus({ preventScroll: true });\n this.setRange(this.savedRange);\n }\n\n format(format: string, value: unknown) {\n this.scroll.update();\n const nativeRange = this.getNativeRange();\n if (\n nativeRange == null ||\n !nativeRange.native.collapsed ||\n this.scroll.query(format, Scope.BLOCK)\n )\n return;\n if (nativeRange.start.node !== this.cursor.textNode) {\n const blot = this.scroll.find(nativeRange.start.node, false);\n if (blot == null) return;\n // TODO Give blot ability to not split\n if (blot instanceof LeafBlot) {\n const after = blot.split(nativeRange.start.offset);\n blot.parent.insertBefore(this.cursor, after);\n } else {\n // @ts-expect-error TODO: nativeRange.start.node doesn't seem to match function signature\n blot.insertBefore(this.cursor, nativeRange.start.node); // Should never happen\n }\n this.cursor.attach();\n }\n this.cursor.format(format, value);\n this.scroll.optimize();\n this.setNativeRange(this.cursor.textNode, this.cursor.textNode.data.length);\n this.update();\n }\n\n getBounds(index: number, length = 0) {\n const scrollLength = this.scroll.length();\n index = Math.min(index, scrollLength - 1);\n length = Math.min(index + length, scrollLength - 1) - index;\n let node: Node;\n let [leaf, offset] = this.scroll.leaf(index);\n if (leaf == null) return null;\n if (length > 0 && offset === leaf.length()) {\n const [next] = this.scroll.leaf(index + 1);\n if (next) {\n const [line] = this.scroll.line(index);\n const [nextLine] = this.scroll.line(index + 1);\n if (line === nextLine) {\n leaf = next;\n offset = 0;\n }\n }\n }\n [node, offset] = leaf.position(offset, true);\n const range = document.createRange();\n if (length > 0) {\n range.setStart(node, offset);\n [leaf, offset] = this.scroll.leaf(index + length);\n if (leaf == null) return null;\n [node, offset] = leaf.position(offset, true);\n range.setEnd(node, offset);\n return range.getBoundingClientRect();\n }\n let side: 'left' | 'right' = 'left';\n let rect: DOMRect;\n if (node instanceof Text) {\n // Return null if the text node is empty because it is\n // not able to get a useful client rect:\n // https://github.com/w3c/csswg-drafts/issues/2514.\n // Empty text nodes are most likely caused by TextBlot#optimize()\n // not getting called when editor content changes.\n if (!node.data.length) {\n return null;\n }\n if (offset < node.data.length) {\n range.setStart(node, offset);\n range.setEnd(node, offset + 1);\n } else {\n range.setStart(node, offset - 1);\n range.setEnd(node, offset);\n side = 'right';\n }\n rect = range.getBoundingClientRect();\n } else {\n if (!(leaf.domNode instanceof Element)) return null;\n rect = leaf.domNode.getBoundingClientRect();\n if (offset > 0) side = 'right';\n }\n return {\n bottom: rect.top + rect.height,\n height: rect.height,\n left: rect[side],\n right: rect[side],\n top: rect.top,\n width: 0,\n };\n }\n\n getNativeRange(): NormalizedRange | null {\n const selection = document.getSelection();\n if (selection == null || selection.rangeCount <= 0) return null;\n const nativeRange = selection.getRangeAt(0);\n if (nativeRange == null) return null;\n const range = this.normalizeNative(nativeRange);\n debug.info('getNativeRange', range);\n return range;\n }\n\n getRange(): [Range, NormalizedRange] | [null, null] {\n const root = this.scroll.domNode;\n if ('isConnected' in root && !root.isConnected) {\n // document.getSelection() forces layout on Blink, so we trend to\n // not calling it.\n return [null, null];\n }\n const normalized = this.getNativeRange();\n if (normalized == null) return [null, null];\n const range = this.normalizedToRange(normalized);\n return [range, normalized];\n }\n\n hasFocus(): boolean {\n return (\n document.activeElement === this.root ||\n (document.activeElement != null &&\n contains(this.root, document.activeElement))\n );\n }\n\n normalizedToRange(range: NormalizedRange) {\n const positions: [Node, number][] = [\n [range.start.node, range.start.offset],\n ];\n if (!range.native.collapsed) {\n positions.push([range.end.node, range.end.offset]);\n }\n const indexes = positions.map((position) => {\n const [node, offset] = position;\n const blot = this.scroll.find(node, true);\n // @ts-expect-error Fix me later\n const index = blot.offset(this.scroll);\n if (offset === 0) {\n return index;\n }\n if (blot instanceof LeafBlot) {\n return index + blot.index(node, offset);\n }\n // @ts-expect-error Fix me later\n return index + blot.length();\n });\n const end = Math.min(Math.max(...indexes), this.scroll.length() - 1);\n const start = Math.min(end, ...indexes);\n return new Range(start, end - start);\n }\n\n normalizeNative(nativeRange: NativeRange) {\n if (\n !contains(this.root, nativeRange.startContainer) ||\n (!nativeRange.collapsed && !contains(this.root, nativeRange.endContainer))\n ) {\n return null;\n }\n const range = {\n start: {\n node: nativeRange.startContainer,\n offset: nativeRange.startOffset,\n },\n end: { node: nativeRange.endContainer, offset: nativeRange.endOffset },\n native: nativeRange,\n };\n [range.start, range.end].forEach((position) => {\n let { node, offset } = position;\n while (!(node instanceof Text) && node.childNodes.length > 0) {\n if (node.childNodes.length > offset) {\n node = node.childNodes[offset];\n offset = 0;\n } else if (node.childNodes.length === offset) {\n // @ts-expect-error Fix me later\n node = node.lastChild;\n if (node instanceof Text) {\n offset = node.data.length;\n } else if (node.childNodes.length > 0) {\n // Container case\n offset = node.childNodes.length;\n } else {\n // Embed case\n offset = node.childNodes.length + 1;\n }\n } else {\n break;\n }\n }\n position.node = node;\n position.offset = offset;\n });\n return range;\n }\n\n rangeToNative(range: Range): [Node | null, number, Node | null, number] {\n const scrollLength = this.scroll.length();\n\n const getPosition = (\n index: number,\n inclusive: boolean,\n ): [Node | null, number] => {\n index = Math.min(scrollLength - 1, index);\n const [leaf, leafOffset] = this.scroll.leaf(index);\n return leaf ? leaf.position(leafOffset, inclusive) : [null, -1];\n };\n return [\n ...getPosition(range.index, false),\n ...getPosition(range.index + range.length, true),\n ];\n }\n\n setNativeRange(\n startNode: Node | null,\n startOffset?: number,\n endNode = startNode,\n endOffset = startOffset,\n force = false,\n ) {\n debug.info('setNativeRange', startNode, startOffset, endNode, endOffset);\n if (\n startNode != null &&\n (this.root.parentNode == null ||\n startNode.parentNode == null ||\n // @ts-expect-error Fix me later\n endNode.parentNode == null)\n ) {\n return;\n }\n const selection = document.getSelection();\n if (selection == null) return;\n if (startNode != null) {\n if (!this.hasFocus()) this.root.focus({ preventScroll: true });\n const { native } = this.getNativeRange() || {};\n if (\n native == null ||\n force ||\n startNode !== native.startContainer ||\n startOffset !== native.startOffset ||\n endNode !== native.endContainer ||\n endOffset !== native.endOffset\n ) {\n if (startNode instanceof Element && startNode.tagName === 'BR') {\n // @ts-expect-error Fix me later\n startOffset = Array.from(startNode.parentNode.childNodes).indexOf(\n startNode,\n );\n startNode = startNode.parentNode;\n }\n if (endNode instanceof Element && endNode.tagName === 'BR') {\n // @ts-expect-error Fix me later\n endOffset = Array.from(endNode.parentNode.childNodes).indexOf(\n endNode,\n );\n endNode = endNode.parentNode;\n }\n const range = document.createRange();\n // @ts-expect-error Fix me later\n range.setStart(startNode, startOffset);\n // @ts-expect-error Fix me later\n range.setEnd(endNode, endOffset);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n } else {\n selection.removeAllRanges();\n this.root.blur();\n }\n }\n\n setRange(range: Range | null, force: boolean, source?: EmitterSource): void;\n setRange(range: Range | null, source?: EmitterSource): void;\n setRange(\n range: Range | null,\n force: boolean | EmitterSource = false,\n source: EmitterSource = Emitter.sources.API,\n ): void {\n if (typeof force === 'string') {\n source = force;\n force = false;\n }\n debug.info('setRange', range);\n if (range != null) {\n const args = this.rangeToNative(range);\n this.setNativeRange(...args, force);\n } else {\n this.setNativeRange(null);\n }\n this.update(source);\n }\n\n update(source: EmitterSource = Emitter.sources.USER) {\n const oldRange = this.lastRange;\n const [lastRange, nativeRange] = this.getRange();\n this.lastRange = lastRange;\n this.lastNative = nativeRange;\n if (this.lastRange != null) {\n this.savedRange = this.lastRange;\n }\n if (!isEqual(oldRange, this.lastRange)) {\n if (\n !this.composing &&\n nativeRange != null &&\n nativeRange.native.collapsed &&\n nativeRange.start.node !== this.cursor.textNode\n ) {\n const range = this.cursor.restore();\n if (range) {\n this.setNativeRange(\n range.startNode,\n range.startOffset,\n range.endNode,\n range.endOffset,\n );\n }\n }\n const args = [\n Emitter.events.SELECTION_CHANGE,\n cloneDeep(this.lastRange),\n cloneDeep(oldRange),\n source,\n ];\n this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);\n if (source !== Emitter.sources.SILENT) {\n this.emitter.emit(...args);\n }\n }\n }\n}\n\nfunction contains(parent: Node, descendant: Node) {\n try {\n // Firefox inserts inaccessible nodes around video elements\n descendant.parentNode; // eslint-disable-line @typescript-eslint/no-unused-expressions\n } catch (e) {\n return false;\n }\n return parent.contains(descendant);\n}\n\nexport default Selection;\n", "import { cloneDeep, isEqual, merge } from 'lodash-es';\nimport { LeafBlot, EmbedBlot, Scope, ParentBlot } from 'parchment';\nimport type { Blot } from 'parchment';\nimport Delta, { AttributeMap, Op } from 'quill-delta';\nimport Block, { BlockEmbed, bubbleFormats } from '../blots/block.js';\nimport Break from '../blots/break.js';\nimport CursorBlot from '../blots/cursor.js';\nimport type Scroll from '../blots/scroll.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport { Range } from './selection.js';\n\nconst ASCII = /^[ -~]*$/;\n\ntype SelectionInfo = {\n newRange: Range;\n oldRange: Range;\n};\n\nclass Editor {\n scroll: Scroll;\n delta: Delta;\n\n constructor(scroll: Scroll) {\n this.scroll = scroll;\n this.delta = this.getDelta();\n }\n\n applyDelta(delta: Delta): Delta {\n this.scroll.update();\n let scrollLength = this.scroll.length();\n this.scroll.batchStart();\n const normalizedDelta = normalizeDelta(delta);\n const deleteDelta = new Delta();\n const normalizedOps = splitOpLines(normalizedDelta.ops.slice());\n normalizedOps.reduce((index, op) => {\n const length = Op.length(op);\n let attributes = op.attributes || {};\n let isImplicitNewlinePrepended = false;\n let isImplicitNewlineAppended = false;\n if (op.insert != null) {\n deleteDelta.retain(length);\n if (typeof op.insert === 'string') {\n const text = op.insert;\n isImplicitNewlineAppended =\n !text.endsWith('\\n') &&\n (scrollLength <= index ||\n !!this.scroll.descendant(BlockEmbed, index)[0]);\n this.scroll.insertAt(index, text);\n const [line, offset] = this.scroll.line(index);\n let formats = merge({}, bubbleFormats(line));\n if (line instanceof Block) {\n const [leaf] = line.descendant(LeafBlot, offset);\n if (leaf) {\n formats = merge(formats, bubbleFormats(leaf));\n }\n }\n attributes = AttributeMap.diff(formats, attributes) || {};\n } else if (typeof op.insert === 'object') {\n const key = Object.keys(op.insert)[0]; // There should only be one key\n if (key == null) return index;\n const isInlineEmbed = this.scroll.query(key, Scope.INLINE) != null;\n if (isInlineEmbed) {\n if (\n scrollLength <= index ||\n !!this.scroll.descendant(BlockEmbed, index)[0]\n ) {\n isImplicitNewlineAppended = true;\n }\n } else if (index > 0) {\n const [leaf, offset] = this.scroll.descendant(LeafBlot, index - 1);\n if (leaf instanceof TextBlot) {\n const text = leaf.value();\n if (text[offset] !== '\\n') {\n isImplicitNewlinePrepended = true;\n }\n } else if (\n leaf instanceof EmbedBlot &&\n leaf.statics.scope === Scope.INLINE_BLOT\n ) {\n isImplicitNewlinePrepended = true;\n }\n }\n this.scroll.insertAt(index, key, op.insert[key]);\n\n if (isInlineEmbed) {\n const [leaf] = this.scroll.descendant(LeafBlot, index);\n if (leaf) {\n const formats = merge({}, bubbleFormats(leaf));\n attributes = AttributeMap.diff(formats, attributes) || {};\n }\n }\n }\n scrollLength += length;\n } else {\n deleteDelta.push(op);\n\n if (op.retain !== null && typeof op.retain === 'object') {\n const key = Object.keys(op.retain)[0];\n if (key == null) return index;\n this.scroll.updateEmbedAt(index, key, op.retain[key]);\n }\n }\n Object.keys(attributes).forEach((name) => {\n this.scroll.formatAt(index, length, name, attributes[name]);\n });\n const prependedLength = isImplicitNewlinePrepended ? 1 : 0;\n const addedLength = isImplicitNewlineAppended ? 1 : 0;\n scrollLength += prependedLength + addedLength;\n deleteDelta.retain(prependedLength);\n deleteDelta.delete(addedLength);\n return index + length + prependedLength + addedLength;\n }, 0);\n deleteDelta.reduce((index, op) => {\n if (typeof op.delete === 'number') {\n this.scroll.deleteAt(index, op.delete);\n return index;\n }\n return index + Op.length(op);\n }, 0);\n this.scroll.batchEnd();\n this.scroll.optimize();\n return this.update(normalizedDelta);\n }\n\n deleteText(index: number, length: number): Delta {\n this.scroll.deleteAt(index, length);\n return this.update(new Delta().retain(index).delete(length));\n }\n\n formatLine(\n index: number,\n length: number,\n formats: Record = {},\n ): Delta {\n this.scroll.update();\n Object.keys(formats).forEach((format) => {\n this.scroll.lines(index, Math.max(length, 1)).forEach((line) => {\n line.format(format, formats[format]);\n });\n });\n this.scroll.optimize();\n const delta = new Delta().retain(index).retain(length, cloneDeep(formats));\n return this.update(delta);\n }\n\n formatText(\n index: number,\n length: number,\n formats: Record = {},\n ): Delta {\n Object.keys(formats).forEach((format) => {\n this.scroll.formatAt(index, length, format, formats[format]);\n });\n const delta = new Delta().retain(index).retain(length, cloneDeep(formats));\n return this.update(delta);\n }\n\n getContents(index: number, length: number): Delta {\n return this.delta.slice(index, index + length);\n }\n\n getDelta(): Delta {\n return this.scroll.lines().reduce((delta, line) => {\n return delta.concat(line.delta());\n }, new Delta());\n }\n\n getFormat(index: number, length = 0): Record {\n let lines: (Block | BlockEmbed)[] = [];\n let leaves: LeafBlot[] = [];\n if (length === 0) {\n this.scroll.path(index).forEach((path) => {\n const [blot] = path;\n if (blot instanceof Block) {\n lines.push(blot);\n } else if (blot instanceof LeafBlot) {\n leaves.push(blot);\n }\n });\n } else {\n lines = this.scroll.lines(index, length);\n leaves = this.scroll.descendants(LeafBlot, index, length);\n }\n const [lineFormats, leafFormats] = [lines, leaves].map((blots) => {\n const blot = blots.shift();\n if (blot == null) return {};\n let formats = bubbleFormats(blot);\n while (Object.keys(formats).length > 0) {\n const blot = blots.shift();\n if (blot == null) return formats;\n formats = combineFormats(bubbleFormats(blot), formats);\n }\n return formats;\n });\n return { ...lineFormats, ...leafFormats };\n }\n\n getHTML(index: number, length: number): string {\n const [line, lineOffset] = this.scroll.line(index);\n if (line) {\n const lineLength = line.length();\n const isWithinLine = line.length() >= lineOffset + length;\n if (isWithinLine && !(lineOffset === 0 && length === lineLength)) {\n return convertHTML(line, lineOffset, length, true);\n }\n return convertHTML(this.scroll, index, length, true);\n }\n return '';\n }\n\n getText(index: number, length: number): string {\n return this.getContents(index, length)\n .filter((op) => typeof op.insert === 'string')\n .map((op) => op.insert)\n .join('');\n }\n\n insertContents(index: number, contents: Delta): Delta {\n const normalizedDelta = normalizeDelta(contents);\n const change = new Delta().retain(index).concat(normalizedDelta);\n this.scroll.insertContents(index, normalizedDelta);\n return this.update(change);\n }\n\n insertEmbed(index: number, embed: string, value: unknown): Delta {\n this.scroll.insertAt(index, embed, value);\n return this.update(new Delta().retain(index).insert({ [embed]: value }));\n }\n\n insertText(\n index: number,\n text: string,\n formats: Record = {},\n ): Delta {\n text = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n this.scroll.insertAt(index, text);\n Object.keys(formats).forEach((format) => {\n this.scroll.formatAt(index, text.length, format, formats[format]);\n });\n return this.update(\n new Delta().retain(index).insert(text, cloneDeep(formats)),\n );\n }\n\n isBlank(): boolean {\n if (this.scroll.children.length === 0) return true;\n if (this.scroll.children.length > 1) return false;\n const blot = this.scroll.children.head;\n if (blot?.statics.blotName !== Block.blotName) return false;\n const block = blot as Block;\n if (block.children.length > 1) return false;\n return block.children.head instanceof Break;\n }\n\n removeFormat(index: number, length: number): Delta {\n const text = this.getText(index, length);\n const [line, offset] = this.scroll.line(index + length);\n let suffixLength = 0;\n let suffix = new Delta();\n if (line != null) {\n suffixLength = line.length() - offset;\n suffix = line\n .delta()\n .slice(offset, offset + suffixLength - 1)\n .insert('\\n');\n }\n const contents = this.getContents(index, length + suffixLength);\n const diff = contents.diff(new Delta().insert(text).concat(suffix));\n const delta = new Delta().retain(index).concat(diff);\n return this.applyDelta(delta);\n }\n\n update(\n change: Delta | null,\n mutations: MutationRecord[] = [],\n selectionInfo: SelectionInfo | undefined = undefined,\n ): Delta {\n const oldDelta = this.delta;\n if (\n mutations.length === 1 &&\n mutations[0].type === 'characterData' &&\n // @ts-expect-error Fix me later\n mutations[0].target.data.match(ASCII) &&\n this.scroll.find(mutations[0].target)\n ) {\n // Optimization for character changes\n const textBlot = this.scroll.find(mutations[0].target) as Blot;\n const formats = bubbleFormats(textBlot);\n const index = textBlot.offset(this.scroll);\n // @ts-expect-error Fix me later\n const oldValue = mutations[0].oldValue.replace(CursorBlot.CONTENTS, '');\n const oldText = new Delta().insert(oldValue);\n // @ts-expect-error\n const newText = new Delta().insert(textBlot.value());\n const relativeSelectionInfo = selectionInfo && {\n oldRange: shiftRange(selectionInfo.oldRange, -index),\n newRange: shiftRange(selectionInfo.newRange, -index),\n };\n const diffDelta = new Delta()\n .retain(index)\n .concat(oldText.diff(newText, relativeSelectionInfo));\n change = diffDelta.reduce((delta, op) => {\n if (op.insert) {\n return delta.insert(op.insert, formats);\n }\n return delta.push(op);\n }, new Delta());\n this.delta = oldDelta.compose(change);\n } else {\n this.delta = this.getDelta();\n if (!change || !isEqual(oldDelta.compose(change), this.delta)) {\n change = oldDelta.diff(this.delta, selectionInfo);\n }\n }\n return change;\n }\n}\n\ninterface ListItem {\n child: Blot;\n offset: number;\n length: number;\n indent: number;\n type: string;\n}\nfunction convertListHTML(\n items: ListItem[],\n lastIndent: number,\n types: string[],\n): string {\n if (items.length === 0) {\n const [endTag] = getListType(types.pop());\n if (lastIndent <= 0) {\n return ``;\n }\n return `${convertListHTML([], lastIndent - 1, types)}`;\n }\n const [{ child, offset, length, indent, type }, ...rest] = items;\n const [tag, attribute] = getListType(type);\n if (indent > lastIndent) {\n types.push(type);\n if (indent === lastIndent + 1) {\n return `<${tag}>${convertHTML(\n child,\n offset,\n length,\n )}${convertListHTML(rest, indent, types)}`;\n }\n return `<${tag}>
  • ${convertListHTML(items, lastIndent + 1, types)}`;\n }\n const previousType = types[types.length - 1];\n if (indent === lastIndent && type === previousType) {\n return `
  • ${convertHTML(\n child,\n offset,\n length,\n )}${convertListHTML(rest, indent, types)}`;\n }\n const [endTag] = getListType(types.pop());\n return `${convertListHTML(items, lastIndent - 1, types)}`;\n}\n\nfunction convertHTML(\n blot: Blot,\n index: number,\n length: number,\n isRoot = false,\n): string {\n if ('html' in blot && typeof blot.html === 'function') {\n return blot.html(index, length);\n }\n if (blot instanceof TextBlot) {\n return escapeText(blot.value().slice(index, index + length));\n }\n if (blot instanceof ParentBlot) {\n // TODO fix API\n if (blot.statics.blotName === 'list-container') {\n const items: any[] = [];\n blot.children.forEachAt(index, length, (child, offset, childLength) => {\n const formats =\n 'formats' in child && typeof child.formats === 'function'\n ? child.formats()\n : {};\n items.push({\n child,\n offset,\n length: childLength,\n indent: formats.indent || 0,\n type: formats.list,\n });\n });\n return convertListHTML(items, -1, []);\n }\n const parts: string[] = [];\n blot.children.forEachAt(index, length, (child, offset, childLength) => {\n parts.push(convertHTML(child, offset, childLength));\n });\n if (isRoot || blot.statics.blotName === 'list') {\n return parts.join('');\n }\n const { outerHTML, innerHTML } = blot.domNode as Element;\n const [start, end] = outerHTML.split(`>${innerHTML}<`);\n // TODO cleanup\n if (start === '${parts.join('')}<${end}`;\n }\n return `${start}>${parts.join('')}<${end}`;\n }\n return blot.domNode instanceof Element ? blot.domNode.outerHTML : '';\n}\n\nfunction combineFormats(\n formats: Record,\n combined: Record,\n): Record {\n return Object.keys(combined).reduce(\n (merged, name) => {\n if (formats[name] == null) return merged;\n const combinedValue = combined[name];\n if (combinedValue === formats[name]) {\n merged[name] = combinedValue;\n } else if (Array.isArray(combinedValue)) {\n if (combinedValue.indexOf(formats[name]) < 0) {\n merged[name] = combinedValue.concat([formats[name]]);\n } else {\n // If style already exists, don't add to an array, but don't lose other styles\n merged[name] = combinedValue;\n }\n } else {\n merged[name] = [combinedValue, formats[name]];\n }\n return merged;\n },\n {} as Record,\n );\n}\n\nfunction getListType(type: string | undefined) {\n const tag = type === 'ordered' ? 'ol' : 'ul';\n switch (type) {\n case 'checked':\n return [tag, ' data-list=\"checked\"'];\n case 'unchecked':\n return [tag, ' data-list=\"unchecked\"'];\n default:\n return [tag, ''];\n }\n}\n\nfunction normalizeDelta(delta: Delta) {\n return delta.reduce((normalizedDelta, op) => {\n if (typeof op.insert === 'string') {\n const text = op.insert.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n return normalizedDelta.insert(text, op.attributes);\n }\n return normalizedDelta.push(op);\n }, new Delta());\n}\n\nfunction shiftRange({ index, length }: Range, amount: number) {\n return new Range(index + amount, length);\n}\n\nfunction splitOpLines(ops: Op[]) {\n const split: Op[] = [];\n ops.forEach((op) => {\n if (typeof op.insert === 'string') {\n const lines = op.insert.split('\\n');\n lines.forEach((line, index) => {\n if (index) split.push({ insert: '\\n', attributes: op.attributes });\n if (line) split.push({ insert: line, attributes: op.attributes });\n });\n } else {\n split.push(op);\n }\n });\n\n return split;\n}\n\nexport default Editor;\n", "import type Quill from './quill.js';\n\nabstract class Module {\n static DEFAULTS = {};\n\n constructor(\n public quill: Quill,\n protected options: Partial = {},\n ) {}\n}\n\nexport default Module;\n", "import type { ScrollBlot } from 'parchment';\nimport { EmbedBlot } from 'parchment';\nimport TextBlot from './text.js';\n\nconst GUARD_TEXT = '\\uFEFF';\n\nexport interface EmbedContextRange {\n startNode: Node | Text;\n startOffset: number;\n endNode?: Node | Text;\n endOffset?: number;\n}\n\nclass Embed extends EmbedBlot {\n contentNode: HTMLSpanElement;\n leftGuard: Text;\n rightGuard: Text;\n\n constructor(scroll: ScrollBlot, node: Node) {\n super(scroll, node);\n this.contentNode = document.createElement('span');\n this.contentNode.setAttribute('contenteditable', 'false');\n Array.from(this.domNode.childNodes).forEach((childNode) => {\n this.contentNode.appendChild(childNode);\n });\n this.leftGuard = document.createTextNode(GUARD_TEXT);\n this.rightGuard = document.createTextNode(GUARD_TEXT);\n this.domNode.appendChild(this.leftGuard);\n this.domNode.appendChild(this.contentNode);\n this.domNode.appendChild(this.rightGuard);\n }\n\n index(node: Node, offset: number) {\n if (node === this.leftGuard) return 0;\n if (node === this.rightGuard) return 1;\n return super.index(node, offset);\n }\n\n restore(node: Text): EmbedContextRange | null {\n let range: EmbedContextRange | null = null;\n let textNode: Text;\n const text = node.data.split(GUARD_TEXT).join('');\n if (node === this.leftGuard) {\n if (this.prev instanceof TextBlot) {\n const prevLength = this.prev.length();\n this.prev.insertAt(prevLength, text);\n range = {\n startNode: this.prev.domNode,\n startOffset: prevLength + text.length,\n };\n } else {\n textNode = document.createTextNode(text);\n this.parent.insertBefore(this.scroll.create(textNode), this);\n range = {\n startNode: textNode,\n startOffset: text.length,\n };\n }\n } else if (node === this.rightGuard) {\n if (this.next instanceof TextBlot) {\n this.next.insertAt(0, text);\n range = {\n startNode: this.next.domNode,\n startOffset: text.length,\n };\n } else {\n textNode = document.createTextNode(text);\n this.parent.insertBefore(this.scroll.create(textNode), this.next);\n range = {\n startNode: textNode,\n startOffset: text.length,\n };\n }\n }\n node.data = GUARD_TEXT;\n return range;\n }\n\n update(mutations: MutationRecord[], context: Record) {\n mutations.forEach((mutation) => {\n if (\n mutation.type === 'characterData' &&\n (mutation.target === this.leftGuard ||\n mutation.target === this.rightGuard)\n ) {\n const range = this.restore(mutation.target as Text);\n if (range) context.range = range;\n }\n });\n }\n}\n\nexport default Embed;\n", "import Embed from '../blots/embed.js';\nimport type Scroll from '../blots/scroll.js';\nimport Emitter from './emitter.js';\n\nclass Composition {\n isComposing = false;\n\n constructor(\n private scroll: Scroll,\n private emitter: Emitter,\n ) {\n this.setupListeners();\n }\n\n private setupListeners() {\n this.scroll.domNode.addEventListener('compositionstart', (event) => {\n if (!this.isComposing) {\n this.handleCompositionStart(event);\n }\n });\n\n this.scroll.domNode.addEventListener('compositionend', (event) => {\n if (this.isComposing) {\n // Webkit makes DOM changes after compositionend, so we use microtask to\n // ensure the order.\n // https://bugs.webkit.org/show_bug.cgi?id=31902\n queueMicrotask(() => {\n this.handleCompositionEnd(event);\n });\n }\n });\n }\n\n private handleCompositionStart(event: CompositionEvent) {\n const blot =\n event.target instanceof Node\n ? this.scroll.find(event.target, true)\n : null;\n\n if (blot && !(blot instanceof Embed)) {\n this.emitter.emit(Emitter.events.COMPOSITION_BEFORE_START, event);\n this.scroll.batchStart();\n this.emitter.emit(Emitter.events.COMPOSITION_START, event);\n this.isComposing = true;\n }\n }\n\n private handleCompositionEnd(event: CompositionEvent) {\n this.emitter.emit(Emitter.events.COMPOSITION_BEFORE_END, event);\n this.scroll.batchEnd();\n this.emitter.emit(Emitter.events.COMPOSITION_END, event);\n this.isComposing = false;\n }\n}\n\nexport default Composition;\n", "import type Quill from '../core.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type { ToolbarProps } from '../modules/toolbar.js';\nimport type Uploader from '../modules/uploader.js';\n\nexport interface ThemeOptions {\n modules: Record & {\n toolbar?: null | ToolbarProps;\n };\n}\n\nclass Theme {\n static DEFAULTS: ThemeOptions = {\n modules: {},\n };\n\n static themes = {\n default: Theme,\n };\n\n modules: ThemeOptions['modules'] = {};\n\n constructor(\n protected quill: Quill,\n protected options: ThemeOptions,\n ) {}\n\n init() {\n Object.keys(this.options.modules).forEach((name) => {\n if (this.modules[name] == null) {\n this.addModule(name);\n }\n });\n }\n\n addModule(name: 'clipboard'): Clipboard;\n addModule(name: 'keyboard'): Keyboard;\n addModule(name: 'uploader'): Uploader;\n addModule(name: 'history'): History;\n addModule(name: string): unknown;\n addModule(name: string) {\n // @ts-expect-error\n const ModuleClass = this.quill.constructor.import(`modules/${name}`);\n this.modules[name] = new ModuleClass(\n this.quill,\n this.options.modules[name] || {},\n );\n return this.modules[name];\n }\n}\n\nexport interface ThemeConstructor {\n new (quill: Quill, options: unknown): Theme;\n DEFAULTS: ThemeOptions;\n}\n\nexport default Theme;\n", "export type Rect = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\nconst getParentElement = (element: Node): Element | null =>\n element.parentElement || (element.getRootNode() as ShadowRoot).host || null;\n\nconst getElementRect = (element: Element): Rect => {\n const rect = element.getBoundingClientRect();\n const scaleX =\n ('offsetWidth' in element &&\n Math.abs(rect.width) / (element as HTMLElement).offsetWidth) ||\n 1;\n const scaleY =\n ('offsetHeight' in element &&\n Math.abs(rect.height) / (element as HTMLElement).offsetHeight) ||\n 1;\n return {\n top: rect.top,\n right: rect.left + element.clientWidth * scaleX,\n bottom: rect.top + element.clientHeight * scaleY,\n left: rect.left,\n };\n};\n\nconst paddingValueToInt = (value: string) => {\n const number = parseInt(value, 10);\n return Number.isNaN(number) ? 0 : number;\n};\n\n// Follow the steps described in https://www.w3.org/TR/cssom-view-1/#element-scrolling-members,\n// assuming that the scroll option is set to 'nearest'.\nconst getScrollDistance = (\n targetStart: number,\n targetEnd: number,\n scrollStart: number,\n scrollEnd: number,\n scrollPaddingStart: number,\n scrollPaddingEnd: number,\n) => {\n if (targetStart < scrollStart && targetEnd > scrollEnd) {\n return 0;\n }\n\n if (targetStart < scrollStart) {\n return -(scrollStart - targetStart + scrollPaddingStart);\n }\n\n if (targetEnd > scrollEnd) {\n return targetEnd - targetStart > scrollEnd - scrollStart\n ? targetStart + scrollPaddingStart - scrollStart\n : targetEnd - scrollEnd + scrollPaddingEnd;\n }\n return 0;\n};\n\nconst scrollRectIntoView = (root: HTMLElement, targetRect: Rect) => {\n const document = root.ownerDocument;\n\n let rect = targetRect;\n\n let current: Element | null = root;\n while (current) {\n const isDocumentBody: boolean = current === document.body;\n const bounding = isDocumentBody\n ? {\n top: 0,\n right:\n window.visualViewport?.width ??\n document.documentElement.clientWidth,\n bottom:\n window.visualViewport?.height ??\n document.documentElement.clientHeight,\n left: 0,\n }\n : getElementRect(current);\n\n const style = getComputedStyle(current);\n const scrollDistanceX = getScrollDistance(\n rect.left,\n rect.right,\n bounding.left,\n bounding.right,\n paddingValueToInt(style.scrollPaddingLeft),\n paddingValueToInt(style.scrollPaddingRight),\n );\n const scrollDistanceY = getScrollDistance(\n rect.top,\n rect.bottom,\n bounding.top,\n bounding.bottom,\n paddingValueToInt(style.scrollPaddingTop),\n paddingValueToInt(style.scrollPaddingBottom),\n );\n if (scrollDistanceX || scrollDistanceY) {\n if (isDocumentBody) {\n document.defaultView?.scrollBy(scrollDistanceX, scrollDistanceY);\n } else {\n const { scrollLeft, scrollTop } = current;\n if (scrollDistanceY) {\n current.scrollTop += scrollDistanceY;\n }\n if (scrollDistanceX) {\n current.scrollLeft += scrollDistanceX;\n }\n const scrolledLeft = current.scrollLeft - scrollLeft;\n const scrolledTop = current.scrollTop - scrollTop;\n rect = {\n left: rect.left - scrolledLeft,\n top: rect.top - scrolledTop,\n right: rect.right - scrolledLeft,\n bottom: rect.bottom - scrolledTop,\n };\n }\n }\n\n current =\n isDocumentBody || style.position === 'fixed'\n ? null\n : getParentElement(current);\n }\n};\n\nexport default scrollRectIntoView;\n", "import { Registry } from 'parchment';\n\nconst MAX_REGISTER_ITERATIONS = 100;\nconst CORE_FORMATS = ['block', 'break', 'cursor', 'inline', 'scroll', 'text'];\n\nconst createRegistryWithFormats = (\n formats: string[],\n sourceRegistry: Registry,\n debug: { error: (errorMessage: string) => void },\n) => {\n const registry = new Registry();\n CORE_FORMATS.forEach((name) => {\n const coreBlot = sourceRegistry.query(name);\n if (coreBlot) registry.register(coreBlot);\n });\n\n formats.forEach((name) => {\n let format = sourceRegistry.query(name);\n if (!format) {\n debug.error(\n `Cannot register \"${name}\" specified in \"formats\" config. Are you sure it was registered?`,\n );\n }\n let iterations = 0;\n while (format) {\n registry.register(format);\n format = 'blotName' in format ? format.requiredContainer ?? null : null;\n\n iterations += 1;\n if (iterations > MAX_REGISTER_ITERATIONS) {\n debug.error(\n `Cycle detected in registering blot requiredContainer: \"${name}\"`,\n );\n break;\n }\n }\n });\n\n return registry;\n};\n\nexport default createRegistryWithFormats;\n", "import { merge } from 'lodash-es';\nimport * as Parchment from 'parchment';\nimport type { Op } from 'quill-delta';\nimport Delta from 'quill-delta';\nimport type { BlockEmbed } from '../blots/block.js';\nimport type Block from '../blots/block.js';\nimport type Scroll from '../blots/scroll.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type Uploader from '../modules/uploader.js';\nimport Editor from './editor.js';\nimport Emitter from './emitter.js';\nimport type { EmitterSource } from './emitter.js';\nimport instances from './instances.js';\nimport logger from './logger.js';\nimport type { DebugLevel } from './logger.js';\nimport Module from './module.js';\nimport Selection, { Range } from './selection.js';\nimport type { Bounds } from './selection.js';\nimport Composition from './composition.js';\nimport Theme from './theme.js';\nimport type { ThemeConstructor } from './theme.js';\nimport scrollRectIntoView from './utils/scrollRectIntoView.js';\nimport type { Rect } from './utils/scrollRectIntoView.js';\nimport createRegistryWithFormats from './utils/createRegistryWithFormats.js';\n\nconst debug = logger('quill');\n\nconst globalRegistry = new Parchment.Registry();\nParchment.ParentBlot.uiClass = 'ql-ui';\n\n/**\n * Options for initializing a Quill instance\n */\nexport interface QuillOptions {\n theme?: string;\n debug?: DebugLevel | boolean;\n registry?: Parchment.Registry;\n /**\n * Whether to disable the editing\n * @default false\n */\n readOnly?: boolean;\n\n /**\n * Placeholder text to display when the editor is empty\n * @default \"\"\n */\n placeholder?: string;\n bounds?: HTMLElement | string | null;\n modules?: Record;\n\n /**\n * A list of formats that are recognized and can exist within the editor contents.\n * `null` means all formats are allowed.\n * @default null\n */\n formats?: string[] | null;\n}\n\n/**\n * Similar to QuillOptions, but with all properties expanded to their default values,\n * and all selectors resolved to HTMLElements.\n */\nexport interface ExpandedQuillOptions\n extends Omit {\n theme: ThemeConstructor;\n registry: Parchment.Registry;\n container: HTMLElement;\n modules: Record;\n bounds?: HTMLElement | null;\n readOnly: boolean;\n}\n\nclass Quill {\n static DEFAULTS = {\n bounds: null,\n modules: {\n clipboard: true,\n keyboard: true,\n history: true,\n uploader: true,\n },\n placeholder: '',\n readOnly: false,\n registry: globalRegistry,\n theme: 'default',\n } satisfies Partial;\n static events = Emitter.events;\n static sources = Emitter.sources;\n static version = typeof QUILL_VERSION === 'undefined' ? 'dev' : QUILL_VERSION;\n\n static imports: Record = {\n delta: Delta,\n parchment: Parchment,\n 'core/module': Module,\n 'core/theme': Theme,\n };\n\n static debug(limit: DebugLevel | boolean) {\n if (limit === true) {\n limit = 'log';\n }\n logger.level(limit);\n }\n\n static find(node: Node, bubble = false) {\n return instances.get(node) || globalRegistry.find(node, bubble);\n }\n\n static import(name: 'core/module'): typeof Module;\n static import(name: `themes/${string}`): typeof Theme;\n static import(name: 'parchment'): typeof Parchment;\n static import(name: 'delta'): typeof Delta;\n static import(name: string): unknown;\n static import(name: string) {\n if (this.imports[name] == null) {\n debug.error(`Cannot import ${name}. Are you sure it was registered?`);\n }\n return this.imports[name];\n }\n\n static register(\n targets: Record<\n string,\n | Parchment.RegistryDefinition\n | Record // any objects\n | Theme\n | Module\n | Function // ES5 constructors\n >,\n overwrite?: boolean,\n ): void;\n static register(\n target: Parchment.RegistryDefinition,\n overwrite?: boolean,\n ): void;\n static register(path: string, target: any, overwrite?: boolean): void;\n static register(...args: any[]): void {\n if (typeof args[0] !== 'string') {\n const target = args[0];\n const overwrite = !!args[1];\n\n const name = 'attrName' in target ? target.attrName : target.blotName;\n if (typeof name === 'string') {\n // Shortcut for formats:\n // register(Blot | Attributor, overwrite)\n this.register(`formats/${name}`, target, overwrite);\n } else {\n Object.keys(target).forEach((key) => {\n this.register(key, target[key], overwrite);\n });\n }\n } else {\n const path = args[0];\n const target = args[1];\n const overwrite = !!args[2];\n\n if (this.imports[path] != null && !overwrite) {\n debug.warn(`Overwriting ${path} with`, target);\n }\n this.imports[path] = target;\n if (\n (path.startsWith('blots/') || path.startsWith('formats/')) &&\n target &&\n typeof target !== 'boolean' &&\n target.blotName !== 'abstract'\n ) {\n globalRegistry.register(target);\n }\n if (typeof target.register === 'function') {\n target.register(globalRegistry);\n }\n }\n }\n\n container: HTMLElement;\n root: HTMLDivElement;\n scroll: Scroll;\n emitter: Emitter;\n protected allowReadOnlyEdits: boolean;\n editor: Editor;\n composition: Composition;\n selection: Selection;\n\n theme: Theme;\n keyboard: Keyboard;\n clipboard: Clipboard;\n history: History;\n uploader: Uploader;\n\n options: ExpandedQuillOptions;\n\n constructor(container: HTMLElement | string, options: QuillOptions = {}) {\n this.options = expandConfig(container, options);\n this.container = this.options.container;\n if (this.container == null) {\n debug.error('Invalid Quill container', container);\n return;\n }\n if (this.options.debug) {\n Quill.debug(this.options.debug);\n }\n const html = this.container.innerHTML.trim();\n this.container.classList.add('ql-container');\n this.container.innerHTML = '';\n instances.set(this.container, this);\n this.root = this.addContainer('ql-editor');\n this.root.classList.add('ql-blank');\n this.emitter = new Emitter();\n const scrollBlotName = Parchment.ScrollBlot.blotName;\n const ScrollBlot = this.options.registry.query(scrollBlotName);\n if (!ScrollBlot || !('blotName' in ScrollBlot)) {\n throw new Error(\n `Cannot initialize Quill without \"${scrollBlotName}\" blot`,\n );\n }\n this.scroll = new ScrollBlot(this.options.registry, this.root, {\n emitter: this.emitter,\n }) as Scroll;\n this.editor = new Editor(this.scroll);\n this.selection = new Selection(this.scroll, this.emitter);\n this.composition = new Composition(this.scroll, this.emitter);\n this.theme = new this.options.theme(this, this.options); // eslint-disable-line new-cap\n this.keyboard = this.theme.addModule('keyboard');\n this.clipboard = this.theme.addModule('clipboard');\n this.history = this.theme.addModule('history');\n this.uploader = this.theme.addModule('uploader');\n this.theme.addModule('input');\n this.theme.addModule('uiNode');\n this.theme.init();\n this.emitter.on(Emitter.events.EDITOR_CHANGE, (type) => {\n if (type === Emitter.events.TEXT_CHANGE) {\n this.root.classList.toggle('ql-blank', this.editor.isBlank());\n }\n });\n this.emitter.on(Emitter.events.SCROLL_UPDATE, (source, mutations) => {\n const oldRange = this.selection.lastRange;\n const [newRange] = this.selection.getRange();\n const selectionInfo =\n oldRange && newRange ? { oldRange, newRange } : undefined;\n modify.call(\n this,\n () => this.editor.update(null, mutations, selectionInfo),\n source,\n );\n });\n this.emitter.on(Emitter.events.SCROLL_EMBED_UPDATE, (blot, delta) => {\n const oldRange = this.selection.lastRange;\n const [newRange] = this.selection.getRange();\n const selectionInfo =\n oldRange && newRange ? { oldRange, newRange } : undefined;\n modify.call(\n this,\n () => {\n const change = new Delta()\n .retain(blot.offset(this))\n .retain({ [blot.statics.blotName]: delta });\n return this.editor.update(change, [], selectionInfo);\n },\n Quill.sources.USER,\n );\n });\n if (html) {\n const contents = this.clipboard.convert({\n html: `${html}


    `,\n text: '\\n',\n });\n this.setContents(contents);\n }\n this.history.clear();\n if (this.options.placeholder) {\n this.root.setAttribute('data-placeholder', this.options.placeholder);\n }\n if (this.options.readOnly) {\n this.disable();\n }\n this.allowReadOnlyEdits = false;\n }\n\n addContainer(container: string, refNode?: Node | null): HTMLDivElement;\n addContainer(container: HTMLElement, refNode?: Node | null): HTMLElement;\n addContainer(\n container: string | HTMLElement,\n refNode: Node | null = null,\n ): HTMLDivElement | HTMLElement {\n if (typeof container === 'string') {\n const className = container;\n container = document.createElement('div');\n container.classList.add(className);\n }\n this.container.insertBefore(container, refNode);\n return container;\n }\n\n blur() {\n this.selection.setRange(null);\n }\n\n deleteText(range: Range, source?: EmitterSource): Delta;\n deleteText(index: number, length: number, source?: EmitterSource): Delta;\n deleteText(\n index: number | Range,\n length?: number | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n // @ts-expect-error\n [index, length, , source] = overload(index, length, source);\n return modify.call(\n this,\n () => {\n return this.editor.deleteText(index, length);\n },\n source,\n index,\n -1 * length,\n );\n }\n\n disable() {\n this.enable(false);\n }\n\n editReadOnly(modifier: () => T): T {\n this.allowReadOnlyEdits = true;\n const value = modifier();\n this.allowReadOnlyEdits = false;\n return value;\n }\n\n enable(enabled = true) {\n this.scroll.enable(enabled);\n this.container.classList.toggle('ql-disabled', !enabled);\n }\n\n focus(options: { preventScroll?: boolean } = {}) {\n this.selection.focus();\n if (!options.preventScroll) {\n this.scrollSelectionIntoView();\n }\n }\n\n format(\n name: string,\n value: unknown,\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n const range = this.getSelection(true);\n let change = new Delta();\n if (range == null) return change;\n if (this.scroll.query(name, Parchment.Scope.BLOCK)) {\n change = this.editor.formatLine(range.index, range.length, {\n [name]: value,\n });\n } else if (range.length === 0) {\n this.selection.format(name, value);\n return change;\n } else {\n change = this.editor.formatText(range.index, range.length, {\n [name]: value,\n });\n }\n this.setSelection(range, Emitter.sources.SILENT);\n return change;\n },\n source,\n );\n }\n\n formatLine(\n index: number,\n length: number,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n formatLine(\n index: number,\n length: number,\n name: string,\n value?: unknown,\n source?: EmitterSource,\n ): Delta;\n formatLine(\n index: number,\n length: number,\n name: string | Record,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n [index, length, formats, source] = overload(\n index,\n length,\n // @ts-expect-error\n name,\n value,\n source,\n );\n return modify.call(\n this,\n () => {\n return this.editor.formatLine(index, length, formats);\n },\n source,\n index,\n 0,\n );\n }\n\n formatText(\n range: Range,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number,\n length: number,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number,\n length: number,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n formatText(\n index: number | Range,\n length: number | string,\n name: string | unknown,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n [index, length, formats, source] = overload(\n // @ts-expect-error\n index,\n length,\n name,\n value,\n source,\n );\n return modify.call(\n this,\n () => {\n return this.editor.formatText(index, length, formats);\n },\n source,\n index,\n 0,\n );\n }\n\n getBounds(index: number | Range, length = 0): Bounds | null {\n let bounds: Bounds | null = null;\n if (typeof index === 'number') {\n bounds = this.selection.getBounds(index, length);\n } else {\n bounds = this.selection.getBounds(index.index, index.length);\n }\n if (!bounds) return null;\n const containerBounds = this.container.getBoundingClientRect();\n return {\n bottom: bounds.bottom - containerBounds.top,\n height: bounds.height,\n left: bounds.left - containerBounds.left,\n right: bounds.right - containerBounds.left,\n top: bounds.top - containerBounds.top,\n width: bounds.width,\n };\n }\n\n getContents(index = 0, length = this.getLength() - index) {\n [index, length] = overload(index, length);\n return this.editor.getContents(index, length);\n }\n\n getFormat(index?: number, length?: number): { [format: string]: unknown };\n getFormat(range?: Range): {\n [format: string]: unknown;\n };\n getFormat(\n index: Range | number = this.getSelection(true),\n length = 0,\n ): { [format: string]: unknown } {\n if (typeof index === 'number') {\n return this.editor.getFormat(index, length);\n }\n return this.editor.getFormat(index.index, index.length);\n }\n\n getIndex(blot: Parchment.Blot) {\n return blot.offset(this.scroll);\n }\n\n getLength() {\n return this.scroll.length();\n }\n\n getLeaf(index: number) {\n return this.scroll.leaf(index);\n }\n\n getLine(index: number) {\n return this.scroll.line(index);\n }\n\n getLines(range: Range): (Block | BlockEmbed)[];\n getLines(index?: number, length?: number): (Block | BlockEmbed)[];\n getLines(\n index: Range | number = 0,\n length = Number.MAX_VALUE,\n ): (Block | BlockEmbed)[] {\n if (typeof index !== 'number') {\n return this.scroll.lines(index.index, index.length);\n }\n return this.scroll.lines(index, length);\n }\n\n getModule(name: string) {\n return this.theme.modules[name];\n }\n\n getSelection(focus: true): Range;\n getSelection(focus?: boolean): Range | null;\n getSelection(focus = false): Range | null {\n if (focus) this.focus();\n this.update(); // Make sure we access getRange with editor in consistent state\n return this.selection.getRange()[0];\n }\n\n getSemanticHTML(range: Range): string;\n getSemanticHTML(index?: number, length?: number): string;\n getSemanticHTML(index: Range | number = 0, length?: number) {\n if (typeof index === 'number') {\n length = length ?? this.getLength() - index;\n }\n // @ts-expect-error\n [index, length] = overload(index, length);\n return this.editor.getHTML(index, length);\n }\n\n getText(range?: Range): string;\n getText(index?: number, length?: number): string;\n getText(index: Range | number = 0, length?: number): string {\n if (typeof index === 'number') {\n length = length ?? this.getLength() - index;\n }\n // @ts-expect-error\n [index, length] = overload(index, length);\n return this.editor.getText(index, length);\n }\n\n hasFocus() {\n return this.selection.hasFocus();\n }\n\n insertEmbed(\n index: number,\n embed: string,\n value: unknown,\n source: EmitterSource = Quill.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n return this.editor.insertEmbed(index, embed, value);\n },\n source,\n index,\n );\n }\n\n insertText(index: number, text: string, source?: EmitterSource): Delta;\n insertText(\n index: number,\n text: string,\n formats: Record,\n source?: EmitterSource,\n ): Delta;\n insertText(\n index: number,\n text: string,\n name: string,\n value: unknown,\n source?: EmitterSource,\n ): Delta;\n insertText(\n index: number,\n text: string,\n name?: string | Record | EmitterSource,\n value?: unknown,\n source?: EmitterSource,\n ): Delta {\n let formats: Record;\n // eslint-disable-next-line prefer-const\n // @ts-expect-error\n [index, , formats, source] = overload(index, 0, name, value, source);\n return modify.call(\n this,\n () => {\n return this.editor.insertText(index, text, formats);\n },\n source,\n index,\n text.length,\n );\n }\n\n isEnabled() {\n return this.scroll.isEnabled();\n }\n\n off(...args: Parameters<(typeof Emitter)['prototype']['off']>) {\n return this.emitter.off(...args);\n }\n\n on(\n event: (typeof Emitter)['events']['TEXT_CHANGE'],\n handler: (delta: Delta, oldContent: Delta, source: EmitterSource) => void,\n ): Emitter;\n on(\n event: (typeof Emitter)['events']['SELECTION_CHANGE'],\n handler: (range: Range, oldRange: Range, source: EmitterSource) => void,\n ): Emitter;\n on(\n event: (typeof Emitter)['events']['EDITOR_CHANGE'],\n handler: (\n ...args:\n | [\n (typeof Emitter)['events']['TEXT_CHANGE'],\n Delta,\n Delta,\n EmitterSource,\n ]\n | [\n (typeof Emitter)['events']['SELECTION_CHANGE'],\n Range,\n Range,\n EmitterSource,\n ]\n ) => void,\n ): Emitter;\n on(event: string, ...args: unknown[]): Emitter;\n on(...args: Parameters<(typeof Emitter)['prototype']['on']>): Emitter {\n return this.emitter.on(...args);\n }\n\n once(...args: Parameters<(typeof Emitter)['prototype']['once']>) {\n return this.emitter.once(...args);\n }\n\n removeFormat(index: number, length: number, source?: EmitterSource): Delta {\n [index, length, , source] = overload(index, length, source);\n return modify.call(\n this,\n () => {\n return this.editor.removeFormat(index, length);\n },\n source,\n index,\n );\n }\n\n scrollRectIntoView(rect: Rect) {\n scrollRectIntoView(this.root, rect);\n }\n\n /**\n * @deprecated Use Quill#scrollSelectionIntoView() instead.\n */\n scrollIntoView() {\n console.warn(\n 'Quill#scrollIntoView() has been deprecated and will be removed in the near future. Please use Quill#scrollSelectionIntoView() instead.',\n );\n this.scrollSelectionIntoView();\n }\n\n /**\n * Scroll the current selection into the visible area.\n * If the selection is already visible, no scrolling will occur.\n */\n scrollSelectionIntoView() {\n const range = this.selection.lastRange;\n const bounds = range && this.selection.getBounds(range.index, range.length);\n if (bounds) {\n this.scrollRectIntoView(bounds);\n }\n }\n\n setContents(\n delta: Delta | Op[],\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n delta = new Delta(delta);\n const length = this.getLength();\n // Quill will set empty editor to \\n\n const delete1 = this.editor.deleteText(0, length);\n const applied = this.editor.insertContents(0, delta);\n // Remove extra \\n from empty editor initialization\n const delete2 = this.editor.deleteText(this.getLength() - 1, 1);\n return delete1.compose(applied).compose(delete2);\n },\n source,\n );\n }\n setSelection(range: Range | null, source?: EmitterSource): void;\n setSelection(index: number, source?: EmitterSource): void;\n setSelection(index: number, length?: number, source?: EmitterSource): void;\n setSelection(index: number, source?: EmitterSource): void;\n setSelection(\n index: Range | null | number,\n length?: EmitterSource | number,\n source?: EmitterSource,\n ): void {\n if (index == null) {\n // @ts-expect-error https://github.com/microsoft/TypeScript/issues/22609\n this.selection.setRange(null, length || Quill.sources.API);\n } else {\n // @ts-expect-error\n [index, length, , source] = overload(index, length, source);\n this.selection.setRange(new Range(Math.max(0, index), length), source);\n if (source !== Emitter.sources.SILENT) {\n this.scrollSelectionIntoView();\n }\n }\n }\n\n setText(text: string, source: EmitterSource = Emitter.sources.API) {\n const delta = new Delta().insert(text);\n return this.setContents(delta, source);\n }\n\n update(source: EmitterSource = Emitter.sources.USER) {\n const change = this.scroll.update(source); // Will update selection before selection.update() does if text changes\n this.selection.update(source);\n // TODO this is usually undefined\n return change;\n }\n\n updateContents(\n delta: Delta | Op[],\n source: EmitterSource = Emitter.sources.API,\n ): Delta {\n return modify.call(\n this,\n () => {\n delta = new Delta(delta);\n return this.editor.applyDelta(delta);\n },\n source,\n true,\n );\n }\n}\n\nfunction resolveSelector(selector: string | HTMLElement | null | undefined) {\n return typeof selector === 'string'\n ? document.querySelector(selector)\n : selector;\n}\n\nfunction expandModuleConfig(config: Record | undefined) {\n return Object.entries(config ?? {}).reduce(\n (expanded, [key, value]) => ({\n ...expanded,\n [key]: value === true ? {} : value,\n }),\n {} as Record,\n );\n}\n\nfunction omitUndefinedValuesFromOptions(obj: QuillOptions) {\n return Object.fromEntries(\n Object.entries(obj).filter((entry) => entry[1] !== undefined),\n );\n}\n\nfunction expandConfig(\n containerOrSelector: HTMLElement | string,\n options: QuillOptions,\n): ExpandedQuillOptions {\n const container = resolveSelector(containerOrSelector);\n if (!container) {\n throw new Error('Invalid Quill container');\n }\n\n const shouldUseDefaultTheme =\n !options.theme || options.theme === Quill.DEFAULTS.theme;\n const theme = shouldUseDefaultTheme\n ? Theme\n : Quill.import(`themes/${options.theme}`);\n if (!theme) {\n throw new Error(`Invalid theme ${options.theme}. Did you register it?`);\n }\n\n const { modules: quillModuleDefaults, ...quillDefaults } = Quill.DEFAULTS;\n const { modules: themeModuleDefaults, ...themeDefaults } = theme.DEFAULTS;\n\n let userModuleOptions = expandModuleConfig(options.modules);\n // Special case toolbar shorthand\n if (\n userModuleOptions != null &&\n userModuleOptions.toolbar &&\n userModuleOptions.toolbar.constructor !== Object\n ) {\n userModuleOptions = {\n ...userModuleOptions,\n toolbar: { container: userModuleOptions.toolbar },\n };\n }\n\n const modules: ExpandedQuillOptions['modules'] = merge(\n {},\n expandModuleConfig(quillModuleDefaults),\n expandModuleConfig(themeModuleDefaults),\n userModuleOptions,\n );\n\n const config = {\n ...quillDefaults,\n ...omitUndefinedValuesFromOptions(themeDefaults),\n ...omitUndefinedValuesFromOptions(options),\n };\n\n let registry = options.registry;\n if (registry) {\n if (options.formats) {\n debug.warn('Ignoring \"formats\" option because \"registry\" is specified');\n }\n } else {\n registry = options.formats\n ? createRegistryWithFormats(options.formats, config.registry, debug)\n : config.registry;\n }\n\n return {\n ...config,\n registry,\n container,\n theme,\n modules: Object.entries(modules).reduce(\n (modulesWithDefaults, [name, value]) => {\n if (!value) return modulesWithDefaults;\n\n const moduleClass = Quill.import(`modules/${name}`);\n if (moduleClass == null) {\n debug.error(\n `Cannot load ${name} module. Are you sure you registered it?`,\n );\n return modulesWithDefaults;\n }\n return {\n ...modulesWithDefaults,\n // @ts-expect-error\n [name]: merge({}, moduleClass.DEFAULTS || {}, value),\n };\n },\n {},\n ),\n bounds: resolveSelector(config.bounds),\n };\n}\n\n// Handle selection preservation and TEXT_CHANGE emission\n// common to modification APIs\nfunction modify(\n modifier: () => Delta,\n source: EmitterSource,\n index: number | boolean,\n shift: number | null,\n) {\n if (\n !this.isEnabled() &&\n source === Emitter.sources.USER &&\n !this.allowReadOnlyEdits\n ) {\n return new Delta();\n }\n let range = index == null ? null : this.getSelection();\n const oldDelta = this.editor.delta;\n const change = modifier();\n if (range != null) {\n if (index === true) {\n index = range.index; // eslint-disable-line prefer-destructuring\n }\n if (shift == null) {\n range = shiftRange(range, change, source);\n } else if (shift !== 0) {\n // @ts-expect-error index should always be number\n range = shiftRange(range, index, shift, source);\n }\n this.setSelection(range, Emitter.sources.SILENT);\n }\n if (change.length() > 0) {\n const args = [Emitter.events.TEXT_CHANGE, change, oldDelta, source];\n this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);\n if (source !== Emitter.sources.SILENT) {\n this.emitter.emit(...args);\n }\n }\n return change;\n}\n\ntype NormalizedIndexLength = [\n number,\n number,\n Record,\n EmitterSource,\n];\nfunction overload(index: number, source?: EmitterSource): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n format: string,\n value: unknown,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: number,\n length: number,\n format: Record,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(range: Range, source?: EmitterSource): NormalizedIndexLength;\nfunction overload(\n range: Range,\n format: string,\n value: unknown,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n range: Range,\n format: Record,\n source?: EmitterSource,\n): NormalizedIndexLength;\nfunction overload(\n index: Range | number,\n length?: number | string | Record | EmitterSource,\n name?: string | unknown | Record | EmitterSource,\n value?: unknown | EmitterSource,\n source?: EmitterSource,\n): NormalizedIndexLength {\n let formats: Record = {};\n // @ts-expect-error\n if (typeof index.index === 'number' && typeof index.length === 'number') {\n // Allow for throwaway end (used by insertText/insertEmbed)\n if (typeof length !== 'number') {\n // @ts-expect-error\n source = value;\n value = name;\n name = length;\n // @ts-expect-error\n length = index.length; // eslint-disable-line prefer-destructuring\n // @ts-expect-error\n index = index.index; // eslint-disable-line prefer-destructuring\n } else {\n // @ts-expect-error\n length = index.length; // eslint-disable-line prefer-destructuring\n // @ts-expect-error\n index = index.index; // eslint-disable-line prefer-destructuring\n }\n } else if (typeof length !== 'number') {\n // @ts-expect-error\n source = value;\n value = name;\n name = length;\n length = 0;\n }\n // Handle format being object, two format name/value strings or excluded\n if (typeof name === 'object') {\n // @ts-expect-error Fix me later\n formats = name;\n // @ts-expect-error\n source = value;\n } else if (typeof name === 'string') {\n if (value != null) {\n formats[name] = value;\n } else {\n // @ts-expect-error\n source = name;\n }\n }\n // Handle optional source\n source = source || Emitter.sources.API;\n // @ts-expect-error\n return [index, length, formats, source];\n}\n\nfunction shiftRange(range: Range, change: Delta, source?: EmitterSource): Range;\nfunction shiftRange(\n range: Range,\n index: number,\n length?: number,\n source?: EmitterSource,\n): Range;\nfunction shiftRange(\n range: Range,\n index: number | Delta,\n lengthOrSource?: number | EmitterSource,\n source?: EmitterSource,\n) {\n const length = typeof lengthOrSource === 'number' ? lengthOrSource : 0;\n if (range == null) return null;\n let start;\n let end;\n // @ts-expect-error -- TODO: add a better type guard around `index`\n if (index && typeof index.transformPosition === 'function') {\n [start, end] = [range.index, range.index + range.length].map((pos) =>\n // @ts-expect-error -- TODO: add a better type guard around `index`\n index.transformPosition(pos, source !== Emitter.sources.USER),\n );\n } else {\n [start, end] = [range.index, range.index + range.length].map((pos) => {\n // @ts-expect-error -- TODO: add a better type guard around `index`\n if (pos < index || (pos === index && source === Emitter.sources.USER))\n return pos;\n if (length >= 0) {\n return pos + length;\n }\n // @ts-expect-error -- TODO: add a better type guard around `index`\n return Math.max(index, pos + length);\n });\n }\n return new Range(start, end - start);\n}\n\nexport type { Bounds, DebugLevel, EmitterSource };\nexport { Parchment, Range };\n\nexport { globalRegistry, expandConfig, overload, Quill as default };\n", "import { ContainerBlot } from 'parchment';\n\nclass Container extends ContainerBlot {}\n\nexport default Container;\n", "import { ContainerBlot, LeafBlot, Scope, ScrollBlot } from 'parchment';\nimport type { Blot, Parent, EmbedBlot, ParentBlot, Registry } from 'parchment';\nimport Delta, { AttributeMap, Op } from 'quill-delta';\nimport Emitter from '../core/emitter.js';\nimport type { EmitterSource } from '../core/emitter.js';\nimport Block, { BlockEmbed, bubbleFormats } from './block.js';\nimport Break from './break.js';\nimport Container from './container.js';\n\ntype RenderBlock =\n | {\n type: 'blockEmbed';\n attributes: AttributeMap;\n key: string;\n value: unknown;\n }\n | { type: 'block'; attributes: AttributeMap; delta: Delta };\n\nfunction isLine(blot: unknown): blot is Block | BlockEmbed {\n return blot instanceof Block || blot instanceof BlockEmbed;\n}\n\ninterface UpdatableEmbed {\n updateContent(change: unknown): void;\n}\n\nfunction isUpdatable(blot: Blot): blot is Blot & UpdatableEmbed {\n return typeof (blot as unknown as any).updateContent === 'function';\n}\n\nclass Scroll extends ScrollBlot {\n static blotName = 'scroll';\n static className = 'ql-editor';\n static tagName = 'DIV';\n static defaultChild = Block;\n static allowedChildren = [Block, BlockEmbed, Container];\n\n emitter: Emitter;\n batch: false | MutationRecord[];\n\n constructor(\n registry: Registry,\n domNode: HTMLDivElement,\n { emitter }: { emitter: Emitter },\n ) {\n super(registry, domNode);\n this.emitter = emitter;\n this.batch = false;\n this.optimize();\n this.enable();\n this.domNode.addEventListener('dragstart', (e) => this.handleDragStart(e));\n }\n\n batchStart() {\n if (!Array.isArray(this.batch)) {\n this.batch = [];\n }\n }\n\n batchEnd() {\n if (!this.batch) return;\n const mutations = this.batch;\n this.batch = false;\n this.update(mutations);\n }\n\n emitMount(blot: Blot) {\n this.emitter.emit(Emitter.events.SCROLL_BLOT_MOUNT, blot);\n }\n\n emitUnmount(blot: Blot) {\n this.emitter.emit(Emitter.events.SCROLL_BLOT_UNMOUNT, blot);\n }\n\n emitEmbedUpdate(blot: Blot, change: unknown) {\n this.emitter.emit(Emitter.events.SCROLL_EMBED_UPDATE, blot, change);\n }\n\n deleteAt(index: number, length: number) {\n const [first, offset] = this.line(index);\n const [last] = this.line(index + length);\n super.deleteAt(index, length);\n if (last != null && first !== last && offset > 0) {\n if (first instanceof BlockEmbed || last instanceof BlockEmbed) {\n this.optimize();\n return;\n }\n const ref =\n last.children.head instanceof Break ? null : last.children.head;\n // @ts-expect-error\n first.moveChildren(last, ref);\n // @ts-expect-error\n first.remove();\n }\n this.optimize();\n }\n\n enable(enabled = true) {\n this.domNode.setAttribute('contenteditable', enabled ? 'true' : 'false');\n }\n\n formatAt(index: number, length: number, format: string, value: unknown) {\n super.formatAt(index, length, format, value);\n this.optimize();\n }\n\n insertAt(index: number, value: string, def?: unknown) {\n if (index >= this.length()) {\n if (def == null || this.scroll.query(value, Scope.BLOCK) == null) {\n const blot = this.scroll.create(this.statics.defaultChild.blotName);\n this.appendChild(blot);\n if (def == null && value.endsWith('\\n')) {\n blot.insertAt(0, value.slice(0, -1), def);\n } else {\n blot.insertAt(0, value, def);\n }\n } else {\n const embed = this.scroll.create(value, def);\n this.appendChild(embed);\n }\n } else {\n super.insertAt(index, value, def);\n }\n this.optimize();\n }\n\n insertBefore(blot: Blot, ref?: Blot | null) {\n if (blot.statics.scope === Scope.INLINE_BLOT) {\n const wrapper = this.scroll.create(\n this.statics.defaultChild.blotName,\n ) as Parent;\n wrapper.appendChild(blot);\n super.insertBefore(wrapper, ref);\n } else {\n super.insertBefore(blot, ref);\n }\n }\n\n insertContents(index: number, delta: Delta) {\n const renderBlocks = this.deltaToRenderBlocks(\n delta.concat(new Delta().insert('\\n')),\n );\n const last = renderBlocks.pop();\n if (last == null) return;\n\n this.batchStart();\n\n const first = renderBlocks.shift();\n if (first) {\n const shouldInsertNewlineChar =\n first.type === 'block' &&\n (first.delta.length() === 0 ||\n (!this.descendant(BlockEmbed, index)[0] && index < this.length()));\n const delta =\n first.type === 'block'\n ? first.delta\n : new Delta().insert({ [first.key]: first.value });\n insertInlineContents(this, index, delta);\n const newlineCharLength = first.type === 'block' ? 1 : 0;\n const lineEndIndex = index + delta.length() + newlineCharLength;\n if (shouldInsertNewlineChar) {\n this.insertAt(lineEndIndex - 1, '\\n');\n }\n\n const formats = bubbleFormats(this.line(index)[0]);\n const attributes = AttributeMap.diff(formats, first.attributes) || {};\n Object.keys(attributes).forEach((name) => {\n this.formatAt(lineEndIndex - 1, 1, name, attributes[name]);\n });\n\n index = lineEndIndex;\n }\n\n let [refBlot, refBlotOffset] = this.children.find(index);\n if (renderBlocks.length) {\n if (refBlot) {\n refBlot = refBlot.split(refBlotOffset);\n refBlotOffset = 0;\n }\n\n renderBlocks.forEach((renderBlock) => {\n if (renderBlock.type === 'block') {\n const block = this.createBlock(\n renderBlock.attributes,\n refBlot || undefined,\n );\n insertInlineContents(block, 0, renderBlock.delta);\n } else {\n const blockEmbed = this.create(\n renderBlock.key,\n renderBlock.value,\n ) as EmbedBlot;\n this.insertBefore(blockEmbed, refBlot || undefined);\n Object.keys(renderBlock.attributes).forEach((name) => {\n blockEmbed.format(name, renderBlock.attributes[name]);\n });\n }\n });\n }\n\n if (last.type === 'block' && last.delta.length()) {\n const offset = refBlot\n ? refBlot.offset(refBlot.scroll) + refBlotOffset\n : this.length();\n insertInlineContents(this, offset, last.delta);\n }\n\n this.batchEnd();\n this.optimize();\n }\n\n isEnabled() {\n return this.domNode.getAttribute('contenteditable') === 'true';\n }\n\n leaf(index: number): [LeafBlot | null, number] {\n const last = this.path(index).pop();\n if (!last) {\n return [null, -1];\n }\n\n const [blot, offset] = last;\n return blot instanceof LeafBlot ? [blot, offset] : [null, -1];\n }\n\n line(index: number): [Block | BlockEmbed | null, number] {\n if (index === this.length()) {\n return this.line(index - 1);\n }\n // @ts-expect-error TODO: make descendant() generic\n return this.descendant(isLine, index);\n }\n\n lines(index = 0, length = Number.MAX_VALUE): (Block | BlockEmbed)[] {\n const getLines = (\n blot: ParentBlot,\n blotIndex: number,\n blotLength: number,\n ) => {\n let lines: (Block | BlockEmbed)[] = [];\n let lengthLeft = blotLength;\n blot.children.forEachAt(\n blotIndex,\n blotLength,\n (child, childIndex, childLength) => {\n if (isLine(child)) {\n lines.push(child);\n } else if (child instanceof ContainerBlot) {\n lines = lines.concat(getLines(child, childIndex, lengthLeft));\n }\n lengthLeft -= childLength;\n },\n );\n return lines;\n };\n return getLines(this, index, length);\n }\n\n optimize(context?: { [key: string]: any }): void;\n optimize(\n mutations?: MutationRecord[],\n context?: { [key: string]: any },\n ): void;\n optimize(mutations = [], context = {}) {\n if (this.batch) return;\n super.optimize(mutations, context);\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_OPTIMIZE, mutations, context);\n }\n }\n\n path(index: number) {\n return super.path(index).slice(1); // Exclude self\n }\n\n remove() {\n // Never remove self\n }\n\n update(source?: EmitterSource): void;\n update(mutations?: MutationRecord[]): void;\n update(mutations?: MutationRecord[] | EmitterSource): void {\n if (this.batch) {\n if (Array.isArray(mutations)) {\n this.batch = this.batch.concat(mutations);\n }\n return;\n }\n let source: EmitterSource = Emitter.sources.USER;\n if (typeof mutations === 'string') {\n source = mutations;\n }\n if (!Array.isArray(mutations)) {\n mutations = this.observer.takeRecords();\n }\n mutations = mutations.filter(({ target }) => {\n const blot = this.find(target, true);\n return blot && !isUpdatable(blot);\n });\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_BEFORE_UPDATE, source, mutations);\n }\n super.update(mutations.concat([])); // pass copy\n if (mutations.length > 0) {\n this.emitter.emit(Emitter.events.SCROLL_UPDATE, source, mutations);\n }\n }\n\n updateEmbedAt(index: number, key: string, change: unknown) {\n // Currently it only supports top-level embeds (BlockEmbed).\n // We can update `ParentBlot` in parchment to support inline embeds.\n const [blot] = this.descendant((b: Blot) => b instanceof BlockEmbed, index);\n if (blot && blot.statics.blotName === key && isUpdatable(blot)) {\n blot.updateContent(change);\n }\n }\n\n protected handleDragStart(event: DragEvent) {\n event.preventDefault();\n }\n\n private deltaToRenderBlocks(delta: Delta) {\n const renderBlocks: RenderBlock[] = [];\n\n let currentBlockDelta = new Delta();\n delta.forEach((op) => {\n const insert = op?.insert;\n if (!insert) return;\n if (typeof insert === 'string') {\n const splitted = insert.split('\\n');\n splitted.slice(0, -1).forEach((text) => {\n currentBlockDelta.insert(text, op.attributes);\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: op.attributes ?? {},\n });\n currentBlockDelta = new Delta();\n });\n const last = splitted[splitted.length - 1];\n if (last) {\n currentBlockDelta.insert(last, op.attributes);\n }\n } else {\n const key = Object.keys(insert)[0];\n if (!key) return;\n if (this.query(key, Scope.INLINE)) {\n currentBlockDelta.push(op);\n } else {\n if (currentBlockDelta.length()) {\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: {},\n });\n }\n currentBlockDelta = new Delta();\n renderBlocks.push({\n type: 'blockEmbed',\n key,\n value: insert[key],\n attributes: op.attributes ?? {},\n });\n }\n }\n });\n\n if (currentBlockDelta.length()) {\n renderBlocks.push({\n type: 'block',\n delta: currentBlockDelta,\n attributes: {},\n });\n }\n\n return renderBlocks;\n }\n\n private createBlock(attributes: AttributeMap, refBlot?: Blot) {\n let blotName: string | undefined;\n const formats: AttributeMap = {};\n\n Object.entries(attributes).forEach(([key, value]) => {\n const isBlockBlot = this.query(key, Scope.BLOCK & Scope.BLOT) != null;\n if (isBlockBlot) {\n blotName = key;\n } else {\n formats[key] = value;\n }\n });\n\n const block = this.create(\n blotName || this.statics.defaultChild.blotName,\n blotName ? attributes[blotName] : undefined,\n ) as ParentBlot;\n\n this.insertBefore(block, refBlot || undefined);\n\n const length = block.length();\n Object.entries(formats).forEach(([key, value]) => {\n block.formatAt(0, length, key, value);\n });\n\n return block;\n }\n}\n\nfunction insertInlineContents(\n parent: ParentBlot,\n index: number,\n inlineContents: Delta,\n) {\n inlineContents.reduce((index, op) => {\n const length = Op.length(op);\n let attributes = op.attributes || {};\n if (op.insert != null) {\n if (typeof op.insert === 'string') {\n const text = op.insert;\n parent.insertAt(index, text);\n const [leaf] = parent.descendant(LeafBlot, index);\n const formats = bubbleFormats(leaf);\n attributes = AttributeMap.diff(formats, attributes) || {};\n } else if (typeof op.insert === 'object') {\n const key = Object.keys(op.insert)[0]; // There should only be one key\n if (key == null) return index;\n parent.insertAt(index, key, op.insert[key]);\n const isInlineEmbed = parent.scroll.query(key, Scope.INLINE) != null;\n if (isInlineEmbed) {\n const [leaf] = parent.descendant(LeafBlot, index);\n const formats = bubbleFormats(leaf);\n attributes = AttributeMap.diff(formats, attributes) || {};\n }\n }\n }\n Object.keys(attributes).forEach((key) => {\n parent.formatAt(index, length, key, attributes[key]);\n });\n return index + length;\n }, index);\n}\n\nexport default Scroll;\n", "import { Attributor, ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.BLOCK,\n whitelist: ['right', 'center', 'justify'],\n};\n\nconst AlignAttribute = new Attributor('align', 'align', config);\nconst AlignClass = new ClassAttributor('align', 'ql-align', config);\nconst AlignStyle = new StyleAttributor('align', 'text-align', config);\n\nexport { AlignAttribute, AlignClass, AlignStyle };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nclass ColorAttributor extends StyleAttributor {\n value(domNode: HTMLElement) {\n let value = super.value(domNode) as string;\n if (!value.startsWith('rgb(')) return value;\n value = value.replace(/^[^\\d]+/, '').replace(/[^\\d]+$/, '');\n const hex = value\n .split(',')\n .map((component) => `00${parseInt(component, 10).toString(16)}`.slice(-2))\n .join('');\n return `#${hex}`;\n }\n}\n\nconst ColorClass = new ClassAttributor('color', 'ql-color', {\n scope: Scope.INLINE,\n});\nconst ColorStyle = new ColorAttributor('color', 'color', {\n scope: Scope.INLINE,\n});\n\nexport { ColorAttributor, ColorClass, ColorStyle };\n", "import { ClassAttributor, Scope } from 'parchment';\nimport { ColorAttributor } from './color.js';\n\nconst BackgroundClass = new ClassAttributor('background', 'ql-bg', {\n scope: Scope.INLINE,\n});\nconst BackgroundStyle = new ColorAttributor('background', 'background-color', {\n scope: Scope.INLINE,\n});\n\nexport { BackgroundClass, BackgroundStyle };\n", "import Block from '../blots/block.js';\nimport Break from '../blots/break.js';\nimport Cursor from '../blots/cursor.js';\nimport Inline from '../blots/inline.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport Container from '../blots/container.js';\nimport Quill from '../core/quill.js';\n\nclass CodeBlockContainer extends Container {\n static create(value: string) {\n const domNode = super.create(value) as Element;\n domNode.setAttribute('spellcheck', 'false');\n return domNode;\n }\n\n code(index: number, length: number) {\n return (\n this.children\n // @ts-expect-error\n .map((child) => (child.length() <= 1 ? '' : child.domNode.innerText))\n .join('\\n')\n .slice(index, index + length)\n );\n }\n\n html(index: number, length: number) {\n // `\\n`s are needed in order to support empty lines at the beginning and the end.\n // https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions\n return `
    \\n${escapeText(this.code(index, length))}\\n
    `;\n }\n}\n\nclass CodeBlock extends Block {\n static TAB = ' ';\n\n static register() {\n Quill.register(CodeBlockContainer);\n }\n}\n\nclass Code extends Inline {}\nCode.blotName = 'code';\nCode.tagName = 'CODE';\n\nCodeBlock.blotName = 'code-block';\nCodeBlock.className = 'ql-code-block';\nCodeBlock.tagName = 'DIV';\nCodeBlockContainer.blotName = 'code-block-container';\nCodeBlockContainer.className = 'ql-code-block-container';\nCodeBlockContainer.tagName = 'DIV';\n\nCodeBlockContainer.allowedChildren = [CodeBlock];\n\nCodeBlock.allowedChildren = [TextBlot, Break, Cursor];\nCodeBlock.requiredContainer = CodeBlockContainer;\n\nexport { Code, CodeBlockContainer, CodeBlock as default };\n", "import { Attributor, ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.BLOCK,\n whitelist: ['rtl'],\n};\n\nconst DirectionAttribute = new Attributor('direction', 'dir', config);\nconst DirectionClass = new ClassAttributor('direction', 'ql-direction', config);\nconst DirectionStyle = new StyleAttributor('direction', 'direction', config);\n\nexport { DirectionAttribute, DirectionClass, DirectionStyle };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst config = {\n scope: Scope.INLINE,\n whitelist: ['serif', 'monospace'],\n};\n\nconst FontClass = new ClassAttributor('font', 'ql-font', config);\n\nclass FontStyleAttributor extends StyleAttributor {\n value(node: HTMLElement) {\n return super.value(node).replace(/[\"']/g, '');\n }\n}\n\nconst FontStyle = new FontStyleAttributor('font', 'font-family', config);\n\nexport { FontStyle, FontClass };\n", "import { ClassAttributor, Scope, StyleAttributor } from 'parchment';\n\nconst SizeClass = new ClassAttributor('size', 'ql-size', {\n scope: Scope.INLINE,\n whitelist: ['small', 'large', 'huge'],\n});\nconst SizeStyle = new StyleAttributor('size', 'font-size', {\n scope: Scope.INLINE,\n whitelist: ['10px', '18px', '32px'],\n});\n\nexport { SizeClass, SizeStyle };\n", "import { cloneDeep, isEqual } from 'lodash-es';\nimport Delta, { AttributeMap } from 'quill-delta';\nimport { EmbedBlot, Scope, TextBlot } from 'parchment';\nimport type { Blot, BlockBlot } from 'parchment';\nimport Quill from '../core/quill.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport type { BlockEmbed } from '../blots/block.js';\nimport type { Range } from '../core/selection.js';\n\nconst debug = logger('quill:keyboard');\n\nconst SHORTKEY = /Mac/i.test(navigator.platform) ? 'metaKey' : 'ctrlKey';\n\nexport interface Context {\n collapsed: boolean;\n empty: boolean;\n offset: number;\n prefix: string;\n suffix: string;\n format: Record;\n event: KeyboardEvent;\n line: BlockEmbed | BlockBlot;\n}\n\ninterface BindingObject\n extends Partial> {\n key: number | string | string[];\n shortKey?: boolean | null;\n shiftKey?: boolean | null;\n altKey?: boolean | null;\n metaKey?: boolean | null;\n ctrlKey?: boolean | null;\n prefix?: RegExp;\n suffix?: RegExp;\n format?: Record | string[];\n handler?: (\n this: { quill: Quill },\n range: Range,\n curContext: Context,\n // eslint-disable-next-line no-use-before-define\n binding: NormalizedBinding,\n ) => boolean | void;\n}\n\ntype Binding = BindingObject | string | number;\n\ninterface NormalizedBinding extends Omit {\n key: string | number;\n}\n\ninterface KeyboardOptions {\n bindings: Record;\n}\n\ninterface KeyboardOptions {\n bindings: Record;\n}\n\nclass Keyboard extends Module {\n static DEFAULTS: KeyboardOptions;\n\n static match(evt: KeyboardEvent, binding: BindingObject) {\n if (\n (['altKey', 'ctrlKey', 'metaKey', 'shiftKey'] as const).some((key) => {\n return !!binding[key] !== evt[key] && binding[key] !== null;\n })\n ) {\n return false;\n }\n return binding.key === evt.key || binding.key === evt.which;\n }\n\n bindings: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.bindings = {};\n // @ts-expect-error Fix me later\n Object.keys(this.options.bindings).forEach((name) => {\n // @ts-expect-error Fix me later\n if (this.options.bindings[name]) {\n // @ts-expect-error Fix me later\n this.addBinding(this.options.bindings[name]);\n }\n });\n this.addBinding({ key: 'Enter', shiftKey: null }, this.handleEnter);\n this.addBinding(\n { key: 'Enter', metaKey: null, ctrlKey: null, altKey: null },\n () => {},\n );\n if (/Firefox/i.test(navigator.userAgent)) {\n // Need to handle delete and backspace for Firefox in the general case #1171\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: true },\n this.handleBackspace,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: true },\n this.handleDelete,\n );\n } else {\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: true, prefix: /^.?$/ },\n this.handleBackspace,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: true, suffix: /^.?$/ },\n this.handleDelete,\n );\n }\n this.addBinding(\n { key: 'Backspace' },\n { collapsed: false },\n this.handleDeleteRange,\n );\n this.addBinding(\n { key: 'Delete' },\n { collapsed: false },\n this.handleDeleteRange,\n );\n this.addBinding(\n {\n key: 'Backspace',\n altKey: null,\n ctrlKey: null,\n metaKey: null,\n shiftKey: null,\n },\n { collapsed: true, offset: 0 },\n this.handleBackspace,\n );\n this.listen();\n }\n\n addBinding(\n keyBinding: Binding,\n context:\n | Required\n | Partial> = {},\n handler:\n | Required\n | Partial> = {},\n ) {\n const binding = normalize(keyBinding);\n if (binding == null) {\n debug.warn('Attempted to add invalid keyboard binding', binding);\n return;\n }\n if (typeof context === 'function') {\n context = { handler: context };\n }\n if (typeof handler === 'function') {\n handler = { handler };\n }\n const keys = Array.isArray(binding.key) ? binding.key : [binding.key];\n keys.forEach((key) => {\n const singleBinding = {\n ...binding,\n key,\n ...context,\n ...handler,\n };\n this.bindings[singleBinding.key] = this.bindings[singleBinding.key] || [];\n this.bindings[singleBinding.key].push(singleBinding);\n });\n }\n\n listen() {\n this.quill.root.addEventListener('keydown', (evt) => {\n if (evt.defaultPrevented || evt.isComposing) return;\n\n // evt.isComposing is false when pressing Enter/Backspace when composing in Safari\n // https://bugs.webkit.org/show_bug.cgi?id=165004\n const isComposing =\n evt.keyCode === 229 && (evt.key === 'Enter' || evt.key === 'Backspace');\n if (isComposing) return;\n\n const bindings = (this.bindings[evt.key] || []).concat(\n this.bindings[evt.which] || [],\n );\n const matches = bindings.filter((binding) =>\n Keyboard.match(evt, binding),\n );\n if (matches.length === 0) return;\n // @ts-expect-error\n const blot = Quill.find(evt.target, true);\n if (blot && blot.scroll !== this.quill.scroll) return;\n const range = this.quill.getSelection();\n if (range == null || !this.quill.hasFocus()) return;\n const [line, offset] = this.quill.getLine(range.index);\n const [leafStart, offsetStart] = this.quill.getLeaf(range.index);\n const [leafEnd, offsetEnd] =\n range.length === 0\n ? [leafStart, offsetStart]\n : this.quill.getLeaf(range.index + range.length);\n const prefixText =\n leafStart instanceof TextBlot\n ? leafStart.value().slice(0, offsetStart)\n : '';\n const suffixText =\n leafEnd instanceof TextBlot ? leafEnd.value().slice(offsetEnd) : '';\n const curContext = {\n collapsed: range.length === 0,\n // @ts-expect-error Fix me later\n empty: range.length === 0 && line.length() <= 1,\n format: this.quill.getFormat(range),\n line,\n offset,\n prefix: prefixText,\n suffix: suffixText,\n event: evt,\n };\n const prevented = matches.some((binding) => {\n if (\n binding.collapsed != null &&\n binding.collapsed !== curContext.collapsed\n ) {\n return false;\n }\n if (binding.empty != null && binding.empty !== curContext.empty) {\n return false;\n }\n if (binding.offset != null && binding.offset !== curContext.offset) {\n return false;\n }\n if (Array.isArray(binding.format)) {\n // any format is present\n if (binding.format.every((name) => curContext.format[name] == null)) {\n return false;\n }\n } else if (typeof binding.format === 'object') {\n // all formats must match\n if (\n !Object.keys(binding.format).every((name) => {\n // @ts-expect-error Fix me later\n if (binding.format[name] === true)\n return curContext.format[name] != null;\n // @ts-expect-error Fix me later\n if (binding.format[name] === false)\n return curContext.format[name] == null;\n // @ts-expect-error Fix me later\n return isEqual(binding.format[name], curContext.format[name]);\n })\n ) {\n return false;\n }\n }\n if (binding.prefix != null && !binding.prefix.test(curContext.prefix)) {\n return false;\n }\n if (binding.suffix != null && !binding.suffix.test(curContext.suffix)) {\n return false;\n }\n // @ts-expect-error Fix me later\n return binding.handler.call(this, range, curContext, binding) !== true;\n });\n if (prevented) {\n evt.preventDefault();\n }\n });\n }\n\n handleBackspace(range: Range, context: Context) {\n // Check for astral symbols\n const length = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]$/.test(context.prefix)\n ? 2\n : 1;\n if (range.index === 0 || this.quill.getLength() <= 1) return;\n let formats = {};\n const [line] = this.quill.getLine(range.index);\n let delta = new Delta().retain(range.index - length).delete(length);\n if (context.offset === 0) {\n // Always deleting newline here, length always 1\n const [prev] = this.quill.getLine(range.index - 1);\n if (prev) {\n const isPrevLineEmpty =\n prev.statics.blotName === 'block' && prev.length() <= 1;\n if (!isPrevLineEmpty) {\n // @ts-expect-error Fix me later\n const curFormats = line.formats();\n const prevFormats = this.quill.getFormat(range.index - 1, 1);\n formats = AttributeMap.diff(curFormats, prevFormats) || {};\n if (Object.keys(formats).length > 0) {\n // line.length() - 1 targets \\n in line, another -1 for newline being deleted\n const formatDelta = new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index + line.length() - 2)\n .retain(1, formats);\n delta = delta.compose(formatDelta);\n }\n }\n }\n }\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.focus();\n }\n\n handleDelete(range: Range, context: Context) {\n // Check for astral symbols\n const length = /^[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/.test(context.suffix)\n ? 2\n : 1;\n if (range.index >= this.quill.getLength() - length) return;\n let formats = {};\n const [line] = this.quill.getLine(range.index);\n let delta = new Delta().retain(range.index).delete(length);\n // @ts-expect-error Fix me later\n if (context.offset >= line.length() - 1) {\n const [next] = this.quill.getLine(range.index + 1);\n if (next) {\n // @ts-expect-error Fix me later\n const curFormats = line.formats();\n const nextFormats = this.quill.getFormat(range.index, 1);\n formats = AttributeMap.diff(curFormats, nextFormats) || {};\n if (Object.keys(formats).length > 0) {\n delta = delta.retain(next.length() - 1).retain(1, formats);\n }\n }\n }\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.focus();\n }\n\n handleDeleteRange(range: Range) {\n deleteRange({ range, quill: this.quill });\n this.quill.focus();\n }\n\n handleEnter(range: Range, context: Context) {\n const lineFormats = Object.keys(context.format).reduce(\n (formats: Record, format) => {\n if (\n this.quill.scroll.query(format, Scope.BLOCK) &&\n !Array.isArray(context.format[format])\n ) {\n formats[format] = context.format[format];\n }\n return formats;\n },\n {},\n );\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .insert('\\n', lineFormats);\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.focus();\n }\n}\n\nconst defaultOptions: KeyboardOptions = {\n bindings: {\n bold: makeFormatHandler('bold'),\n italic: makeFormatHandler('italic'),\n underline: makeFormatHandler('underline'),\n indent: {\n // highlight tab or tab at beginning of list, indent or blockquote\n key: 'Tab',\n format: ['blockquote', 'indent', 'list'],\n handler(range, context) {\n if (context.collapsed && context.offset !== 0) return true;\n this.quill.format('indent', '+1', Quill.sources.USER);\n return false;\n },\n },\n outdent: {\n key: 'Tab',\n shiftKey: true,\n format: ['blockquote', 'indent', 'list'],\n // highlight tab or tab at beginning of list, indent or blockquote\n handler(range, context) {\n if (context.collapsed && context.offset !== 0) return true;\n this.quill.format('indent', '-1', Quill.sources.USER);\n return false;\n },\n },\n 'outdent backspace': {\n key: 'Backspace',\n collapsed: true,\n shiftKey: null,\n metaKey: null,\n ctrlKey: null,\n altKey: null,\n format: ['indent', 'list'],\n offset: 0,\n handler(range, context) {\n if (context.format.indent != null) {\n this.quill.format('indent', '-1', Quill.sources.USER);\n } else if (context.format.list != null) {\n this.quill.format('list', false, Quill.sources.USER);\n }\n },\n },\n 'indent code-block': makeCodeBlockHandler(true),\n 'outdent code-block': makeCodeBlockHandler(false),\n 'remove tab': {\n key: 'Tab',\n shiftKey: true,\n collapsed: true,\n prefix: /\\t$/,\n handler(range) {\n this.quill.deleteText(range.index - 1, 1, Quill.sources.USER);\n },\n },\n tab: {\n key: 'Tab',\n handler(range, context) {\n if (context.format.table) return true;\n this.quill.history.cutoff();\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .insert('\\t');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.history.cutoff();\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n return false;\n },\n },\n 'blockquote empty enter': {\n key: 'Enter',\n collapsed: true,\n format: ['blockquote'],\n empty: true,\n handler() {\n this.quill.format('blockquote', false, Quill.sources.USER);\n },\n },\n 'list empty enter': {\n key: 'Enter',\n collapsed: true,\n format: ['list'],\n empty: true,\n handler(range, context) {\n const formats: Record = { list: false };\n if (context.format.indent) {\n formats.indent = false;\n }\n this.quill.formatLine(\n range.index,\n range.length,\n formats,\n Quill.sources.USER,\n );\n },\n },\n 'checklist enter': {\n key: 'Enter',\n collapsed: true,\n format: { list: 'checked' },\n handler(range) {\n const [line, offset] = this.quill.getLine(range.index);\n const formats = {\n // @ts-expect-error Fix me later\n ...line.formats(),\n list: 'checked',\n };\n const delta = new Delta()\n .retain(range.index)\n .insert('\\n', formats)\n // @ts-expect-error Fix me later\n .retain(line.length() - offset - 1)\n .retain(1, { list: 'unchecked' });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.scrollSelectionIntoView();\n },\n },\n 'header enter': {\n key: 'Enter',\n collapsed: true,\n format: ['header'],\n suffix: /^$/,\n handler(range, context) {\n const [line, offset] = this.quill.getLine(range.index);\n const delta = new Delta()\n .retain(range.index)\n .insert('\\n', context.format)\n // @ts-expect-error Fix me later\n .retain(line.length() - offset - 1)\n .retain(1, { header: null });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index + 1, Quill.sources.SILENT);\n this.quill.scrollSelectionIntoView();\n },\n },\n 'table backspace': {\n key: 'Backspace',\n format: ['table'],\n collapsed: true,\n offset: 0,\n handler() {},\n },\n 'table delete': {\n key: 'Delete',\n format: ['table'],\n collapsed: true,\n suffix: /^$/,\n handler() {},\n },\n 'table enter': {\n key: 'Enter',\n shiftKey: null,\n format: ['table'],\n handler(range) {\n const module = this.quill.getModule('table');\n if (module) {\n // @ts-expect-error\n const [table, row, cell, offset] = module.getTable(range);\n const shift = tableSide(table, row, cell, offset);\n if (shift == null) return;\n let index = table.offset();\n if (shift < 0) {\n const delta = new Delta().retain(index).insert('\\n');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(\n range.index + 1,\n range.length,\n Quill.sources.SILENT,\n );\n } else if (shift > 0) {\n index += table.length();\n const delta = new Delta().retain(index).insert('\\n');\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(index, Quill.sources.USER);\n }\n }\n },\n },\n 'table tab': {\n key: 'Tab',\n shiftKey: null,\n format: ['table'],\n handler(range, context) {\n const { event, line: cell } = context;\n const offset = cell.offset(this.quill.scroll);\n if (event.shiftKey) {\n this.quill.setSelection(offset - 1, Quill.sources.USER);\n } else {\n this.quill.setSelection(offset + cell.length(), Quill.sources.USER);\n }\n },\n },\n 'list autofill': {\n key: ' ',\n shiftKey: null,\n collapsed: true,\n format: {\n 'code-block': false,\n blockquote: false,\n table: false,\n },\n prefix: /^\\s*?(\\d+\\.|-|\\*|\\[ ?\\]|\\[x\\])$/,\n handler(range, context) {\n if (this.quill.scroll.query('list') == null) return true;\n const { length } = context.prefix;\n const [line, offset] = this.quill.getLine(range.index);\n if (offset > length) return true;\n let value;\n switch (context.prefix.trim()) {\n case '[]':\n case '[ ]':\n value = 'unchecked';\n break;\n case '[x]':\n value = 'checked';\n break;\n case '-':\n case '*':\n value = 'bullet';\n break;\n default:\n value = 'ordered';\n }\n this.quill.insertText(range.index, ' ', Quill.sources.USER);\n this.quill.history.cutoff();\n const delta = new Delta()\n .retain(range.index - offset)\n .delete(length + 1)\n // @ts-expect-error Fix me later\n .retain(line.length() - 2 - offset)\n .retain(1, { list: value });\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.history.cutoff();\n this.quill.setSelection(range.index - length, Quill.sources.SILENT);\n return false;\n },\n },\n 'code exit': {\n key: 'Enter',\n collapsed: true,\n format: ['code-block'],\n prefix: /^$/,\n suffix: /^\\s*$/,\n handler(range) {\n const [line, offset] = this.quill.getLine(range.index);\n let numLines = 2;\n let cur = line;\n while (\n cur != null &&\n cur.length() <= 1 &&\n cur.formats()['code-block']\n ) {\n // @ts-expect-error\n cur = cur.prev;\n numLines -= 1;\n // Requisite prev lines are empty\n if (numLines <= 0) {\n const delta = new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index + line.length() - offset - 2)\n .retain(1, { 'code-block': null })\n .delete(1);\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index - 1, Quill.sources.SILENT);\n return false;\n }\n }\n return true;\n },\n },\n 'embed left': makeEmbedArrowHandler('ArrowLeft', false),\n 'embed left shift': makeEmbedArrowHandler('ArrowLeft', true),\n 'embed right': makeEmbedArrowHandler('ArrowRight', false),\n 'embed right shift': makeEmbedArrowHandler('ArrowRight', true),\n 'table down': makeTableArrowHandler(false),\n 'table up': makeTableArrowHandler(true),\n },\n};\n\nKeyboard.DEFAULTS = defaultOptions;\n\nfunction makeCodeBlockHandler(indent: boolean): BindingObject {\n return {\n key: 'Tab',\n shiftKey: !indent,\n format: { 'code-block': true },\n handler(range, { event }) {\n const CodeBlock = this.quill.scroll.query('code-block');\n // @ts-expect-error\n const { TAB } = CodeBlock;\n if (range.length === 0 && !event.shiftKey) {\n this.quill.insertText(range.index, TAB, Quill.sources.USER);\n this.quill.setSelection(range.index + TAB.length, Quill.sources.SILENT);\n return;\n }\n\n const lines =\n range.length === 0\n ? this.quill.getLines(range.index, 1)\n : this.quill.getLines(range);\n let { index, length } = range;\n lines.forEach((line, i) => {\n if (indent) {\n line.insertAt(0, TAB);\n if (i === 0) {\n index += TAB.length;\n } else {\n length += TAB.length;\n }\n // @ts-expect-error Fix me later\n } else if (line.domNode.textContent.startsWith(TAB)) {\n line.deleteAt(0, TAB.length);\n if (i === 0) {\n index -= TAB.length;\n } else {\n length -= TAB.length;\n }\n }\n });\n this.quill.update(Quill.sources.USER);\n this.quill.setSelection(index, length, Quill.sources.SILENT);\n },\n };\n}\n\nfunction makeEmbedArrowHandler(\n key: string,\n shiftKey: boolean | null,\n): BindingObject {\n const where = key === 'ArrowLeft' ? 'prefix' : 'suffix';\n return {\n key,\n shiftKey,\n altKey: null,\n [where]: /^$/,\n handler(range) {\n let { index } = range;\n if (key === 'ArrowRight') {\n index += range.length + 1;\n }\n const [leaf] = this.quill.getLeaf(index);\n if (!(leaf instanceof EmbedBlot)) return true;\n if (key === 'ArrowLeft') {\n if (shiftKey) {\n this.quill.setSelection(\n range.index - 1,\n range.length + 1,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(range.index - 1, Quill.sources.USER);\n }\n } else if (shiftKey) {\n this.quill.setSelection(\n range.index,\n range.length + 1,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(\n range.index + range.length + 1,\n Quill.sources.USER,\n );\n }\n return false;\n },\n };\n}\n\nfunction makeFormatHandler(format: string): BindingObject {\n return {\n key: format[0],\n shortKey: true,\n handler(range, context) {\n this.quill.format(format, !context.format[format], Quill.sources.USER);\n },\n };\n}\n\nfunction makeTableArrowHandler(up: boolean): BindingObject {\n return {\n key: up ? 'ArrowUp' : 'ArrowDown',\n collapsed: true,\n format: ['table'],\n handler(range, context) {\n // TODO move to table module\n const key = up ? 'prev' : 'next';\n const cell = context.line;\n const targetRow = cell.parent[key];\n if (targetRow != null) {\n if (targetRow.statics.blotName === 'table-row') {\n // @ts-expect-error\n let targetCell = targetRow.children.head;\n let cur = cell;\n while (cur.prev != null) {\n // @ts-expect-error\n cur = cur.prev;\n targetCell = targetCell.next;\n }\n const index =\n targetCell.offset(this.quill.scroll) +\n Math.min(context.offset, targetCell.length() - 1);\n this.quill.setSelection(index, 0, Quill.sources.USER);\n }\n } else {\n // @ts-expect-error\n const targetLine = cell.table()[key];\n if (targetLine != null) {\n if (up) {\n this.quill.setSelection(\n targetLine.offset(this.quill.scroll) + targetLine.length() - 1,\n 0,\n Quill.sources.USER,\n );\n } else {\n this.quill.setSelection(\n targetLine.offset(this.quill.scroll),\n 0,\n Quill.sources.USER,\n );\n }\n }\n }\n return false;\n },\n };\n}\n\nfunction normalize(binding: Binding): BindingObject | null {\n if (typeof binding === 'string' || typeof binding === 'number') {\n binding = { key: binding };\n } else if (typeof binding === 'object') {\n binding = cloneDeep(binding);\n } else {\n return null;\n }\n if (binding.shortKey) {\n binding[SHORTKEY] = binding.shortKey;\n delete binding.shortKey;\n }\n return binding;\n}\n\n// TODO: Move into quill.ts or editor.ts\nfunction deleteRange({ quill, range }: { quill: Quill; range: Range }) {\n const lines = quill.getLines(range);\n let formats = {};\n if (lines.length > 1) {\n const firstFormats = lines[0].formats();\n const lastFormats = lines[lines.length - 1].formats();\n formats = AttributeMap.diff(lastFormats, firstFormats) || {};\n }\n quill.deleteText(range, Quill.sources.USER);\n if (Object.keys(formats).length > 0) {\n quill.formatLine(range.index, 1, formats, Quill.sources.USER);\n }\n quill.setSelection(range.index, Quill.sources.SILENT);\n}\n\nfunction tableSide(_table: unknown, row: Blot, cell: Blot, offset: number) {\n if (row.prev == null && row.next == null) {\n if (cell.prev == null && cell.next == null) {\n return offset === 0 ? -1 : 1;\n }\n return cell.prev == null ? -1 : 1;\n }\n if (row.prev == null) {\n return -1;\n }\n if (row.next == null) {\n return 1;\n }\n return null;\n}\n\nexport { Keyboard as default, SHORTKEY, normalize, deleteRange };\n", "const normalWeightRegexp = /font-weight:\\s*normal/;\nconst blockTagNames = ['P', 'OL', 'UL'];\n\nconst isBlockElement = (element: Element | null) => {\n return element && blockTagNames.includes(element.tagName);\n};\n\nconst normalizeEmptyLines = (doc: Document) => {\n Array.from(doc.querySelectorAll('br'))\n .filter(\n (br) =>\n isBlockElement(br.previousElementSibling) &&\n isBlockElement(br.nextElementSibling),\n )\n .forEach((br) => {\n br.parentNode?.removeChild(br);\n });\n};\n\nconst normalizeFontWeight = (doc: Document) => {\n Array.from(doc.querySelectorAll('b[style*=\"font-weight\"]'))\n .filter((node) => node.getAttribute('style')?.match(normalWeightRegexp))\n .forEach((node) => {\n const fragment = doc.createDocumentFragment();\n fragment.append(...node.childNodes);\n node.parentNode?.replaceChild(fragment, node);\n });\n};\n\nexport default function normalize(doc: Document) {\n if (doc.querySelector('[id^=\"docs-internal-guid-\"]')) {\n normalizeFontWeight(doc);\n normalizeEmptyLines(doc);\n }\n}\n", "const ignoreRegexp = /\\bmso-list:[^;]*ignore/i;\nconst idRegexp = /\\bmso-list:[^;]*\\bl(\\d+)/i;\nconst indentRegexp = /\\bmso-list:[^;]*\\blevel(\\d+)/i;\n\nconst parseListItem = (element: Element, html: string) => {\n const style = element.getAttribute('style');\n const idMatch = style?.match(idRegexp);\n if (!idMatch) {\n return null;\n }\n const id = Number(idMatch[1]);\n\n const indentMatch = style?.match(indentRegexp);\n const indent = indentMatch ? Number(indentMatch[1]) : 1;\n\n const typeRegexp = new RegExp(\n `@list l${id}:level${indent}\\\\s*\\\\{[^\\\\}]*mso-level-number-format:\\\\s*([\\\\w-]+)`,\n 'i',\n );\n const typeMatch = html.match(typeRegexp);\n const type = typeMatch && typeMatch[1] === 'bullet' ? 'bullet' : 'ordered';\n\n return { id, indent, type, element };\n};\n\n// list items are represented as `p` tags with styles like `mso-list: l0 level1` where:\n// 1. \"0\" in \"l0\" means the list item id;\n// 2. \"1\" in \"level1\" means the indent level, starting from 1.\nconst normalizeListItem = (doc: Document) => {\n const msoList = Array.from(doc.querySelectorAll('[style*=mso-list]'));\n const ignored: Element[] = [];\n const others: Element[] = [];\n msoList.forEach((node) => {\n const shouldIgnore = (node.getAttribute('style') || '').match(ignoreRegexp);\n if (shouldIgnore) {\n ignored.push(node);\n } else {\n others.push(node);\n }\n });\n\n // Each list item contains a marker wrapped with \"mso-list: Ignore\".\n ignored.forEach((node) => node.parentNode?.removeChild(node));\n\n // The list stype is not defined inline with the tag, instead, it's in the\n // style tag so we need to pass the html as a string.\n const html = doc.documentElement.innerHTML;\n const listItems = others\n .map((element) => parseListItem(element, html))\n .filter((parsed) => parsed);\n\n while (listItems.length) {\n const childListItems = [];\n\n let current = listItems.shift();\n // Group continuous items into the same group (aka \"ul\")\n while (current) {\n childListItems.push(current);\n current =\n listItems.length &&\n listItems[0]?.element === current.element.nextElementSibling &&\n // Different id means the next item doesn't belong to this group.\n listItems[0].id === current.id\n ? listItems.shift()\n : null;\n }\n\n const ul = document.createElement('ul');\n childListItems.forEach((listItem) => {\n const li = document.createElement('li');\n li.setAttribute('data-list', listItem.type);\n if (listItem.indent > 1) {\n li.setAttribute('class', `ql-indent-${listItem.indent - 1}`);\n }\n li.innerHTML = listItem.element.innerHTML;\n ul.appendChild(li);\n });\n\n const element = childListItems[0]?.element;\n const { parentNode } = element ?? {};\n if (element) {\n parentNode?.replaceChild(ul, element);\n }\n childListItems.slice(1).forEach(({ element: e }) => {\n parentNode?.removeChild(e);\n });\n }\n};\n\nexport default function normalize(doc: Document) {\n if (\n doc.documentElement.getAttribute('xmlns:w') ===\n 'urn:schemas-microsoft-com:office:word'\n ) {\n normalizeListItem(doc);\n }\n}\n", "import googleDocs from './normalizers/googleDocs.js';\nimport msWord from './normalizers/msWord.js';\n\nconst NORMALIZERS = [msWord, googleDocs];\n\nconst normalizeExternalHTML = (doc: Document) => {\n if (doc.documentElement) {\n NORMALIZERS.forEach((normalize) => {\n normalize(doc);\n });\n }\n};\n\nexport default normalizeExternalHTML;\n", "import type { ScrollBlot } from 'parchment';\nimport {\n Attributor,\n BlockBlot,\n ClassAttributor,\n EmbedBlot,\n Scope,\n StyleAttributor,\n} from 'parchment';\nimport Delta from 'quill-delta';\nimport { BlockEmbed } from '../blots/block.js';\nimport type { EmitterSource } from '../core/emitter.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type { Range } from '../core/selection.js';\nimport { AlignAttribute, AlignStyle } from '../formats/align.js';\nimport { BackgroundStyle } from '../formats/background.js';\nimport CodeBlock from '../formats/code.js';\nimport { ColorStyle } from '../formats/color.js';\nimport { DirectionAttribute, DirectionStyle } from '../formats/direction.js';\nimport { FontStyle } from '../formats/font.js';\nimport { SizeStyle } from '../formats/size.js';\nimport { deleteRange } from './keyboard.js';\nimport normalizeExternalHTML from './normalizeExternalHTML/index.js';\n\nconst debug = logger('quill:clipboard');\n\ntype Selector = string | Node['TEXT_NODE'] | Node['ELEMENT_NODE'];\ntype Matcher = (node: Node, delta: Delta, scroll: ScrollBlot) => Delta;\n\nconst CLIPBOARD_CONFIG: [Selector, Matcher][] = [\n [Node.TEXT_NODE, matchText],\n [Node.TEXT_NODE, matchNewline],\n ['br', matchBreak],\n [Node.ELEMENT_NODE, matchNewline],\n [Node.ELEMENT_NODE, matchBlot],\n [Node.ELEMENT_NODE, matchAttributor],\n [Node.ELEMENT_NODE, matchStyles],\n ['li', matchIndent],\n ['ol, ul', matchList],\n ['pre', matchCodeBlock],\n ['tr', matchTable],\n ['b', createMatchAlias('bold')],\n ['i', createMatchAlias('italic')],\n ['strike', createMatchAlias('strike')],\n ['style', matchIgnore],\n];\n\nconst ATTRIBUTE_ATTRIBUTORS = [AlignAttribute, DirectionAttribute].reduce(\n (memo: Record, attr) => {\n memo[attr.keyName] = attr;\n return memo;\n },\n {},\n);\n\nconst STYLE_ATTRIBUTORS = [\n AlignStyle,\n BackgroundStyle,\n ColorStyle,\n DirectionStyle,\n FontStyle,\n SizeStyle,\n].reduce((memo: Record, attr) => {\n memo[attr.keyName] = attr;\n return memo;\n}, {});\n\ninterface ClipboardOptions {\n matchers: [Selector, Matcher][];\n}\n\nclass Clipboard extends Module {\n static DEFAULTS: ClipboardOptions = {\n matchers: [],\n };\n\n matchers: [Selector, Matcher][];\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.quill.root.addEventListener('copy', (e) =>\n this.onCaptureCopy(e, false),\n );\n this.quill.root.addEventListener('cut', (e) => this.onCaptureCopy(e, true));\n this.quill.root.addEventListener('paste', this.onCapturePaste.bind(this));\n this.matchers = [];\n CLIPBOARD_CONFIG.concat(this.options.matchers ?? []).forEach(\n ([selector, matcher]) => {\n this.addMatcher(selector, matcher);\n },\n );\n }\n\n addMatcher(selector: Selector, matcher: Matcher) {\n this.matchers.push([selector, matcher]);\n }\n\n convert(\n { html, text }: { html?: string; text?: string },\n formats: Record = {},\n ) {\n if (formats[CodeBlock.blotName]) {\n return new Delta().insert(text || '', {\n [CodeBlock.blotName]: formats[CodeBlock.blotName],\n });\n }\n if (!html) {\n return new Delta().insert(text || '', formats);\n }\n const delta = this.convertHTML(html);\n // Remove trailing newline\n if (\n deltaEndsWith(delta, '\\n') &&\n (delta.ops[delta.ops.length - 1].attributes == null || formats.table)\n ) {\n return delta.compose(new Delta().retain(delta.length() - 1).delete(1));\n }\n return delta;\n }\n\n protected normalizeHTML(doc: Document) {\n normalizeExternalHTML(doc);\n }\n\n protected convertHTML(html: string) {\n const doc = new DOMParser().parseFromString(html, 'text/html');\n this.normalizeHTML(doc);\n const container = doc.body;\n const nodeMatches = new WeakMap();\n const [elementMatchers, textMatchers] = this.prepareMatching(\n container,\n nodeMatches,\n );\n return traverse(\n this.quill.scroll,\n container,\n elementMatchers,\n textMatchers,\n nodeMatches,\n );\n }\n\n dangerouslyPasteHTML(html: string, source?: EmitterSource): void;\n dangerouslyPasteHTML(\n index: number,\n html: string,\n source?: EmitterSource,\n ): void;\n dangerouslyPasteHTML(\n index: number | string,\n html?: string,\n source: EmitterSource = Quill.sources.API,\n ) {\n if (typeof index === 'string') {\n const delta = this.convert({ html: index, text: '' });\n // @ts-expect-error\n this.quill.setContents(delta, html);\n this.quill.setSelection(0, Quill.sources.SILENT);\n } else {\n const paste = this.convert({ html, text: '' });\n this.quill.updateContents(\n new Delta().retain(index).concat(paste),\n source,\n );\n this.quill.setSelection(index + paste.length(), Quill.sources.SILENT);\n }\n }\n\n onCaptureCopy(e: ClipboardEvent, isCut = false) {\n if (e.defaultPrevented) return;\n e.preventDefault();\n const [range] = this.quill.selection.getRange();\n if (range == null) return;\n const { html, text } = this.onCopy(range, isCut);\n e.clipboardData?.setData('text/plain', text);\n e.clipboardData?.setData('text/html', html);\n if (isCut) {\n deleteRange({ range, quill: this.quill });\n }\n }\n\n /*\n * https://www.iana.org/assignments/media-types/text/uri-list\n */\n private normalizeURIList(urlList: string) {\n return (\n urlList\n .split(/\\r?\\n/)\n // Ignore all comments\n .filter((url) => url[0] !== '#')\n .join('\\n')\n );\n }\n\n onCapturePaste(e: ClipboardEvent) {\n if (e.defaultPrevented || !this.quill.isEnabled()) return;\n e.preventDefault();\n const range = this.quill.getSelection(true);\n if (range == null) return;\n const html = e.clipboardData?.getData('text/html');\n let text = e.clipboardData?.getData('text/plain');\n if (!html && !text) {\n const urlList = e.clipboardData?.getData('text/uri-list');\n if (urlList) {\n text = this.normalizeURIList(urlList);\n }\n }\n const files = Array.from(e.clipboardData?.files || []);\n if (!html && files.length > 0) {\n this.quill.uploader.upload(range, files);\n return;\n }\n if (html && files.length > 0) {\n const doc = new DOMParser().parseFromString(html, 'text/html');\n if (\n doc.body.childElementCount === 1 &&\n doc.body.firstElementChild?.tagName === 'IMG'\n ) {\n this.quill.uploader.upload(range, files);\n return;\n }\n }\n this.onPaste(range, { html, text });\n }\n\n onCopy(range: Range, isCut: boolean): { html: string; text: string };\n onCopy(range: Range) {\n const text = this.quill.getText(range);\n const html = this.quill.getSemanticHTML(range);\n return { html, text };\n }\n\n onPaste(range: Range, { text, html }: { text?: string; html?: string }) {\n const formats = this.quill.getFormat(range.index);\n const pastedDelta = this.convert({ text, html }, formats);\n debug.log('onPaste', pastedDelta, { text, html });\n const delta = new Delta()\n .retain(range.index)\n .delete(range.length)\n .concat(pastedDelta);\n this.quill.updateContents(delta, Quill.sources.USER);\n // range.length contributes to delta.length()\n this.quill.setSelection(\n delta.length() - range.length,\n Quill.sources.SILENT,\n );\n this.quill.scrollSelectionIntoView();\n }\n\n prepareMatching(container: Element, nodeMatches: WeakMap) {\n const elementMatchers: Matcher[] = [];\n const textMatchers: Matcher[] = [];\n this.matchers.forEach((pair) => {\n const [selector, matcher] = pair;\n switch (selector) {\n case Node.TEXT_NODE:\n textMatchers.push(matcher);\n break;\n case Node.ELEMENT_NODE:\n elementMatchers.push(matcher);\n break;\n default:\n Array.from(container.querySelectorAll(selector)).forEach((node) => {\n if (nodeMatches.has(node)) {\n const matches = nodeMatches.get(node);\n matches?.push(matcher);\n } else {\n nodeMatches.set(node, [matcher]);\n }\n });\n break;\n }\n });\n return [elementMatchers, textMatchers];\n }\n}\n\nfunction applyFormat(\n delta: Delta,\n format: string,\n value: unknown,\n scroll: ScrollBlot,\n): Delta {\n if (!scroll.query(format)) {\n return delta;\n }\n\n return delta.reduce((newDelta, op) => {\n if (!op.insert) return newDelta;\n if (op.attributes && op.attributes[format]) {\n return newDelta.push(op);\n }\n const formats = value ? { [format]: value } : {};\n return newDelta.insert(op.insert, { ...formats, ...op.attributes });\n }, new Delta());\n}\n\nfunction deltaEndsWith(delta: Delta, text: string) {\n let endText = '';\n for (\n let i = delta.ops.length - 1;\n i >= 0 && endText.length < text.length;\n --i // eslint-disable-line no-plusplus\n ) {\n const op = delta.ops[i];\n if (typeof op.insert !== 'string') break;\n endText = op.insert + endText;\n }\n return endText.slice(-1 * text.length) === text;\n}\n\nfunction isLine(node: Node, scroll: ScrollBlot) {\n if (!(node instanceof Element)) return false;\n const match = scroll.query(node);\n // @ts-expect-error\n if (match && match.prototype instanceof EmbedBlot) return false;\n\n return [\n 'address',\n 'article',\n 'blockquote',\n 'canvas',\n 'dd',\n 'div',\n 'dl',\n 'dt',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'iframe',\n 'li',\n 'main',\n 'nav',\n 'ol',\n 'output',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'td',\n 'tr',\n 'ul',\n 'video',\n ].includes(node.tagName.toLowerCase());\n}\n\nfunction isBetweenInlineElements(node: HTMLElement, scroll: ScrollBlot) {\n return (\n node.previousElementSibling &&\n node.nextElementSibling &&\n !isLine(node.previousElementSibling, scroll) &&\n !isLine(node.nextElementSibling, scroll)\n );\n}\n\nconst preNodes = new WeakMap();\nfunction isPre(node: Node | null) {\n if (node == null) return false;\n if (!preNodes.has(node)) {\n // @ts-expect-error\n if (node.tagName === 'PRE') {\n preNodes.set(node, true);\n } else {\n preNodes.set(node, isPre(node.parentNode));\n }\n }\n return preNodes.get(node);\n}\n\nfunction traverse(\n scroll: ScrollBlot,\n node: ChildNode,\n elementMatchers: Matcher[],\n textMatchers: Matcher[],\n nodeMatches: WeakMap,\n): Delta {\n // Post-order\n if (node.nodeType === node.TEXT_NODE) {\n return textMatchers.reduce((delta: Delta, matcher) => {\n return matcher(node, delta, scroll);\n }, new Delta());\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n return Array.from(node.childNodes || []).reduce((delta, childNode) => {\n let childrenDelta = traverse(\n scroll,\n childNode,\n elementMatchers,\n textMatchers,\n nodeMatches,\n );\n if (childNode.nodeType === node.ELEMENT_NODE) {\n childrenDelta = elementMatchers.reduce((reducedDelta, matcher) => {\n return matcher(childNode as HTMLElement, reducedDelta, scroll);\n }, childrenDelta);\n childrenDelta = (nodeMatches.get(childNode) || []).reduce(\n (reducedDelta, matcher) => {\n return matcher(childNode, reducedDelta, scroll);\n },\n childrenDelta,\n );\n }\n return delta.concat(childrenDelta);\n }, new Delta());\n }\n return new Delta();\n}\n\nfunction createMatchAlias(format: string) {\n return (_node: Element, delta: Delta, scroll: ScrollBlot) => {\n return applyFormat(delta, format, true, scroll);\n };\n}\n\nfunction matchAttributor(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n const attributes = Attributor.keys(node);\n const classes = ClassAttributor.keys(node);\n const styles = StyleAttributor.keys(node);\n const formats: Record = {};\n attributes\n .concat(classes)\n .concat(styles)\n .forEach((name) => {\n let attr = scroll.query(name, Scope.ATTRIBUTE) as Attributor;\n if (attr != null) {\n formats[attr.attrName] = attr.value(node);\n if (formats[attr.attrName]) return;\n }\n attr = ATTRIBUTE_ATTRIBUTORS[name];\n if (attr != null && (attr.attrName === name || attr.keyName === name)) {\n formats[attr.attrName] = attr.value(node) || undefined;\n }\n attr = STYLE_ATTRIBUTORS[name];\n if (attr != null && (attr.attrName === name || attr.keyName === name)) {\n attr = STYLE_ATTRIBUTORS[name];\n formats[attr.attrName] = attr.value(node) || undefined;\n }\n });\n\n return Object.entries(formats).reduce(\n (newDelta, [name, value]) => applyFormat(newDelta, name, value, scroll),\n delta,\n );\n}\n\nfunction matchBlot(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query(node);\n if (match == null) return delta;\n // @ts-expect-error\n if (match.prototype instanceof EmbedBlot) {\n const embed = {};\n // @ts-expect-error\n const value = match.value(node);\n if (value != null) {\n // @ts-expect-error\n embed[match.blotName] = value;\n // @ts-expect-error\n return new Delta().insert(embed, match.formats(node, scroll));\n }\n } else {\n // @ts-expect-error\n if (match.prototype instanceof BlockBlot && !deltaEndsWith(delta, '\\n')) {\n delta.insert('\\n');\n }\n if (\n 'blotName' in match &&\n 'formats' in match &&\n typeof match.formats === 'function'\n ) {\n return applyFormat(\n delta,\n match.blotName,\n match.formats(node, scroll),\n scroll,\n );\n }\n }\n return delta;\n}\n\nfunction matchBreak(node: Node, delta: Delta) {\n if (!deltaEndsWith(delta, '\\n')) {\n delta.insert('\\n');\n }\n return delta;\n}\n\nfunction matchCodeBlock(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query('code-block');\n const language =\n match && 'formats' in match && typeof match.formats === 'function'\n ? match.formats(node, scroll)\n : true;\n return applyFormat(delta, 'code-block', language, scroll);\n}\n\nfunction matchIgnore() {\n return new Delta();\n}\n\nfunction matchIndent(node: Node, delta: Delta, scroll: ScrollBlot) {\n const match = scroll.query(node);\n if (\n match == null ||\n // @ts-expect-error\n match.blotName !== 'list' ||\n !deltaEndsWith(delta, '\\n')\n ) {\n return delta;\n }\n let indent = -1;\n let parent = node.parentNode;\n while (parent != null) {\n // @ts-expect-error\n if (['OL', 'UL'].includes(parent.tagName)) {\n indent += 1;\n }\n parent = parent.parentNode;\n }\n if (indent <= 0) return delta;\n return delta.reduce((composed, op) => {\n if (!op.insert) return composed;\n if (op.attributes && typeof op.attributes.indent === 'number') {\n return composed.push(op);\n }\n return composed.insert(op.insert, { indent, ...(op.attributes || {}) });\n }, new Delta());\n}\n\nfunction matchList(node: Node, delta: Delta, scroll: ScrollBlot) {\n const element = node as Element;\n let list = element.tagName === 'OL' ? 'ordered' : 'bullet';\n\n const checkedAttr = element.getAttribute('data-checked');\n if (checkedAttr) {\n list = checkedAttr === 'true' ? 'checked' : 'unchecked';\n }\n\n return applyFormat(delta, 'list', list, scroll);\n}\n\nfunction matchNewline(node: Node, delta: Delta, scroll: ScrollBlot) {\n if (!deltaEndsWith(delta, '\\n')) {\n if (\n isLine(node, scroll) &&\n (node.childNodes.length > 0 || node instanceof HTMLParagraphElement)\n ) {\n return delta.insert('\\n');\n }\n if (delta.length() > 0 && node.nextSibling) {\n let nextSibling: Node | null = node.nextSibling;\n while (nextSibling != null) {\n if (isLine(nextSibling, scroll)) {\n return delta.insert('\\n');\n }\n const match = scroll.query(nextSibling);\n // @ts-expect-error\n if (match && match.prototype instanceof BlockEmbed) {\n return delta.insert('\\n');\n }\n nextSibling = nextSibling.firstChild;\n }\n }\n }\n return delta;\n}\n\nfunction matchStyles(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n const formats: Record = {};\n const style: Partial = node.style || {};\n if (style.fontStyle === 'italic') {\n formats.italic = true;\n }\n if (style.textDecoration === 'underline') {\n formats.underline = true;\n }\n if (style.textDecoration === 'line-through') {\n formats.strike = true;\n }\n if (\n style.fontWeight?.startsWith('bold') ||\n // @ts-expect-error Fix me later\n parseInt(style.fontWeight, 10) >= 700\n ) {\n formats.bold = true;\n }\n delta = Object.entries(formats).reduce(\n (newDelta, [name, value]) => applyFormat(newDelta, name, value, scroll),\n delta,\n );\n // @ts-expect-error\n if (parseFloat(style.textIndent || 0) > 0) {\n // Could be 0.5in\n return new Delta().insert('\\t').concat(delta);\n }\n return delta;\n}\n\nfunction matchTable(\n node: HTMLTableRowElement,\n delta: Delta,\n scroll: ScrollBlot,\n) {\n const table =\n node.parentElement?.tagName === 'TABLE'\n ? node.parentElement\n : node.parentElement?.parentElement;\n if (table != null) {\n const rows = Array.from(table.querySelectorAll('tr'));\n const row = rows.indexOf(node) + 1;\n return applyFormat(delta, 'table', row, scroll);\n }\n return delta;\n}\n\nfunction matchText(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {\n // @ts-expect-error\n let text = node.data;\n // Word represents empty line with  \n if (node.parentElement?.tagName === 'O:P') {\n return delta.insert(text.trim());\n }\n if (!isPre(node)) {\n if (\n text.trim().length === 0 &&\n text.includes('\\n') &&\n !isBetweenInlineElements(node, scroll)\n ) {\n return delta;\n }\n const replacer = (collapse: unknown, match: string) => {\n const replaced = match.replace(/[^\\u00a0]/g, ''); // \\u00a0 is nbsp;\n return replaced.length < 1 && collapse ? ' ' : replaced;\n };\n text = text.replace(/\\r\\n/g, ' ').replace(/\\n/g, ' ');\n text = text.replace(/\\s\\s+/g, replacer.bind(replacer, true)); // collapse whitespace\n if (\n (node.previousSibling == null &&\n node.parentElement != null &&\n isLine(node.parentElement, scroll)) ||\n (node.previousSibling instanceof Element &&\n isLine(node.previousSibling, scroll))\n ) {\n text = text.replace(/^\\s+/, replacer.bind(replacer, false));\n }\n if (\n (node.nextSibling == null &&\n node.parentElement != null &&\n isLine(node.parentElement, scroll)) ||\n (node.nextSibling instanceof Element && isLine(node.nextSibling, scroll))\n ) {\n text = text.replace(/\\s+$/, replacer.bind(replacer, false));\n }\n }\n return delta.insert(text);\n}\n\nexport {\n Clipboard as default,\n matchAttributor,\n matchBlot,\n matchNewline,\n matchText,\n traverse,\n};\n", "import { Scope } from 'parchment';\nimport type Delta from 'quill-delta';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type Scroll from '../blots/scroll.js';\nimport type { Range } from '../core/selection.js';\n\nexport interface HistoryOptions {\n userOnly: boolean;\n delay: number;\n maxStack: number;\n}\n\nexport interface StackItem {\n delta: Delta;\n range: Range | null;\n}\n\ninterface Stack {\n undo: StackItem[];\n redo: StackItem[];\n}\n\nclass History extends Module {\n static DEFAULTS: HistoryOptions = {\n delay: 1000,\n maxStack: 100,\n userOnly: false,\n };\n\n lastRecorded = 0;\n ignoreChange = false;\n stack: Stack = { undo: [], redo: [] };\n currentRange: Range | null = null;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n this.quill.on(\n Quill.events.EDITOR_CHANGE,\n (eventName, value, oldValue, source) => {\n if (eventName === Quill.events.SELECTION_CHANGE) {\n if (value && source !== Quill.sources.SILENT) {\n this.currentRange = value;\n }\n } else if (eventName === Quill.events.TEXT_CHANGE) {\n if (!this.ignoreChange) {\n if (!this.options.userOnly || source === Quill.sources.USER) {\n this.record(value, oldValue);\n } else {\n this.transform(value);\n }\n }\n\n this.currentRange = transformRange(this.currentRange, value);\n }\n },\n );\n\n this.quill.keyboard.addBinding(\n { key: 'z', shortKey: true },\n this.undo.bind(this),\n );\n this.quill.keyboard.addBinding(\n { key: ['z', 'Z'], shortKey: true, shiftKey: true },\n this.redo.bind(this),\n );\n if (/Win/i.test(navigator.platform)) {\n this.quill.keyboard.addBinding(\n { key: 'y', shortKey: true },\n this.redo.bind(this),\n );\n }\n\n this.quill.root.addEventListener('beforeinput', (event) => {\n if (event.inputType === 'historyUndo') {\n this.undo();\n event.preventDefault();\n } else if (event.inputType === 'historyRedo') {\n this.redo();\n event.preventDefault();\n }\n });\n }\n\n change(source: 'undo' | 'redo', dest: 'redo' | 'undo') {\n if (this.stack[source].length === 0) return;\n const item = this.stack[source].pop();\n if (!item) return;\n const base = this.quill.getContents();\n const inverseDelta = item.delta.invert(base);\n this.stack[dest].push({\n delta: inverseDelta,\n range: transformRange(item.range, inverseDelta),\n });\n this.lastRecorded = 0;\n this.ignoreChange = true;\n this.quill.updateContents(item.delta, Quill.sources.USER);\n this.ignoreChange = false;\n\n this.restoreSelection(item);\n }\n\n clear() {\n this.stack = { undo: [], redo: [] };\n }\n\n cutoff() {\n this.lastRecorded = 0;\n }\n\n record(changeDelta: Delta, oldDelta: Delta) {\n if (changeDelta.ops.length === 0) return;\n this.stack.redo = [];\n let undoDelta = changeDelta.invert(oldDelta);\n let undoRange = this.currentRange;\n const timestamp = Date.now();\n if (\n // @ts-expect-error Fix me later\n this.lastRecorded + this.options.delay > timestamp &&\n this.stack.undo.length > 0\n ) {\n const item = this.stack.undo.pop();\n if (item) {\n undoDelta = undoDelta.compose(item.delta);\n undoRange = item.range;\n }\n } else {\n this.lastRecorded = timestamp;\n }\n if (undoDelta.length() === 0) return;\n this.stack.undo.push({ delta: undoDelta, range: undoRange });\n // @ts-expect-error Fix me later\n if (this.stack.undo.length > this.options.maxStack) {\n this.stack.undo.shift();\n }\n }\n\n redo() {\n this.change('redo', 'undo');\n }\n\n transform(delta: Delta) {\n transformStack(this.stack.undo, delta);\n transformStack(this.stack.redo, delta);\n }\n\n undo() {\n this.change('undo', 'redo');\n }\n\n protected restoreSelection(stackItem: StackItem) {\n if (stackItem.range) {\n this.quill.setSelection(stackItem.range, Quill.sources.USER);\n } else {\n const index = getLastChangeIndex(this.quill.scroll, stackItem.delta);\n this.quill.setSelection(index, Quill.sources.USER);\n }\n }\n}\n\nfunction transformStack(stack: StackItem[], delta: Delta) {\n let remoteDelta = delta;\n for (let i = stack.length - 1; i >= 0; i -= 1) {\n const oldItem = stack[i];\n stack[i] = {\n delta: remoteDelta.transform(oldItem.delta, true),\n range: oldItem.range && transformRange(oldItem.range, remoteDelta),\n };\n remoteDelta = oldItem.delta.transform(remoteDelta);\n if (stack[i].delta.length() === 0) {\n stack.splice(i, 1);\n }\n }\n}\n\nfunction endsWithNewlineChange(scroll: Scroll, delta: Delta) {\n const lastOp = delta.ops[delta.ops.length - 1];\n if (lastOp == null) return false;\n if (lastOp.insert != null) {\n return typeof lastOp.insert === 'string' && lastOp.insert.endsWith('\\n');\n }\n if (lastOp.attributes != null) {\n return Object.keys(lastOp.attributes).some((attr) => {\n return scroll.query(attr, Scope.BLOCK) != null;\n });\n }\n return false;\n}\n\nfunction getLastChangeIndex(scroll: Scroll, delta: Delta) {\n const deleteLength = delta.reduce((length, op) => {\n return length + (op.delete || 0);\n }, 0);\n let changeIndex = delta.length() - deleteLength;\n if (endsWithNewlineChange(scroll, delta)) {\n changeIndex -= 1;\n }\n return changeIndex;\n}\n\nfunction transformRange(range: Range | null, delta: Delta) {\n if (!range) return range;\n const start = delta.transformPosition(range.index);\n const end = delta.transformPosition(range.index + range.length);\n return { index: start, length: end - start };\n}\n\nexport { History as default, getLastChangeIndex };\n", "import Delta from 'quill-delta';\nimport type Quill from '../core/quill.js';\nimport Emitter from '../core/emitter.js';\nimport Module from '../core/module.js';\nimport type { Range } from '../core/selection.js';\n\ninterface UploaderOptions {\n mimetypes: string[];\n handler: (this: { quill: Quill }, range: Range, files: File[]) => void;\n}\n\nclass Uploader extends Module {\n static DEFAULTS: UploaderOptions;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n quill.root.addEventListener('drop', (e) => {\n e.preventDefault();\n let native: ReturnType | null = null;\n if (document.caretRangeFromPoint) {\n native = document.caretRangeFromPoint(e.clientX, e.clientY);\n // @ts-expect-error\n } else if (document.caretPositionFromPoint) {\n // @ts-expect-error\n const position = document.caretPositionFromPoint(e.clientX, e.clientY);\n native = document.createRange();\n native.setStart(position.offsetNode, position.offset);\n native.setEnd(position.offsetNode, position.offset);\n }\n\n const normalized = native && quill.selection.normalizeNative(native);\n if (normalized) {\n const range = quill.selection.normalizedToRange(normalized);\n if (e.dataTransfer?.files) {\n this.upload(range, e.dataTransfer.files);\n }\n }\n });\n }\n\n upload(range: Range, files: FileList | File[]) {\n const uploads: File[] = [];\n Array.from(files).forEach((file) => {\n if (file && this.options.mimetypes?.includes(file.type)) {\n uploads.push(file);\n }\n });\n if (uploads.length > 0) {\n // @ts-expect-error Fix me later\n this.options.handler.call(this, range, uploads);\n }\n }\n}\n\nUploader.DEFAULTS = {\n mimetypes: ['image/png', 'image/jpeg'],\n handler(range: Range, files: File[]) {\n if (!this.quill.scroll.query('image')) {\n return;\n }\n const promises = files.map>((file) => {\n return new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => {\n resolve(reader.result as string);\n };\n reader.readAsDataURL(file);\n });\n });\n Promise.all(promises).then((images) => {\n const update = images.reduce((delta: Delta, image) => {\n return delta.insert({ image });\n }, new Delta().retain(range.index).delete(range.length)) as Delta;\n this.quill.updateContents(update, Emitter.sources.USER);\n this.quill.setSelection(\n range.index + images.length,\n Emitter.sources.SILENT,\n );\n });\n },\n};\n\nexport default Uploader;\n", "import Delta from 'quill-delta';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\nimport type { Range } from '../core/selection.js';\nimport { deleteRange } from './keyboard.js';\n\nconst INSERT_TYPES = ['insertText', 'insertReplacementText'];\n\nclass Input extends Module {\n constructor(quill: Quill, options: Record) {\n super(quill, options);\n\n quill.root.addEventListener('beforeinput', (event) => {\n this.handleBeforeInput(event);\n });\n\n // Gboard with English input on Android triggers `compositionstart` sometimes even\n // users are not going to type anything.\n if (!/Android/i.test(navigator.userAgent)) {\n quill.on(Quill.events.COMPOSITION_BEFORE_START, () => {\n this.handleCompositionStart();\n });\n }\n }\n\n private deleteRange(range: Range) {\n deleteRange({ range, quill: this.quill });\n }\n\n private replaceText(range: Range, text = '') {\n if (range.length === 0) return false;\n\n if (text) {\n // Follow the native behavior that inherits the formats of the first character\n const formats = this.quill.getFormat(range.index, 1);\n this.deleteRange(range);\n this.quill.updateContents(\n new Delta().retain(range.index).insert(text, formats),\n Quill.sources.USER,\n );\n } else {\n this.deleteRange(range);\n }\n\n this.quill.setSelection(range.index + text.length, 0, Quill.sources.SILENT);\n return true;\n }\n\n private handleBeforeInput(event: InputEvent) {\n if (\n this.quill.composition.isComposing ||\n event.defaultPrevented ||\n !INSERT_TYPES.includes(event.inputType)\n ) {\n return;\n }\n\n const staticRange = event.getTargetRanges\n ? event.getTargetRanges()[0]\n : null;\n if (!staticRange || staticRange.collapsed === true) {\n return;\n }\n\n const text = getPlainTextFromInputEvent(event);\n if (text == null) {\n return;\n }\n const normalized = this.quill.selection.normalizeNative(staticRange);\n const range = normalized\n ? this.quill.selection.normalizedToRange(normalized)\n : null;\n if (range && this.replaceText(range, text)) {\n event.preventDefault();\n }\n }\n\n private handleCompositionStart() {\n const range = this.quill.getSelection();\n if (range) {\n this.replaceText(range);\n }\n }\n}\n\nfunction getPlainTextFromInputEvent(event: InputEvent) {\n // When `inputType` is \"insertText\":\n // - `event.data` should be string (Safari uses `event.dataTransfer`).\n // - `event.dataTransfer` should be null.\n // When `inputType` is \"insertReplacementText\":\n // - `event.data` should be null.\n // - `event.dataTransfer` should contain \"text/plain\" data.\n\n if (typeof event.data === 'string') {\n return event.data;\n }\n if (event.dataTransfer?.types.includes('text/plain')) {\n return event.dataTransfer.getData('text/plain');\n }\n return null;\n}\n\nexport default Input;\n", "import { ParentBlot } from 'parchment';\nimport Module from '../core/module.js';\nimport Quill from '../core/quill.js';\n\nconst isMac = /Mac/i.test(navigator.platform);\n\n// Export for testing\nexport const TTL_FOR_VALID_SELECTION_CHANGE = 100;\n\n// A loose check to determine if the shortcut can move the caret before a UI node:\n// [CARET]
    [CONTENT]
    \nconst canMoveCaretBeforeUINode = (event: KeyboardEvent) => {\n if (\n event.key === 'ArrowLeft' ||\n event.key === 'ArrowRight' || // RTL scripts or moving from the end of the previous line\n event.key === 'ArrowUp' ||\n event.key === 'ArrowDown' ||\n event.key === 'Home'\n ) {\n return true;\n }\n\n if (isMac && event.key === 'a' && event.ctrlKey === true) {\n return true;\n }\n\n return false;\n};\n\nclass UINode extends Module {\n isListening = false;\n selectionChangeDeadline = 0;\n\n constructor(quill: Quill, options: Record) {\n super(quill, options);\n\n this.handleArrowKeys();\n this.handleNavigationShortcuts();\n }\n\n private handleArrowKeys() {\n this.quill.keyboard.addBinding({\n key: ['ArrowLeft', 'ArrowRight'],\n offset: 0,\n shiftKey: null,\n handler(range, { line, event }) {\n if (!(line instanceof ParentBlot) || !line.uiNode) {\n return true;\n }\n\n const isRTL = getComputedStyle(line.domNode)['direction'] === 'rtl';\n if (\n (isRTL && event.key !== 'ArrowRight') ||\n (!isRTL && event.key !== 'ArrowLeft')\n ) {\n return true;\n }\n\n this.quill.setSelection(\n range.index - 1,\n range.length + (event.shiftKey ? 1 : 0),\n Quill.sources.USER,\n );\n return false;\n },\n });\n }\n\n private handleNavigationShortcuts() {\n this.quill.root.addEventListener('keydown', (event) => {\n if (!event.defaultPrevented && canMoveCaretBeforeUINode(event)) {\n this.ensureListeningToSelectionChange();\n }\n });\n }\n\n /**\n * We only listen to the `selectionchange` event when\n * there is an intention of moving the caret to the beginning using shortcuts.\n * This is primarily implemented to prevent infinite loops, as we are changing\n * the selection within the handler of a `selectionchange` event.\n */\n private ensureListeningToSelectionChange() {\n this.selectionChangeDeadline = Date.now() + TTL_FOR_VALID_SELECTION_CHANGE;\n\n if (this.isListening) return;\n this.isListening = true;\n\n const listener = () => {\n this.isListening = false;\n\n if (Date.now() <= this.selectionChangeDeadline) {\n this.handleSelectionChange();\n }\n };\n\n document.addEventListener('selectionchange', listener, {\n once: true,\n });\n }\n\n private handleSelectionChange() {\n const selection = document.getSelection();\n if (!selection) return;\n const range = selection.getRangeAt(0);\n if (range.collapsed !== true || range.startOffset !== 0) return;\n\n const line = this.quill.scroll.find(range.startContainer);\n if (!(line instanceof ParentBlot) || !line.uiNode) return;\n\n const newRange = document.createRange();\n newRange.setStartAfter(line.uiNode);\n newRange.setEndAfter(line.uiNode);\n selection.removeAllRanges();\n selection.addRange(newRange);\n }\n}\n\nexport default UINode;\n", "import Quill, { Parchment, Range } from './core/quill.js';\nimport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n} from './core/quill.js';\n\nimport Block, { BlockEmbed } from './blots/block.js';\nimport Break from './blots/break.js';\nimport Container from './blots/container.js';\nimport Cursor from './blots/cursor.js';\nimport Embed from './blots/embed.js';\nimport Inline from './blots/inline.js';\nimport Scroll from './blots/scroll.js';\nimport TextBlot from './blots/text.js';\n\nimport Clipboard from './modules/clipboard.js';\nimport History from './modules/history.js';\nimport Keyboard from './modules/keyboard.js';\nimport Uploader from './modules/uploader.js';\nimport Delta, { Op, OpIterator, AttributeMap } from 'quill-delta';\nimport Input from './modules/input.js';\nimport UINode from './modules/uiNode.js';\n\nexport { default as Module } from './core/module.js';\nexport { Delta, Op, OpIterator, AttributeMap, Parchment, Range };\nexport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n};\n\nQuill.register({\n 'blots/block': Block,\n 'blots/block/embed': BlockEmbed,\n 'blots/break': Break,\n 'blots/container': Container,\n 'blots/cursor': Cursor,\n 'blots/embed': Embed,\n 'blots/inline': Inline,\n 'blots/scroll': Scroll,\n 'blots/text': TextBlot,\n\n 'modules/clipboard': Clipboard,\n 'modules/history': History,\n 'modules/keyboard': Keyboard,\n 'modules/uploader': Uploader,\n 'modules/input': Input,\n 'modules/uiNode': UINode,\n});\n\nexport default Quill;\n", "import { ClassAttributor, Scope } from 'parchment';\n\nclass IndentAttributor extends ClassAttributor {\n add(node: HTMLElement, value: string | number) {\n let normalizedValue = 0;\n if (value === '+1' || value === '-1') {\n const indent = this.value(node) || 0;\n normalizedValue = value === '+1' ? indent + 1 : indent - 1;\n } else if (typeof value === 'number') {\n normalizedValue = value;\n }\n if (normalizedValue === 0) {\n this.remove(node);\n return true;\n }\n return super.add(node, normalizedValue.toString());\n }\n\n canAdd(node: HTMLElement, value: string) {\n return super.canAdd(node, value) || super.canAdd(node, parseInt(value, 10));\n }\n\n value(node: HTMLElement) {\n return parseInt(super.value(node), 10) || undefined; // Don't return NaN\n }\n}\n\nconst IndentClass = new IndentAttributor('indent', 'ql-indent', {\n scope: Scope.BLOCK,\n // @ts-expect-error\n whitelist: [1, 2, 3, 4, 5, 6, 7, 8],\n});\n\nexport default IndentClass;\n", "import Block from '../blots/block.js';\n\nclass Blockquote extends Block {\n static blotName = 'blockquote';\n static tagName = 'blockquote';\n}\n\nexport default Blockquote;\n", "import Block from '../blots/block.js';\n\nclass Header extends Block {\n static blotName = 'header';\n static tagName = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];\n\n static formats(domNode: Element) {\n return this.tagName.indexOf(domNode.tagName) + 1;\n }\n}\n\nexport default Header;\n", "import Block from '../blots/block.js';\nimport Container from '../blots/container.js';\nimport type Scroll from '../blots/scroll.js';\nimport Quill from '../core/quill.js';\n\nclass ListContainer extends Container {}\nListContainer.blotName = 'list-container';\nListContainer.tagName = 'OL';\n\nclass ListItem extends Block {\n static create(value: string) {\n const node = super.create() as HTMLElement;\n node.setAttribute('data-list', value);\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n return domNode.getAttribute('data-list') || undefined;\n }\n\n static register() {\n Quill.register(ListContainer);\n }\n\n constructor(scroll: Scroll, domNode: HTMLElement) {\n super(scroll, domNode);\n const ui = domNode.ownerDocument.createElement('span');\n const listEventHandler = (e: Event) => {\n if (!scroll.isEnabled()) return;\n const format = this.statics.formats(domNode, scroll);\n if (format === 'checked') {\n this.format('list', 'unchecked');\n e.preventDefault();\n } else if (format === 'unchecked') {\n this.format('list', 'checked');\n e.preventDefault();\n }\n };\n ui.addEventListener('mousedown', listEventHandler);\n ui.addEventListener('touchstart', listEventHandler);\n this.attachUI(ui);\n }\n\n format(name: string, value: string) {\n if (name === this.statics.blotName && value) {\n this.domNode.setAttribute('data-list', value);\n } else {\n super.format(name, value);\n }\n }\n}\nListItem.blotName = 'list';\nListItem.tagName = 'LI';\n\nListContainer.allowedChildren = [ListItem];\nListItem.requiredContainer = ListContainer;\n\nexport { ListContainer, ListItem as default };\n", "import Inline from '../blots/inline.js';\n\nclass Bold extends Inline {\n static blotName = 'bold';\n static tagName = ['STRONG', 'B'];\n\n static create() {\n return super.create();\n }\n\n static formats() {\n return true;\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n if (this.domNode.tagName !== this.statics.tagName[0]) {\n this.replaceWith(this.statics.blotName);\n }\n }\n}\n\nexport default Bold;\n", "import Bold from './bold.js';\n\nclass Italic extends Bold {\n static blotName = 'italic';\n static tagName = ['EM', 'I'];\n}\n\nexport default Italic;\n", "import Inline from '../blots/inline.js';\n\nclass Link extends Inline {\n static blotName = 'link';\n static tagName = 'A';\n static SANITIZED_URL = 'about:blank';\n static PROTOCOL_WHITELIST = ['http', 'https', 'mailto', 'tel', 'sms'];\n\n static create(value: string) {\n const node = super.create(value) as HTMLElement;\n node.setAttribute('href', this.sanitize(value));\n node.setAttribute('rel', 'noopener noreferrer');\n node.setAttribute('target', '_blank');\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n return domNode.getAttribute('href');\n }\n\n static sanitize(url: string) {\n return sanitize(url, this.PROTOCOL_WHITELIST) ? url : this.SANITIZED_URL;\n }\n\n format(name: string, value: unknown) {\n if (name !== this.statics.blotName || !value) {\n super.format(name, value);\n } else {\n // @ts-expect-error\n this.domNode.setAttribute('href', this.constructor.sanitize(value));\n }\n }\n}\n\nfunction sanitize(url: string, protocols: string[]) {\n const anchor = document.createElement('a');\n anchor.href = url;\n const protocol = anchor.href.slice(0, anchor.href.indexOf(':'));\n return protocols.indexOf(protocol) > -1;\n}\n\nexport { Link as default, sanitize };\n", "import Inline from '../blots/inline.js';\n\nclass Script extends Inline {\n static blotName = 'script';\n static tagName = ['SUB', 'SUP'];\n\n static create(value: 'super' | 'sub' | (string & {})) {\n if (value === 'super') {\n return document.createElement('sup');\n }\n if (value === 'sub') {\n return document.createElement('sub');\n }\n return super.create(value);\n }\n\n static formats(domNode: HTMLElement) {\n if (domNode.tagName === 'SUB') return 'sub';\n if (domNode.tagName === 'SUP') return 'super';\n return undefined;\n }\n}\n\nexport default Script;\n", "import Bold from './bold.js';\n\nclass Strike extends Bold {\n static blotName = 'strike';\n static tagName = ['S', 'STRIKE'];\n}\n\nexport default Strike;\n", "import Inline from '../blots/inline.js';\n\nclass Underline extends Inline {\n static blotName = 'underline';\n static tagName = 'U';\n}\n\nexport default Underline;\n", "import Embed from '../blots/embed.js';\n\nclass Formula extends Embed {\n static blotName = 'formula';\n static className = 'ql-formula';\n static tagName = 'SPAN';\n\n static create(value: string) {\n // @ts-expect-error\n if (window.katex == null) {\n throw new Error('Formula module requires KaTeX.');\n }\n const node = super.create(value) as Element;\n if (typeof value === 'string') {\n // @ts-expect-error\n window.katex.render(value, node, {\n throwOnError: false,\n errorColor: '#f00',\n });\n node.setAttribute('data-value', value);\n }\n return node;\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('data-value');\n }\n\n html() {\n const { formula } = this.value();\n return `${formula}`;\n }\n}\n\nexport default Formula;\n", "import { EmbedBlot } from 'parchment';\nimport { sanitize } from './link.js';\n\nconst ATTRIBUTES = ['alt', 'height', 'width'];\n\nclass Image extends EmbedBlot {\n static blotName = 'image';\n static tagName = 'IMG';\n\n static create(value: string) {\n const node = super.create(value) as Element;\n if (typeof value === 'string') {\n node.setAttribute('src', this.sanitize(value));\n }\n return node;\n }\n\n static formats(domNode: Element) {\n return ATTRIBUTES.reduce(\n (formats: Record, attribute) => {\n if (domNode.hasAttribute(attribute)) {\n formats[attribute] = domNode.getAttribute(attribute);\n }\n return formats;\n },\n {},\n );\n }\n\n static match(url: string) {\n return /\\.(jpe?g|gif|png)$/.test(url) || /^data:image\\/.+;base64/.test(url);\n }\n\n static sanitize(url: string) {\n return sanitize(url, ['http', 'https', 'data']) ? url : '//:0';\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('src');\n }\n\n domNode: HTMLImageElement;\n\n format(name: string, value: string) {\n if (ATTRIBUTES.indexOf(name) > -1) {\n if (value) {\n this.domNode.setAttribute(name, value);\n } else {\n this.domNode.removeAttribute(name);\n }\n } else {\n super.format(name, value);\n }\n }\n}\n\nexport default Image;\n", "import { BlockEmbed } from '../blots/block.js';\nimport Link from './link.js';\n\nconst ATTRIBUTES = ['height', 'width'];\n\nclass Video extends BlockEmbed {\n static blotName = 'video';\n static className = 'ql-video';\n static tagName = 'IFRAME';\n\n static create(value: string) {\n const node = super.create(value) as Element;\n node.setAttribute('frameborder', '0');\n node.setAttribute('allowfullscreen', 'true');\n node.setAttribute('src', this.sanitize(value));\n return node;\n }\n\n static formats(domNode: Element) {\n return ATTRIBUTES.reduce(\n (formats: Record, attribute) => {\n if (domNode.hasAttribute(attribute)) {\n formats[attribute] = domNode.getAttribute(attribute);\n }\n return formats;\n },\n {},\n );\n }\n\n static sanitize(url: string) {\n return Link.sanitize(url);\n }\n\n static value(domNode: Element) {\n return domNode.getAttribute('src');\n }\n\n domNode: HTMLVideoElement;\n\n format(name: string, value: string) {\n if (ATTRIBUTES.indexOf(name) > -1) {\n if (value) {\n this.domNode.setAttribute(name, value);\n } else {\n this.domNode.removeAttribute(name);\n }\n } else {\n super.format(name, value);\n }\n }\n\n html() {\n const { video } = this.value();\n return `${video}`;\n }\n}\n\nexport default Video;\n", "import Delta from 'quill-delta';\nimport { ClassAttributor, Scope } from 'parchment';\nimport type { Blot, ScrollBlot } from 'parchment';\nimport Inline from '../blots/inline.js';\nimport Quill from '../core/quill.js';\nimport Module from '../core/module.js';\nimport { blockDelta } from '../blots/block.js';\nimport BreakBlot from '../blots/break.js';\nimport CursorBlot from '../blots/cursor.js';\nimport TextBlot, { escapeText } from '../blots/text.js';\nimport CodeBlock, { CodeBlockContainer } from '../formats/code.js';\nimport { traverse } from './clipboard.js';\n\nconst TokenAttributor = new ClassAttributor('code-token', 'hljs', {\n scope: Scope.INLINE,\n});\nclass CodeToken extends Inline {\n static formats(node: Element, scroll: ScrollBlot) {\n while (node != null && node !== scroll.domNode) {\n if (node.classList && node.classList.contains(CodeBlock.className)) {\n // @ts-expect-error\n return super.formats(node, scroll);\n }\n // @ts-expect-error\n node = node.parentNode;\n }\n return undefined;\n }\n\n constructor(scroll: ScrollBlot, domNode: Node, value: unknown) {\n // @ts-expect-error\n super(scroll, domNode, value);\n TokenAttributor.add(this.domNode, value);\n }\n\n format(format: string, value: unknown) {\n if (format !== CodeToken.blotName) {\n super.format(format, value);\n } else if (value) {\n TokenAttributor.add(this.domNode, value);\n } else {\n TokenAttributor.remove(this.domNode);\n this.domNode.classList.remove(this.statics.className);\n }\n }\n\n optimize(...args: unknown[]) {\n // @ts-expect-error\n super.optimize(...args);\n if (!TokenAttributor.value(this.domNode)) {\n this.unwrap();\n }\n }\n}\nCodeToken.blotName = 'code-token';\nCodeToken.className = 'ql-token';\n\nclass SyntaxCodeBlock extends CodeBlock {\n static create(value: unknown) {\n const domNode = super.create(value);\n if (typeof value === 'string') {\n domNode.setAttribute('data-language', value);\n }\n return domNode;\n }\n\n static formats(domNode: Node) {\n // @ts-expect-error\n return domNode.getAttribute('data-language') || 'plain';\n }\n\n static register() {} // Syntax module will register\n\n format(name: string, value: unknown) {\n if (name === this.statics.blotName && value) {\n // @ts-expect-error\n this.domNode.setAttribute('data-language', value);\n } else {\n super.format(name, value);\n }\n }\n\n replaceWith(name: string | Blot, value?: any) {\n this.formatAt(0, this.length(), CodeToken.blotName, false);\n return super.replaceWith(name, value);\n }\n}\n\nclass SyntaxCodeBlockContainer extends CodeBlockContainer {\n forceNext?: boolean;\n cachedText?: string | null;\n\n attach() {\n super.attach();\n this.forceNext = false;\n // @ts-expect-error\n this.scroll.emitMount(this);\n }\n\n format(name: string, value: unknown) {\n if (name === SyntaxCodeBlock.blotName) {\n this.forceNext = true;\n this.children.forEach((child) => {\n // @ts-expect-error\n child.format(name, value);\n });\n }\n }\n\n formatAt(index: number, length: number, name: string, value: unknown) {\n if (name === SyntaxCodeBlock.blotName) {\n this.forceNext = true;\n }\n super.formatAt(index, length, name, value);\n }\n\n highlight(\n highlight: (text: string, language: string) => Delta,\n forced = false,\n ) {\n if (this.children.head == null) return;\n const nodes = Array.from(this.domNode.childNodes).filter(\n (node) => node !== this.uiNode,\n );\n const text = `${nodes.map((node) => node.textContent).join('\\n')}\\n`;\n const language = SyntaxCodeBlock.formats(this.children.head.domNode);\n if (forced || this.forceNext || this.cachedText !== text) {\n if (text.trim().length > 0 || this.cachedText == null) {\n const oldDelta = this.children.reduce((delta, child) => {\n // @ts-expect-error\n return delta.concat(blockDelta(child, false));\n }, new Delta());\n const delta = highlight(text, language);\n oldDelta.diff(delta).reduce((index, { retain, attributes }) => {\n // Should be all retains\n if (!retain) return index;\n if (attributes) {\n Object.keys(attributes).forEach((format) => {\n if (\n [SyntaxCodeBlock.blotName, CodeToken.blotName].includes(format)\n ) {\n // @ts-expect-error\n this.formatAt(index, retain, format, attributes[format]);\n }\n });\n }\n // @ts-expect-error\n return index + retain;\n }, 0);\n }\n this.cachedText = text;\n this.forceNext = false;\n }\n }\n\n html(index: number, length: number) {\n const [codeBlock] = this.children.find(index);\n const language = codeBlock\n ? SyntaxCodeBlock.formats(codeBlock.domNode)\n : 'plain';\n\n return `
    \\n${escapeText(\n      this.code(index, length),\n    )}\\n
    `;\n }\n\n optimize(context: Record) {\n super.optimize(context);\n if (\n this.parent != null &&\n this.children.head != null &&\n this.uiNode != null\n ) {\n const language = SyntaxCodeBlock.formats(this.children.head.domNode);\n // @ts-expect-error\n if (language !== this.uiNode.value) {\n // @ts-expect-error\n this.uiNode.value = language;\n }\n }\n }\n}\n\nSyntaxCodeBlockContainer.allowedChildren = [SyntaxCodeBlock];\nSyntaxCodeBlock.requiredContainer = SyntaxCodeBlockContainer;\nSyntaxCodeBlock.allowedChildren = [CodeToken, CursorBlot, TextBlot, BreakBlot];\n\ninterface SyntaxOptions {\n interval: number;\n languages: { key: string; label: string }[];\n hljs: any;\n}\n\nconst highlight = (lib: any, language: string, text: string) => {\n if (typeof lib.versionString === 'string') {\n const majorVersion = lib.versionString.split('.')[0];\n if (parseInt(majorVersion, 10) >= 11) {\n return lib.highlight(text, { language }).value;\n }\n }\n return lib.highlight(language, text).value;\n};\n\nclass Syntax extends Module {\n static DEFAULTS: SyntaxOptions & { hljs: any };\n\n static register() {\n Quill.register(CodeToken, true);\n Quill.register(SyntaxCodeBlock, true);\n Quill.register(SyntaxCodeBlockContainer, true);\n }\n\n languages: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n if (this.options.hljs == null) {\n throw new Error(\n 'Syntax module requires highlight.js. Please include the library on the page before Quill.',\n );\n }\n // @ts-expect-error Fix me later\n this.languages = this.options.languages.reduce(\n (memo: Record, { key }) => {\n memo[key] = true;\n return memo;\n },\n {},\n );\n this.highlightBlot = this.highlightBlot.bind(this);\n this.initListener();\n this.initTimer();\n }\n\n initListener() {\n this.quill.on(Quill.events.SCROLL_BLOT_MOUNT, (blot: Blot) => {\n if (!(blot instanceof SyntaxCodeBlockContainer)) return;\n const select = this.quill.root.ownerDocument.createElement('select');\n // @ts-expect-error Fix me later\n this.options.languages.forEach(({ key, label }) => {\n const option = select.ownerDocument.createElement('option');\n option.textContent = label;\n option.setAttribute('value', key);\n select.appendChild(option);\n });\n select.addEventListener('change', () => {\n blot.format(SyntaxCodeBlock.blotName, select.value);\n this.quill.root.focus(); // Prevent scrolling\n this.highlight(blot, true);\n });\n if (blot.uiNode == null) {\n blot.attachUI(select);\n if (blot.children.head) {\n select.value = SyntaxCodeBlock.formats(blot.children.head.domNode);\n }\n }\n });\n }\n\n initTimer() {\n let timer: ReturnType | null = null;\n this.quill.on(Quill.events.SCROLL_OPTIMIZE, () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = setTimeout(() => {\n this.highlight();\n timer = null;\n }, this.options.interval);\n });\n }\n\n highlight(blot: SyntaxCodeBlockContainer | null = null, force = false) {\n if (this.quill.selection.composing) return;\n this.quill.update(Quill.sources.USER);\n const range = this.quill.getSelection();\n const blots =\n blot == null\n ? this.quill.scroll.descendants(SyntaxCodeBlockContainer)\n : [blot];\n blots.forEach((container) => {\n container.highlight(this.highlightBlot, force);\n });\n this.quill.update(Quill.sources.SILENT);\n if (range != null) {\n this.quill.setSelection(range, Quill.sources.SILENT);\n }\n }\n\n highlightBlot(text: string, language = 'plain') {\n language = this.languages[language] ? language : 'plain';\n if (language === 'plain') {\n return escapeText(text)\n .split('\\n')\n .reduce((delta, line, i) => {\n if (i !== 0) {\n delta.insert('\\n', { [CodeBlock.blotName]: language });\n }\n return delta.insert(line);\n }, new Delta());\n }\n const container = this.quill.root.ownerDocument.createElement('div');\n container.classList.add(CodeBlock.className);\n container.innerHTML = highlight(this.options.hljs, language, text);\n return traverse(\n this.quill.scroll,\n container,\n [\n (node, delta) => {\n // @ts-expect-error\n const value = TokenAttributor.value(node);\n if (value) {\n return delta.compose(\n new Delta().retain(delta.length(), {\n [CodeToken.blotName]: value,\n }),\n );\n }\n return delta;\n },\n ],\n [\n (node, delta) => {\n // @ts-expect-error\n return node.data.split('\\n').reduce((memo, nodeText, i) => {\n if (i !== 0) memo.insert('\\n', { [CodeBlock.blotName]: language });\n return memo.insert(nodeText);\n }, delta);\n },\n ],\n new WeakMap(),\n );\n }\n}\nSyntax.DEFAULTS = {\n hljs: (() => {\n return window.hljs;\n })(),\n interval: 1000,\n languages: [\n { key: 'plain', label: 'Plain' },\n { key: 'bash', label: 'Bash' },\n { key: 'cpp', label: 'C++' },\n { key: 'cs', label: 'C#' },\n { key: 'css', label: 'CSS' },\n { key: 'diff', label: 'Diff' },\n { key: 'xml', label: 'HTML/XML' },\n { key: 'java', label: 'Java' },\n { key: 'javascript', label: 'JavaScript' },\n { key: 'markdown', label: 'Markdown' },\n { key: 'php', label: 'PHP' },\n { key: 'python', label: 'Python' },\n { key: 'ruby', label: 'Ruby' },\n { key: 'sql', label: 'SQL' },\n ],\n};\n\nexport { SyntaxCodeBlock as CodeBlock, CodeToken, Syntax as default };\n", "import type { LinkedList } from 'parchment';\nimport Block from '../blots/block.js';\nimport Container from '../blots/container.js';\n\nclass TableCell extends Block {\n static blotName = 'table';\n static tagName = 'TD';\n\n static create(value: string) {\n const node = super.create() as HTMLElement;\n if (value) {\n node.setAttribute('data-row', value);\n } else {\n node.setAttribute('data-row', tableId());\n }\n return node;\n }\n\n static formats(domNode: HTMLElement) {\n if (domNode.hasAttribute('data-row')) {\n return domNode.getAttribute('data-row');\n }\n return undefined;\n }\n\n next: this | null;\n\n cellOffset() {\n if (this.parent) {\n return this.parent.children.indexOf(this);\n }\n return -1;\n }\n\n format(name: string, value: string) {\n if (name === TableCell.blotName && value) {\n this.domNode.setAttribute('data-row', value);\n } else {\n super.format(name, value);\n }\n }\n\n row(): TableRow {\n return this.parent as TableRow;\n }\n\n rowOffset() {\n if (this.row()) {\n return this.row().rowOffset();\n }\n return -1;\n }\n\n table() {\n return this.row() && this.row().table();\n }\n}\n\nclass TableRow extends Container {\n static blotName = 'table-row';\n static tagName = 'TR';\n\n children: LinkedList;\n next: this | null;\n\n checkMerge() {\n // @ts-expect-error\n if (super.checkMerge() && this.next.children.head != null) {\n // @ts-expect-error\n const thisHead = this.children.head.formats();\n // @ts-expect-error\n const thisTail = this.children.tail.formats();\n // @ts-expect-error\n const nextHead = this.next.children.head.formats();\n // @ts-expect-error\n const nextTail = this.next.children.tail.formats();\n return (\n thisHead.table === thisTail.table &&\n thisHead.table === nextHead.table &&\n thisHead.table === nextTail.table\n );\n }\n return false;\n }\n\n optimize(context: { [key: string]: any }) {\n super.optimize(context);\n this.children.forEach((child) => {\n if (child.next == null) return;\n const childFormats = child.formats();\n const nextFormats = child.next.formats();\n if (childFormats.table !== nextFormats.table) {\n const next = this.splitAfter(child);\n if (next) {\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n next.optimize();\n }\n // We might be able to merge with prev now\n if (this.prev) {\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n this.prev.optimize();\n }\n }\n });\n }\n\n rowOffset() {\n if (this.parent) {\n return this.parent.children.indexOf(this);\n }\n return -1;\n }\n\n table() {\n return this.parent && this.parent.parent;\n }\n}\n\nclass TableBody extends Container {\n static blotName = 'table-body';\n static tagName = 'TBODY';\n\n children: LinkedList;\n}\n\nclass TableContainer extends Container {\n static blotName = 'table-container';\n static tagName = 'TABLE';\n\n children: LinkedList;\n\n balanceCells() {\n const rows = this.descendants(TableRow);\n const maxColumns = rows.reduce((max, row) => {\n return Math.max(row.children.length, max);\n }, 0);\n rows.forEach((row) => {\n new Array(maxColumns - row.children.length).fill(0).forEach(() => {\n let value;\n if (row.children.head != null) {\n value = TableCell.formats(row.children.head.domNode);\n }\n const blot = this.scroll.create(TableCell.blotName, value);\n row.appendChild(blot);\n // @ts-expect-error TODO: parameters of optimize() should be a optional\n blot.optimize(); // Add break blot\n });\n });\n }\n\n cells(column: number) {\n return this.rows().map((row) => row.children.at(column));\n }\n\n deleteColumn(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n body.children.forEach((row) => {\n const cell = row.children.at(index);\n if (cell != null) {\n cell.remove();\n }\n });\n }\n\n insertColumn(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n body.children.forEach((row) => {\n const ref = row.children.at(index);\n // @ts-expect-error\n const value = TableCell.formats(row.children.head.domNode);\n const cell = this.scroll.create(TableCell.blotName, value);\n row.insertBefore(cell, ref);\n });\n }\n\n insertRow(index: number) {\n // @ts-expect-error\n const [body] = this.descendant(TableBody) as TableBody[];\n if (body == null || body.children.head == null) return;\n const id = tableId();\n const row = this.scroll.create(TableRow.blotName) as TableRow;\n body.children.head.children.forEach(() => {\n const cell = this.scroll.create(TableCell.blotName, id);\n row.appendChild(cell);\n });\n const ref = body.children.at(index);\n body.insertBefore(row, ref);\n }\n\n rows() {\n const body = this.children.head;\n if (body == null) return [];\n return body.children.map((row) => row);\n }\n}\n\nTableContainer.allowedChildren = [TableBody];\nTableBody.requiredContainer = TableContainer;\n\nTableBody.allowedChildren = [TableRow];\nTableRow.requiredContainer = TableBody;\n\nTableRow.allowedChildren = [TableCell];\nTableCell.requiredContainer = TableRow;\n\nfunction tableId() {\n const id = Math.random().toString(36).slice(2, 6);\n return `row-${id}`;\n}\n\nexport { TableCell, TableRow, TableBody, TableContainer, tableId };\n", "import Delta from 'quill-delta';\nimport Quill from '../core/quill.js';\nimport Module from '../core/module.js';\nimport {\n TableCell,\n TableRow,\n TableBody,\n TableContainer,\n tableId,\n} from '../formats/table.js';\n\nclass Table extends Module {\n static register() {\n Quill.register(TableCell);\n Quill.register(TableRow);\n Quill.register(TableBody);\n Quill.register(TableContainer);\n }\n\n constructor(...args: ConstructorParameters) {\n super(...args);\n this.listenBalanceCells();\n }\n\n balanceTables() {\n this.quill.scroll.descendants(TableContainer).forEach((table) => {\n table.balanceCells();\n });\n }\n\n deleteColumn() {\n const [table, , cell] = this.getTable();\n if (cell == null) return;\n // @ts-expect-error\n table.deleteColumn(cell.cellOffset());\n this.quill.update(Quill.sources.USER);\n }\n\n deleteRow() {\n const [, row] = this.getTable();\n if (row == null) return;\n row.remove();\n this.quill.update(Quill.sources.USER);\n }\n\n deleteTable() {\n const [table] = this.getTable();\n if (table == null) return;\n // @ts-expect-error\n const offset = table.offset();\n // @ts-expect-error\n table.remove();\n this.quill.update(Quill.sources.USER);\n this.quill.setSelection(offset, Quill.sources.SILENT);\n }\n\n getTable(\n range = this.quill.getSelection(),\n ): [null, null, null, -1] | [Table, TableRow, TableCell, number] {\n if (range == null) return [null, null, null, -1];\n const [cell, offset] = this.quill.getLine(range.index);\n if (cell == null || cell.statics.blotName !== TableCell.blotName) {\n return [null, null, null, -1];\n }\n const row = cell.parent;\n const table = row.parent.parent;\n // @ts-expect-error\n return [table, row, cell, offset];\n }\n\n insertColumn(offset: number) {\n const range = this.quill.getSelection();\n if (!range) return;\n const [table, row, cell] = this.getTable(range);\n if (cell == null) return;\n const column = cell.cellOffset();\n table.insertColumn(column + offset);\n this.quill.update(Quill.sources.USER);\n let shift = row.rowOffset();\n if (offset === 0) {\n shift += 1;\n }\n this.quill.setSelection(\n range.index + shift,\n range.length,\n Quill.sources.SILENT,\n );\n }\n\n insertColumnLeft() {\n this.insertColumn(0);\n }\n\n insertColumnRight() {\n this.insertColumn(1);\n }\n\n insertRow(offset: number) {\n const range = this.quill.getSelection();\n if (!range) return;\n const [table, row, cell] = this.getTable(range);\n if (cell == null) return;\n const index = row.rowOffset();\n table.insertRow(index + offset);\n this.quill.update(Quill.sources.USER);\n if (offset > 0) {\n this.quill.setSelection(range, Quill.sources.SILENT);\n } else {\n this.quill.setSelection(\n range.index + row.children.length,\n range.length,\n Quill.sources.SILENT,\n );\n }\n }\n\n insertRowAbove() {\n this.insertRow(0);\n }\n\n insertRowBelow() {\n this.insertRow(1);\n }\n\n insertTable(rows: number, columns: number) {\n const range = this.quill.getSelection();\n if (range == null) return;\n const delta = new Array(rows).fill(0).reduce((memo) => {\n const text = new Array(columns).fill('\\n').join('');\n return memo.insert(text, { table: tableId() });\n }, new Delta().retain(range.index));\n this.quill.updateContents(delta, Quill.sources.USER);\n this.quill.setSelection(range.index, Quill.sources.SILENT);\n this.balanceTables();\n }\n\n listenBalanceCells() {\n this.quill.on(\n Quill.events.SCROLL_OPTIMIZE,\n (mutations: MutationRecord[]) => {\n mutations.some((mutation) => {\n if (\n ['TD', 'TR', 'TBODY', 'TABLE'].includes(\n (mutation.target as HTMLElement).tagName,\n )\n ) {\n this.quill.once(Quill.events.TEXT_CHANGE, (delta, old, source) => {\n if (source !== Quill.sources.USER) return;\n this.balanceTables();\n });\n return true;\n }\n return false;\n });\n },\n );\n }\n}\n\nexport default Table;\n", "import Delta from 'quill-delta';\nimport { EmbedBlot, Scope } from 'parchment';\nimport Quill from '../core/quill.js';\nimport logger from '../core/logger.js';\nimport Module from '../core/module.js';\nimport type { Range } from '../core/selection.js';\n\nconst debug = logger('quill:toolbar');\n\ntype Handler = (this: Toolbar, value: any) => void;\n\nexport type ToolbarConfig = Array<\n string[] | Array>\n>;\nexport interface ToolbarProps {\n container?: HTMLElement | ToolbarConfig | null;\n handlers?: Record;\n option?: number;\n module?: boolean;\n theme?: boolean;\n}\n\nclass Toolbar extends Module {\n static DEFAULTS: ToolbarProps;\n\n container?: HTMLElement | null;\n controls: [string, HTMLElement][];\n handlers: Record;\n\n constructor(quill: Quill, options: Partial) {\n super(quill, options);\n if (Array.isArray(this.options.container)) {\n const container = document.createElement('div');\n container.setAttribute('role', 'toolbar');\n addControls(container, this.options.container);\n quill.container?.parentNode?.insertBefore(container, quill.container);\n this.container = container;\n } else if (typeof this.options.container === 'string') {\n this.container = document.querySelector(this.options.container);\n } else {\n this.container = this.options.container;\n }\n if (!(this.container instanceof HTMLElement)) {\n debug.error('Container required for toolbar', this.options);\n return;\n }\n this.container.classList.add('ql-toolbar');\n this.controls = [];\n this.handlers = {};\n if (this.options.handlers) {\n Object.keys(this.options.handlers).forEach((format) => {\n const handler = this.options.handlers?.[format];\n if (handler) {\n this.addHandler(format, handler);\n }\n });\n }\n Array.from(this.container.querySelectorAll('button, select')).forEach(\n (input) => {\n // @ts-expect-error\n this.attach(input);\n },\n );\n this.quill.on(Quill.events.EDITOR_CHANGE, () => {\n const [range] = this.quill.selection.getRange(); // quill.getSelection triggers update\n this.update(range);\n });\n }\n\n addHandler(format: string, handler: Handler) {\n this.handlers[format] = handler;\n }\n\n attach(input: HTMLElement) {\n let format = Array.from(input.classList).find((className) => {\n return className.indexOf('ql-') === 0;\n });\n if (!format) return;\n format = format.slice('ql-'.length);\n if (input.tagName === 'BUTTON') {\n input.setAttribute('type', 'button');\n }\n if (\n this.handlers[format] == null &&\n this.quill.scroll.query(format) == null\n ) {\n debug.warn('ignoring attaching to nonexistent format', format, input);\n return;\n }\n const eventName = input.tagName === 'SELECT' ? 'change' : 'click';\n input.addEventListener(eventName, (e) => {\n let value;\n if (input.tagName === 'SELECT') {\n // @ts-expect-error\n if (input.selectedIndex < 0) return;\n // @ts-expect-error\n const selected = input.options[input.selectedIndex];\n if (selected.hasAttribute('selected')) {\n value = false;\n } else {\n value = selected.value || false;\n }\n } else {\n if (input.classList.contains('ql-active')) {\n value = false;\n } else {\n // @ts-expect-error\n value = input.value || !input.hasAttribute('value');\n }\n e.preventDefault();\n }\n this.quill.focus();\n const [range] = this.quill.selection.getRange();\n if (this.handlers[format] != null) {\n this.handlers[format].call(this, value);\n } else if (\n // @ts-expect-error\n this.quill.scroll.query(format).prototype instanceof EmbedBlot\n ) {\n value = prompt(`Enter ${format}`); // eslint-disable-line no-alert\n if (!value) return;\n this.quill.updateContents(\n new Delta()\n // @ts-expect-error Fix me later\n .retain(range.index)\n // @ts-expect-error Fix me later\n .delete(range.length)\n .insert({ [format]: value }),\n Quill.sources.USER,\n );\n } else {\n this.quill.format(format, value, Quill.sources.USER);\n }\n this.update(range);\n });\n this.controls.push([format, input]);\n }\n\n update(range: Range | null) {\n const formats = range == null ? {} : this.quill.getFormat(range);\n this.controls.forEach((pair) => {\n const [format, input] = pair;\n if (input.tagName === 'SELECT') {\n let option: HTMLOptionElement | null = null;\n if (range == null) {\n option = null;\n } else if (formats[format] == null) {\n option = input.querySelector('option[selected]');\n } else if (!Array.isArray(formats[format])) {\n let value = formats[format];\n if (typeof value === 'string') {\n value = value.replace(/\"/g, '\\\\\"');\n }\n option = input.querySelector(`option[value=\"${value}\"]`);\n }\n if (option == null) {\n // @ts-expect-error TODO fix me later\n input.value = ''; // TODO make configurable?\n // @ts-expect-error TODO fix me later\n input.selectedIndex = -1;\n } else {\n option.selected = true;\n }\n } else if (range == null) {\n input.classList.remove('ql-active');\n input.setAttribute('aria-pressed', 'false');\n } else if (input.hasAttribute('value')) {\n // both being null should match (default values)\n // '1' should match with 1 (headers)\n const value = formats[format] as boolean | number | string | object;\n const isActive =\n value === input.getAttribute('value') ||\n (value != null && value.toString() === input.getAttribute('value')) ||\n (value == null && !input.getAttribute('value'));\n input.classList.toggle('ql-active', isActive);\n input.setAttribute('aria-pressed', isActive.toString());\n } else {\n const isActive = formats[format] != null;\n input.classList.toggle('ql-active', isActive);\n input.setAttribute('aria-pressed', isActive.toString());\n }\n });\n }\n}\nToolbar.DEFAULTS = {};\n\nfunction addButton(container: HTMLElement, format: string, value?: string) {\n const input = document.createElement('button');\n input.setAttribute('type', 'button');\n input.classList.add(`ql-${format}`);\n input.setAttribute('aria-pressed', 'false');\n if (value != null) {\n input.value = value;\n input.setAttribute('aria-label', `${format}: ${value}`);\n } else {\n input.setAttribute('aria-label', format);\n }\n container.appendChild(input);\n}\n\nfunction addControls(\n container: HTMLElement,\n groups:\n | (string | Record)[][]\n | (string | Record)[],\n) {\n if (!Array.isArray(groups[0])) {\n // @ts-expect-error\n groups = [groups];\n }\n groups.forEach((controls: any) => {\n const group = document.createElement('span');\n group.classList.add('ql-formats');\n controls.forEach((control: any) => {\n if (typeof control === 'string') {\n addButton(group, control);\n } else {\n const format = Object.keys(control)[0];\n const value = control[format];\n if (Array.isArray(value)) {\n addSelect(group, format, value);\n } else {\n addButton(group, format, value);\n }\n }\n });\n container.appendChild(group);\n });\n}\n\nfunction addSelect(\n container: HTMLElement,\n format: string,\n values: Array,\n) {\n const input = document.createElement('select');\n input.classList.add(`ql-${format}`);\n values.forEach((value) => {\n const option = document.createElement('option');\n if (value !== false) {\n option.setAttribute('value', String(value));\n } else {\n option.setAttribute('selected', 'selected');\n }\n input.appendChild(option);\n });\n container.appendChild(input);\n}\n\nToolbar.DEFAULTS = {\n container: null,\n handlers: {\n clean() {\n const range = this.quill.getSelection();\n if (range == null) return;\n if (range.length === 0) {\n const formats = this.quill.getFormat();\n Object.keys(formats).forEach((name) => {\n // Clean functionality in existing apps only clean inline formats\n if (this.quill.scroll.query(name, Scope.INLINE) != null) {\n this.quill.format(name, false, Quill.sources.USER);\n }\n });\n } else {\n this.quill.removeFormat(range.index, range.length, Quill.sources.USER);\n }\n },\n direction(value) {\n const { align } = this.quill.getFormat();\n if (value === 'rtl' && align == null) {\n this.quill.format('align', 'right', Quill.sources.USER);\n } else if (!value && align === 'right') {\n this.quill.format('align', false, Quill.sources.USER);\n }\n this.quill.format('direction', value, Quill.sources.USER);\n },\n indent(value) {\n const range = this.quill.getSelection();\n // @ts-expect-error\n const formats = this.quill.getFormat(range);\n // @ts-expect-error\n const indent = parseInt(formats.indent || 0, 10);\n if (value === '+1' || value === '-1') {\n let modifier = value === '+1' ? 1 : -1;\n if (formats.direction === 'rtl') modifier *= -1;\n this.quill.format('indent', indent + modifier, Quill.sources.USER);\n }\n },\n link(value) {\n if (value === true) {\n value = prompt('Enter link URL:'); // eslint-disable-line no-alert\n }\n this.quill.format('link', value, Quill.sources.USER);\n },\n list(value) {\n const range = this.quill.getSelection();\n // @ts-expect-error\n const formats = this.quill.getFormat(range);\n if (value === 'check') {\n if (formats.list === 'checked' || formats.list === 'unchecked') {\n this.quill.format('list', false, Quill.sources.USER);\n } else {\n this.quill.format('list', 'unchecked', Quill.sources.USER);\n }\n } else {\n this.quill.format('list', value, Quill.sources.USER);\n }\n },\n },\n};\n\nexport { Toolbar as default, addControls };\n", "import alignLeftIcon from '../assets/icons/align-left.svg';\nimport alignCenterIcon from '../assets/icons/align-center.svg';\nimport alignRightIcon from '../assets/icons/align-right.svg';\nimport alignJustifyIcon from '../assets/icons/align-justify.svg';\nimport backgroundIcon from '../assets/icons/background.svg';\nimport blockquoteIcon from '../assets/icons/blockquote.svg';\nimport boldIcon from '../assets/icons/bold.svg';\nimport cleanIcon from '../assets/icons/clean.svg';\nimport codeIcon from '../assets/icons/code.svg';\nimport colorIcon from '../assets/icons/color.svg';\nimport directionLeftToRightIcon from '../assets/icons/direction-ltr.svg';\nimport directionRightToLeftIcon from '../assets/icons/direction-rtl.svg';\nimport formulaIcon from '../assets/icons/formula.svg';\nimport headerIcon from '../assets/icons/header.svg';\nimport header2Icon from '../assets/icons/header-2.svg';\nimport header3Icon from '../assets/icons/header-3.svg';\nimport header4Icon from '../assets/icons/header-4.svg';\nimport header5Icon from '../assets/icons/header-5.svg';\nimport header6Icon from '../assets/icons/header-6.svg';\nimport italicIcon from '../assets/icons/italic.svg';\nimport imageIcon from '../assets/icons/image.svg';\nimport indentIcon from '../assets/icons/indent.svg';\nimport outdentIcon from '../assets/icons/outdent.svg';\nimport linkIcon from '../assets/icons/link.svg';\nimport listBulletIcon from '../assets/icons/list-bullet.svg';\nimport listCheckIcon from '../assets/icons/list-check.svg';\nimport listOrderedIcon from '../assets/icons/list-ordered.svg';\nimport subscriptIcon from '../assets/icons/subscript.svg';\nimport superscriptIcon from '../assets/icons/superscript.svg';\nimport strikeIcon from '../assets/icons/strike.svg';\nimport tableIcon from '../assets/icons/table.svg';\nimport underlineIcon from '../assets/icons/underline.svg';\nimport videoIcon from '../assets/icons/video.svg';\n\nexport default {\n align: {\n '': alignLeftIcon,\n center: alignCenterIcon,\n right: alignRightIcon,\n justify: alignJustifyIcon,\n },\n background: backgroundIcon,\n blockquote: blockquoteIcon,\n bold: boldIcon,\n clean: cleanIcon,\n code: codeIcon,\n 'code-block': codeIcon,\n color: colorIcon,\n direction: {\n '': directionLeftToRightIcon,\n rtl: directionRightToLeftIcon,\n },\n formula: formulaIcon,\n header: {\n '1': headerIcon,\n '2': header2Icon,\n '3': header3Icon,\n '4': header4Icon,\n '5': header5Icon,\n '6': header6Icon,\n },\n italic: italicIcon,\n image: imageIcon,\n indent: {\n '+1': indentIcon,\n '-1': outdentIcon,\n },\n link: linkIcon,\n list: {\n bullet: listBulletIcon,\n check: listCheckIcon,\n ordered: listOrderedIcon,\n },\n script: {\n sub: subscriptIcon,\n super: superscriptIcon,\n },\n strike: strikeIcon,\n table: tableIcon,\n underline: underlineIcon,\n video: videoIcon,\n};\n", "import DropdownIcon from '../assets/icons/dropdown.svg';\n\nlet optionsCounter = 0;\n\nfunction toggleAriaAttribute(element: HTMLElement, attribute: string) {\n element.setAttribute(\n attribute,\n `${!(element.getAttribute(attribute) === 'true')}`,\n );\n}\n\nclass Picker {\n select: HTMLSelectElement;\n container: HTMLElement;\n label: HTMLElement;\n\n constructor(select: HTMLSelectElement) {\n this.select = select;\n this.container = document.createElement('span');\n this.buildPicker();\n this.select.style.display = 'none';\n // @ts-expect-error Fix me later\n this.select.parentNode.insertBefore(this.container, this.select);\n\n this.label.addEventListener('mousedown', () => {\n this.togglePicker();\n });\n this.label.addEventListener('keydown', (event) => {\n switch (event.key) {\n case 'Enter':\n this.togglePicker();\n break;\n case 'Escape':\n this.escape();\n event.preventDefault();\n break;\n default:\n }\n });\n this.select.addEventListener('change', this.update.bind(this));\n }\n\n togglePicker() {\n this.container.classList.toggle('ql-expanded');\n // Toggle aria-expanded and aria-hidden to make the picker accessible\n toggleAriaAttribute(this.label, 'aria-expanded');\n // @ts-expect-error\n toggleAriaAttribute(this.options, 'aria-hidden');\n }\n\n buildItem(option: HTMLOptionElement) {\n const item = document.createElement('span');\n // @ts-expect-error\n item.tabIndex = '0';\n item.setAttribute('role', 'button');\n item.classList.add('ql-picker-item');\n const value = option.getAttribute('value');\n if (value) {\n item.setAttribute('data-value', value);\n }\n if (option.textContent) {\n item.setAttribute('data-label', option.textContent);\n }\n item.addEventListener('click', () => {\n this.selectItem(item, true);\n });\n item.addEventListener('keydown', (event) => {\n switch (event.key) {\n case 'Enter':\n this.selectItem(item, true);\n event.preventDefault();\n break;\n case 'Escape':\n this.escape();\n event.preventDefault();\n break;\n default:\n }\n });\n\n return item;\n }\n\n buildLabel() {\n const label = document.createElement('span');\n label.classList.add('ql-picker-label');\n label.innerHTML = DropdownIcon;\n // @ts-expect-error\n label.tabIndex = '0';\n label.setAttribute('role', 'button');\n label.setAttribute('aria-expanded', 'false');\n this.container.appendChild(label);\n return label;\n }\n\n buildOptions() {\n const options = document.createElement('span');\n options.classList.add('ql-picker-options');\n\n // Don't want screen readers to read this until options are visible\n options.setAttribute('aria-hidden', 'true');\n // @ts-expect-error\n options.tabIndex = '-1';\n\n // Need a unique id for aria-controls\n options.id = `ql-picker-options-${optionsCounter}`;\n optionsCounter += 1;\n this.label.setAttribute('aria-controls', options.id);\n\n // @ts-expect-error\n this.options = options;\n\n Array.from(this.select.options).forEach((option) => {\n const item = this.buildItem(option);\n options.appendChild(item);\n if (option.selected === true) {\n this.selectItem(item);\n }\n });\n this.container.appendChild(options);\n }\n\n buildPicker() {\n Array.from(this.select.attributes).forEach((item) => {\n this.container.setAttribute(item.name, item.value);\n });\n this.container.classList.add('ql-picker');\n this.label = this.buildLabel();\n this.buildOptions();\n }\n\n escape() {\n // Close menu and return focus to trigger label\n this.close();\n // Need setTimeout for accessibility to ensure that the browser executes\n // focus on the next process thread and after any DOM content changes\n setTimeout(() => this.label.focus(), 1);\n }\n\n close() {\n this.container.classList.remove('ql-expanded');\n this.label.setAttribute('aria-expanded', 'false');\n // @ts-expect-error\n this.options.setAttribute('aria-hidden', 'true');\n }\n\n selectItem(item: HTMLElement | null, trigger = false) {\n const selected = this.container.querySelector('.ql-selected');\n if (item === selected) return;\n if (selected != null) {\n selected.classList.remove('ql-selected');\n }\n if (item == null) return;\n item.classList.add('ql-selected');\n // @ts-expect-error Fix me later\n this.select.selectedIndex = Array.from(item.parentNode.children).indexOf(\n item,\n );\n if (item.hasAttribute('data-value')) {\n // @ts-expect-error Fix me later\n this.label.setAttribute('data-value', item.getAttribute('data-value'));\n } else {\n this.label.removeAttribute('data-value');\n }\n if (item.hasAttribute('data-label')) {\n // @ts-expect-error Fix me later\n this.label.setAttribute('data-label', item.getAttribute('data-label'));\n } else {\n this.label.removeAttribute('data-label');\n }\n if (trigger) {\n this.select.dispatchEvent(new Event('change'));\n this.close();\n }\n }\n\n update() {\n let option;\n if (this.select.selectedIndex > -1) {\n const item =\n // @ts-expect-error Fix me later\n this.container.querySelector('.ql-picker-options').children[\n this.select.selectedIndex\n ];\n option = this.select.options[this.select.selectedIndex];\n // @ts-expect-error\n this.selectItem(item);\n } else {\n this.selectItem(null);\n }\n const isActive =\n option != null &&\n option !== this.select.querySelector('option[selected]');\n this.label.classList.toggle('ql-active', isActive);\n }\n}\n\nexport default Picker;\n", "import Picker from './picker.js';\n\nclass ColorPicker extends Picker {\n constructor(select: HTMLSelectElement, label: string) {\n super(select);\n this.label.innerHTML = label;\n this.container.classList.add('ql-color-picker');\n Array.from(this.container.querySelectorAll('.ql-picker-item'))\n .slice(0, 7)\n .forEach((item) => {\n item.classList.add('ql-primary');\n });\n }\n\n buildItem(option: HTMLOptionElement) {\n const item = super.buildItem(option);\n item.style.backgroundColor = option.getAttribute('value') || '';\n return item;\n }\n\n selectItem(item: HTMLElement | null, trigger?: boolean) {\n super.selectItem(item, trigger);\n const colorLabel = this.label.querySelector('.ql-color-label');\n const value = item ? item.getAttribute('data-value') || '' : '';\n if (colorLabel) {\n if (colorLabel.tagName === 'line') {\n colorLabel.style.stroke = value;\n } else {\n colorLabel.style.fill = value;\n }\n }\n }\n}\n\nexport default ColorPicker;\n", "import Picker from './picker.js';\n\nclass IconPicker extends Picker {\n defaultItem: HTMLElement | null;\n\n constructor(select: HTMLSelectElement, icons: Record) {\n super(select);\n this.container.classList.add('ql-icon-picker');\n Array.from(this.container.querySelectorAll('.ql-picker-item')).forEach(\n (item) => {\n item.innerHTML = icons[item.getAttribute('data-value') || ''];\n },\n );\n this.defaultItem = this.container.querySelector('.ql-selected');\n this.selectItem(this.defaultItem);\n }\n\n selectItem(target: HTMLElement | null, trigger?: boolean) {\n super.selectItem(target, trigger);\n const item = target || this.defaultItem;\n if (item != null) {\n if (this.label.innerHTML === item.innerHTML) return;\n this.label.innerHTML = item.innerHTML;\n }\n }\n}\n\nexport default IconPicker;\n", "import type Quill from '../core.js';\nimport type { Bounds } from '../core/selection.js';\n\nconst isScrollable = (el: Element) => {\n const { overflowY } = getComputedStyle(el, null);\n return overflowY !== 'visible' && overflowY !== 'clip';\n};\n\nclass Tooltip {\n quill: Quill;\n boundsContainer: HTMLElement;\n root: HTMLDivElement;\n\n constructor(quill: Quill, boundsContainer?: HTMLElement) {\n this.quill = quill;\n this.boundsContainer = boundsContainer || document.body;\n this.root = quill.addContainer('ql-tooltip');\n // @ts-expect-error\n this.root.innerHTML = this.constructor.TEMPLATE;\n if (isScrollable(this.quill.root)) {\n this.quill.root.addEventListener('scroll', () => {\n this.root.style.marginTop = `${-1 * this.quill.root.scrollTop}px`;\n });\n }\n this.hide();\n }\n\n hide() {\n this.root.classList.add('ql-hidden');\n }\n\n position(reference: Bounds) {\n const left =\n reference.left + reference.width / 2 - this.root.offsetWidth / 2;\n // root.scrollTop should be 0 if scrollContainer !== root\n const top = reference.bottom + this.quill.root.scrollTop;\n this.root.style.left = `${left}px`;\n this.root.style.top = `${top}px`;\n this.root.classList.remove('ql-flip');\n const containerBounds = this.boundsContainer.getBoundingClientRect();\n const rootBounds = this.root.getBoundingClientRect();\n let shift = 0;\n if (rootBounds.right > containerBounds.right) {\n shift = containerBounds.right - rootBounds.right;\n this.root.style.left = `${left + shift}px`;\n }\n if (rootBounds.left < containerBounds.left) {\n shift = containerBounds.left - rootBounds.left;\n this.root.style.left = `${left + shift}px`;\n }\n if (rootBounds.bottom > containerBounds.bottom) {\n const height = rootBounds.bottom - rootBounds.top;\n const verticalShift = reference.bottom - reference.top + height;\n this.root.style.top = `${top - verticalShift}px`;\n this.root.classList.add('ql-flip');\n }\n return shift;\n }\n\n show() {\n this.root.classList.remove('ql-editing');\n this.root.classList.remove('ql-hidden');\n }\n}\n\nexport default Tooltip;\n", "import { merge } from 'lodash-es';\nimport type Quill from '../core/quill.js';\nimport Emitter from '../core/emitter.js';\nimport Theme from '../core/theme.js';\nimport type { ThemeOptions } from '../core/theme.js';\nimport ColorPicker from '../ui/color-picker.js';\nimport IconPicker from '../ui/icon-picker.js';\nimport Picker from '../ui/picker.js';\nimport Tooltip from '../ui/tooltip.js';\nimport type { Range } from '../core/selection.js';\nimport type Clipboard from '../modules/clipboard.js';\nimport type History from '../modules/history.js';\nimport type Keyboard from '../modules/keyboard.js';\nimport type Uploader from '../modules/uploader.js';\nimport type Selection from '../core/selection.js';\n\nconst ALIGNS = [false, 'center', 'right', 'justify'];\n\nconst COLORS = [\n '#000000',\n '#e60000',\n '#ff9900',\n '#ffff00',\n '#008a00',\n '#0066cc',\n '#9933ff',\n '#ffffff',\n '#facccc',\n '#ffebcc',\n '#ffffcc',\n '#cce8cc',\n '#cce0f5',\n '#ebd6ff',\n '#bbbbbb',\n '#f06666',\n '#ffc266',\n '#ffff66',\n '#66b966',\n '#66a3e0',\n '#c285ff',\n '#888888',\n '#a10000',\n '#b26b00',\n '#b2b200',\n '#006100',\n '#0047b2',\n '#6b24b2',\n '#444444',\n '#5c0000',\n '#663d00',\n '#666600',\n '#003700',\n '#002966',\n '#3d1466',\n];\n\nconst FONTS = [false, 'serif', 'monospace'];\n\nconst HEADERS = ['1', '2', '3', false];\n\nconst SIZES = ['small', false, 'large', 'huge'];\n\nclass BaseTheme extends Theme {\n pickers: Picker[];\n tooltip?: Tooltip;\n\n constructor(quill: Quill, options: ThemeOptions) {\n super(quill, options);\n const listener = (e: MouseEvent) => {\n if (!document.body.contains(quill.root)) {\n document.body.removeEventListener('click', listener);\n return;\n }\n if (\n this.tooltip != null &&\n // @ts-expect-error\n !this.tooltip.root.contains(e.target) &&\n // @ts-expect-error\n document.activeElement !== this.tooltip.textbox &&\n !this.quill.hasFocus()\n ) {\n this.tooltip.hide();\n }\n if (this.pickers != null) {\n this.pickers.forEach((picker) => {\n // @ts-expect-error\n if (!picker.container.contains(e.target)) {\n picker.close();\n }\n });\n }\n };\n quill.emitter.listenDOM('click', document.body, listener);\n }\n\n addModule(name: 'clipboard'): Clipboard;\n addModule(name: 'keyboard'): Keyboard;\n addModule(name: 'uploader'): Uploader;\n addModule(name: 'history'): History;\n addModule(name: 'selection'): Selection;\n addModule(name: string): unknown;\n addModule(name: string) {\n const module = super.addModule(name);\n if (name === 'toolbar') {\n // @ts-expect-error\n this.extendToolbar(module);\n }\n return module;\n }\n\n buildButtons(\n buttons: NodeListOf,\n icons: Record | string>,\n ) {\n Array.from(buttons).forEach((button) => {\n const className = button.getAttribute('class') || '';\n className.split(/\\s+/).forEach((name) => {\n if (!name.startsWith('ql-')) return;\n name = name.slice('ql-'.length);\n if (icons[name] == null) return;\n if (name === 'direction') {\n // @ts-expect-error\n button.innerHTML = icons[name][''] + icons[name].rtl;\n } else if (typeof icons[name] === 'string') {\n // @ts-expect-error\n button.innerHTML = icons[name];\n } else {\n // @ts-expect-error\n const value = button.value || '';\n // @ts-expect-error\n if (value != null && icons[name][value]) {\n // @ts-expect-error\n button.innerHTML = icons[name][value];\n }\n }\n });\n });\n }\n\n buildPickers(\n selects: NodeListOf,\n icons: Record>,\n ) {\n this.pickers = Array.from(selects).map((select) => {\n if (select.classList.contains('ql-align')) {\n if (select.querySelector('option') == null) {\n fillSelect(select, ALIGNS);\n }\n if (typeof icons.align === 'object') {\n return new IconPicker(select, icons.align);\n }\n }\n if (\n select.classList.contains('ql-background') ||\n select.classList.contains('ql-color')\n ) {\n const format = select.classList.contains('ql-background')\n ? 'background'\n : 'color';\n if (select.querySelector('option') == null) {\n fillSelect(\n select,\n COLORS,\n format === 'background' ? '#ffffff' : '#000000',\n );\n }\n return new ColorPicker(select, icons[format] as string);\n }\n if (select.querySelector('option') == null) {\n if (select.classList.contains('ql-font')) {\n fillSelect(select, FONTS);\n } else if (select.classList.contains('ql-header')) {\n fillSelect(select, HEADERS);\n } else if (select.classList.contains('ql-size')) {\n fillSelect(select, SIZES);\n }\n }\n return new Picker(select);\n });\n const update = () => {\n this.pickers.forEach((picker) => {\n picker.update();\n });\n };\n this.quill.on(Emitter.events.EDITOR_CHANGE, update);\n }\n}\nBaseTheme.DEFAULTS = merge({}, Theme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n formula() {\n this.quill.theme.tooltip.edit('formula');\n },\n image() {\n let fileInput = this.container.querySelector(\n 'input.ql-image[type=file]',\n );\n if (fileInput == null) {\n fileInput = document.createElement('input');\n fileInput.setAttribute('type', 'file');\n fileInput.setAttribute(\n 'accept',\n this.quill.uploader.options.mimetypes.join(', '),\n );\n fileInput.classList.add('ql-image');\n fileInput.addEventListener('change', () => {\n const range = this.quill.getSelection(true);\n this.quill.uploader.upload(range, fileInput.files);\n fileInput.value = '';\n });\n this.container.appendChild(fileInput);\n }\n fileInput.click();\n },\n video() {\n this.quill.theme.tooltip.edit('video');\n },\n },\n },\n },\n});\n\nclass BaseTooltip extends Tooltip {\n textbox: HTMLInputElement | null;\n linkRange?: Range;\n\n constructor(quill: Quill, boundsContainer?: HTMLElement) {\n super(quill, boundsContainer);\n this.textbox = this.root.querySelector('input[type=\"text\"]');\n this.listen();\n }\n\n listen() {\n // @ts-expect-error Fix me later\n this.textbox.addEventListener('keydown', (event) => {\n if (event.key === 'Enter') {\n this.save();\n event.preventDefault();\n } else if (event.key === 'Escape') {\n this.cancel();\n event.preventDefault();\n }\n });\n }\n\n cancel() {\n this.hide();\n this.restoreFocus();\n }\n\n edit(mode = 'link', preview: string | null = null) {\n this.root.classList.remove('ql-hidden');\n this.root.classList.add('ql-editing');\n if (this.textbox == null) return;\n\n if (preview != null) {\n this.textbox.value = preview;\n } else if (mode !== this.root.getAttribute('data-mode')) {\n this.textbox.value = '';\n }\n const bounds = this.quill.getBounds(this.quill.selection.savedRange);\n if (bounds != null) {\n this.position(bounds);\n }\n this.textbox.select();\n this.textbox.setAttribute(\n 'placeholder',\n this.textbox.getAttribute(`data-${mode}`) || '',\n );\n this.root.setAttribute('data-mode', mode);\n }\n\n restoreFocus() {\n this.quill.focus({ preventScroll: true });\n }\n\n save() {\n // @ts-expect-error Fix me later\n let { value } = this.textbox;\n switch (this.root.getAttribute('data-mode')) {\n case 'link': {\n const { scrollTop } = this.quill.root;\n if (this.linkRange) {\n this.quill.formatText(\n this.linkRange,\n 'link',\n value,\n Emitter.sources.USER,\n );\n delete this.linkRange;\n } else {\n this.restoreFocus();\n this.quill.format('link', value, Emitter.sources.USER);\n }\n this.quill.root.scrollTop = scrollTop;\n break;\n }\n case 'video': {\n value = extractVideoUrl(value);\n } // eslint-disable-next-line no-fallthrough\n case 'formula': {\n if (!value) break;\n const range = this.quill.getSelection(true);\n if (range != null) {\n const index = range.index + range.length;\n this.quill.insertEmbed(\n index,\n // @ts-expect-error Fix me later\n this.root.getAttribute('data-mode'),\n value,\n Emitter.sources.USER,\n );\n if (this.root.getAttribute('data-mode') === 'formula') {\n this.quill.insertText(index + 1, ' ', Emitter.sources.USER);\n }\n this.quill.setSelection(index + 2, Emitter.sources.USER);\n }\n break;\n }\n default:\n }\n // @ts-expect-error Fix me later\n this.textbox.value = '';\n this.hide();\n }\n}\n\nfunction extractVideoUrl(url: string) {\n let match =\n url.match(\n /^(?:(https?):\\/\\/)?(?:(?:www|m)\\.)?youtube\\.com\\/watch.*v=([a-zA-Z0-9_-]+)/,\n ) ||\n url.match(/^(?:(https?):\\/\\/)?(?:(?:www|m)\\.)?youtu\\.be\\/([a-zA-Z0-9_-]+)/);\n if (match) {\n return `${match[1] || 'https'}://www.youtube.com/embed/${\n match[2]\n }?showinfo=0`;\n }\n // eslint-disable-next-line no-cond-assign\n if ((match = url.match(/^(?:(https?):\\/\\/)?(?:www\\.)?vimeo\\.com\\/(\\d+)/))) {\n return `${match[1] || 'https'}://player.vimeo.com/video/${match[2]}/`;\n }\n return url;\n}\n\nfunction fillSelect(\n select: HTMLSelectElement,\n values: Array,\n defaultValue: unknown = false,\n) {\n values.forEach((value) => {\n const option = document.createElement('option');\n if (value === defaultValue) {\n option.setAttribute('selected', 'selected');\n } else {\n option.setAttribute('value', String(value));\n }\n select.appendChild(option);\n });\n}\n\nexport { BaseTooltip, BaseTheme as default };\n", "import { merge } from 'lodash-es';\nimport Emitter from '../core/emitter.js';\nimport BaseTheme, { BaseTooltip } from './base.js';\nimport { Range } from '../core/selection.js';\nimport type { Bounds } from '../core/selection.js';\nimport icons from '../ui/icons.js';\nimport Quill from '../core/quill.js';\nimport type { ThemeOptions } from '../core/theme.js';\nimport type Toolbar from '../modules/toolbar.js';\nimport type { ToolbarConfig } from '../modules/toolbar.js';\n\nconst TOOLBAR_CONFIG: ToolbarConfig = [\n ['bold', 'italic', 'link'],\n [{ header: 1 }, { header: 2 }, 'blockquote'],\n];\n\nclass BubbleTooltip extends BaseTooltip {\n static TEMPLATE = [\n '',\n '
    ',\n '',\n '',\n '
    ',\n ].join('');\n\n constructor(quill: Quill, bounds?: HTMLElement) {\n super(quill, bounds);\n this.quill.on(\n Emitter.events.EDITOR_CHANGE,\n (type, range, oldRange, source) => {\n if (type !== Emitter.events.SELECTION_CHANGE) return;\n if (\n range != null &&\n range.length > 0 &&\n source === Emitter.sources.USER\n ) {\n this.show();\n // Lock our width so we will expand beyond our offsetParent boundaries\n this.root.style.left = '0px';\n this.root.style.width = '';\n this.root.style.width = `${this.root.offsetWidth}px`;\n const lines = this.quill.getLines(range.index, range.length);\n if (lines.length === 1) {\n const bounds = this.quill.getBounds(range);\n if (bounds != null) {\n this.position(bounds);\n }\n } else {\n const lastLine = lines[lines.length - 1];\n const index = this.quill.getIndex(lastLine);\n const length = Math.min(\n lastLine.length() - 1,\n range.index + range.length - index,\n );\n const indexBounds = this.quill.getBounds(new Range(index, length));\n if (indexBounds != null) {\n this.position(indexBounds);\n }\n }\n } else if (\n document.activeElement !== this.textbox &&\n this.quill.hasFocus()\n ) {\n this.hide();\n }\n },\n );\n }\n\n listen() {\n super.listen();\n // @ts-expect-error Fix me later\n this.root.querySelector('.ql-close').addEventListener('click', () => {\n this.root.classList.remove('ql-editing');\n });\n this.quill.on(Emitter.events.SCROLL_OPTIMIZE, () => {\n // Let selection be restored by toolbar handlers before repositioning\n setTimeout(() => {\n if (this.root.classList.contains('ql-hidden')) return;\n const range = this.quill.getSelection();\n if (range != null) {\n const bounds = this.quill.getBounds(range);\n if (bounds != null) {\n this.position(bounds);\n }\n }\n }, 1);\n });\n }\n\n cancel() {\n this.show();\n }\n\n position(reference: Bounds) {\n const shift = super.position(reference);\n const arrow = this.root.querySelector('.ql-tooltip-arrow');\n // @ts-expect-error\n arrow.style.marginLeft = '';\n if (shift !== 0) {\n // @ts-expect-error\n arrow.style.marginLeft = `${-1 * shift - arrow.offsetWidth / 2}px`;\n }\n return shift;\n }\n}\n\nclass BubbleTheme extends BaseTheme {\n tooltip: BubbleTooltip;\n\n constructor(quill: Quill, options: ThemeOptions) {\n if (\n options.modules.toolbar != null &&\n options.modules.toolbar.container == null\n ) {\n options.modules.toolbar.container = TOOLBAR_CONFIG;\n }\n super(quill, options);\n this.quill.container.classList.add('ql-bubble');\n }\n\n extendToolbar(toolbar: Toolbar) {\n // @ts-expect-error\n this.tooltip = new BubbleTooltip(this.quill, this.options.bounds);\n if (toolbar.container != null) {\n this.tooltip.root.appendChild(toolbar.container);\n this.buildButtons(toolbar.container.querySelectorAll('button'), icons);\n this.buildPickers(toolbar.container.querySelectorAll('select'), icons);\n }\n }\n}\nBubbleTheme.DEFAULTS = merge({}, BaseTheme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n link(value: string) {\n if (!value) {\n this.quill.format('link', false, Quill.sources.USER);\n } else {\n // @ts-expect-error\n this.quill.theme.tooltip.edit();\n }\n },\n },\n },\n },\n} satisfies ThemeOptions);\n\nexport { BubbleTooltip, BubbleTheme as default };\n", "import { merge } from 'lodash-es';\nimport Emitter from '../core/emitter.js';\nimport BaseTheme, { BaseTooltip } from './base.js';\nimport LinkBlot from '../formats/link.js';\nimport { Range } from '../core/selection.js';\nimport icons from '../ui/icons.js';\nimport Quill from '../core/quill.js';\nimport type { Context } from '../modules/keyboard.js';\nimport type Toolbar from '../modules/toolbar.js';\nimport type { ToolbarConfig } from '../modules/toolbar.js';\nimport type { ThemeOptions } from '../core/theme.js';\n\nconst TOOLBAR_CONFIG: ToolbarConfig = [\n [{ header: ['1', '2', '3', false] }],\n ['bold', 'italic', 'underline', 'link'],\n [{ list: 'ordered' }, { list: 'bullet' }],\n ['clean'],\n];\n\nclass SnowTooltip extends BaseTooltip {\n static TEMPLATE = [\n '',\n '',\n '',\n '',\n ].join('');\n\n preview = this.root.querySelector('a.ql-preview');\n\n listen() {\n super.listen();\n // @ts-expect-error Fix me later\n this.root\n .querySelector('a.ql-action')\n .addEventListener('click', (event) => {\n if (this.root.classList.contains('ql-editing')) {\n this.save();\n } else {\n // @ts-expect-error Fix me later\n this.edit('link', this.preview.textContent);\n }\n event.preventDefault();\n });\n // @ts-expect-error Fix me later\n this.root\n .querySelector('a.ql-remove')\n .addEventListener('click', (event) => {\n if (this.linkRange != null) {\n const range = this.linkRange;\n this.restoreFocus();\n this.quill.formatText(range, 'link', false, Emitter.sources.USER);\n delete this.linkRange;\n }\n event.preventDefault();\n this.hide();\n });\n this.quill.on(\n Emitter.events.SELECTION_CHANGE,\n (range, oldRange, source) => {\n if (range == null) return;\n if (range.length === 0 && source === Emitter.sources.USER) {\n const [link, offset] = this.quill.scroll.descendant(\n LinkBlot,\n range.index,\n );\n if (link != null) {\n this.linkRange = new Range(range.index - offset, link.length());\n const preview = LinkBlot.formats(link.domNode);\n // @ts-expect-error Fix me later\n this.preview.textContent = preview;\n // @ts-expect-error Fix me later\n this.preview.setAttribute('href', preview);\n this.show();\n const bounds = this.quill.getBounds(this.linkRange);\n if (bounds != null) {\n this.position(bounds);\n }\n return;\n }\n } else {\n delete this.linkRange;\n }\n this.hide();\n },\n );\n }\n\n show() {\n super.show();\n this.root.removeAttribute('data-mode');\n }\n}\n\nclass SnowTheme extends BaseTheme {\n constructor(quill: Quill, options: ThemeOptions) {\n if (\n options.modules.toolbar != null &&\n options.modules.toolbar.container == null\n ) {\n options.modules.toolbar.container = TOOLBAR_CONFIG;\n }\n super(quill, options);\n this.quill.container.classList.add('ql-snow');\n }\n\n extendToolbar(toolbar: Toolbar) {\n if (toolbar.container != null) {\n toolbar.container.classList.add('ql-snow');\n this.buildButtons(toolbar.container.querySelectorAll('button'), icons);\n this.buildPickers(toolbar.container.querySelectorAll('select'), icons);\n // @ts-expect-error\n this.tooltip = new SnowTooltip(this.quill, this.options.bounds);\n if (toolbar.container.querySelector('.ql-link')) {\n this.quill.keyboard.addBinding(\n { key: 'k', shortKey: true },\n (_range: Range, context: Context) => {\n toolbar.handlers.link.call(toolbar, !context.format.link);\n },\n );\n }\n }\n }\n}\nSnowTheme.DEFAULTS = merge({}, BaseTheme.DEFAULTS, {\n modules: {\n toolbar: {\n handlers: {\n link(value: string) {\n if (value) {\n const range = this.quill.getSelection();\n if (range == null || range.length === 0) return;\n let preview = this.quill.getText(range);\n if (\n /^\\S+@\\S+\\.\\S+$/.test(preview) &&\n preview.indexOf('mailto:') !== 0\n ) {\n preview = `mailto:${preview}`;\n }\n // @ts-expect-error\n const { tooltip } = this.quill.theme;\n tooltip.edit('link', preview);\n } else {\n this.quill.format('link', false, Quill.sources.USER);\n }\n },\n },\n },\n },\n} satisfies ThemeOptions);\n\nexport default SnowTheme;\n", "import Quill, { Parchment, Range } from './core.js';\nimport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n} from './core.js';\n\nimport { AlignClass, AlignStyle } from './formats/align.js';\nimport {\n DirectionAttribute,\n DirectionClass,\n DirectionStyle,\n} from './formats/direction.js';\nimport Indent from './formats/indent.js';\n\nimport Blockquote from './formats/blockquote.js';\nimport Header from './formats/header.js';\nimport List from './formats/list.js';\n\nimport { BackgroundClass, BackgroundStyle } from './formats/background.js';\nimport { ColorClass, ColorStyle } from './formats/color.js';\nimport { FontClass, FontStyle } from './formats/font.js';\nimport { SizeClass, SizeStyle } from './formats/size.js';\n\nimport Bold from './formats/bold.js';\nimport Italic from './formats/italic.js';\nimport Link from './formats/link.js';\nimport Script from './formats/script.js';\nimport Strike from './formats/strike.js';\nimport Underline from './formats/underline.js';\n\nimport Formula from './formats/formula.js';\nimport Image from './formats/image.js';\nimport Video from './formats/video.js';\n\nimport CodeBlock, { Code as InlineCode } from './formats/code.js';\n\nimport Syntax from './modules/syntax.js';\nimport Table from './modules/table.js';\nimport Toolbar from './modules/toolbar.js';\n\nimport Icons from './ui/icons.js';\nimport Picker from './ui/picker.js';\nimport ColorPicker from './ui/color-picker.js';\nimport IconPicker from './ui/icon-picker.js';\nimport Tooltip from './ui/tooltip.js';\n\nimport BubbleTheme from './themes/bubble.js';\nimport SnowTheme from './themes/snow.js';\n\nQuill.register(\n {\n 'attributors/attribute/direction': DirectionAttribute,\n\n 'attributors/class/align': AlignClass,\n 'attributors/class/background': BackgroundClass,\n 'attributors/class/color': ColorClass,\n 'attributors/class/direction': DirectionClass,\n 'attributors/class/font': FontClass,\n 'attributors/class/size': SizeClass,\n\n 'attributors/style/align': AlignStyle,\n 'attributors/style/background': BackgroundStyle,\n 'attributors/style/color': ColorStyle,\n 'attributors/style/direction': DirectionStyle,\n 'attributors/style/font': FontStyle,\n 'attributors/style/size': SizeStyle,\n },\n true,\n);\n\nQuill.register(\n {\n 'formats/align': AlignClass,\n 'formats/direction': DirectionClass,\n 'formats/indent': Indent,\n\n 'formats/background': BackgroundStyle,\n 'formats/color': ColorStyle,\n 'formats/font': FontClass,\n 'formats/size': SizeClass,\n\n 'formats/blockquote': Blockquote,\n 'formats/code-block': CodeBlock,\n 'formats/header': Header,\n 'formats/list': List,\n\n 'formats/bold': Bold,\n 'formats/code': InlineCode,\n 'formats/italic': Italic,\n 'formats/link': Link,\n 'formats/script': Script,\n 'formats/strike': Strike,\n 'formats/underline': Underline,\n\n 'formats/formula': Formula,\n 'formats/image': Image,\n 'formats/video': Video,\n\n 'modules/syntax': Syntax,\n 'modules/table': Table,\n 'modules/toolbar': Toolbar,\n\n 'themes/bubble': BubbleTheme,\n 'themes/snow': SnowTheme,\n\n 'ui/icons': Icons,\n 'ui/picker': Picker,\n 'ui/icon-picker': IconPicker,\n 'ui/color-picker': ColorPicker,\n 'ui/tooltip': Tooltip,\n },\n true,\n);\n\nexport { Module } from './core.js';\nexport type {\n Bounds,\n DebugLevel,\n EmitterSource,\n ExpandedQuillOptions,\n QuillOptions,\n};\nexport { Parchment, Range };\n\nexport default Quill;\n", "/*! For license information please see quill-cursors.js.LICENSE.txt */\n!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define([],e):\"object\"==typeof exports?exports.QuillCursors=e():t.QuillCursors=e()}(self,(()=>(()=>{var t={582:(t,e,r)=>{\"use strict\";r.d(e,{Z:()=>s});var n=r(81),i=r.n(n),o=r(645),a=r.n(o)()(i());a.push([t.id,\".ql-container{position:relative;overflow:hidden}@media(pointer: coarse){.ql-cursor-caret-container{z-index:-1}}.ql-cursor.hidden{display:none}.ql-cursor .ql-cursor-caret-container,.ql-cursor .ql-cursor-flag{position:absolute}.ql-cursor .ql-cursor-flag{z-index:1;transform:translate3d(-1px, -100%, 0);opacity:0;visibility:hidden;color:#fff;padding-bottom:2px;border-radius:0 3px 3px 0}.ql-cursor .ql-cursor-flag.flag-flipped{border-radius:3px 0 0 3px;transform:translate3d(calc(-100% + 1px ), -100%, 0)}@media screen{.ql-cursor .ql-cursor-flag{transition:opacity 0ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 0ms,visibility 0ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 0ms}}.ql-cursor .ql-cursor-flag .ql-cursor-name{margin-left:5px;margin-right:5px;display:inline-block;margin-top:-2px;white-space:nowrap}.ql-cursor .ql-cursor-flag.no-delay[style]{transition-delay:unset !important}.ql-cursor .ql-cursor-caret-container{cursor:text;margin-left:-9px;padding:0 9px}.ql-cursor .ql-cursor-caret-container.hover+.ql-cursor-flag{opacity:1;visibility:visible;transition:none}.ql-cursor .ql-cursor-caret-container.no-pointer{pointer-events:none}.ql-cursor .ql-cursor-caret-container .ql-cursor-caret{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background-color:attr(data-color)}.ql-cursor .ql-cursor-selection-block{position:absolute;pointer-events:none}\",\"\"]);const s=a},645:t=>{\"use strict\";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var r=\"\",n=void 0!==e[5];return e[4]&&(r+=\"@supports (\".concat(e[4],\") {\")),e[2]&&(r+=\"@media \".concat(e[2],\" {\")),n&&(r+=\"@layer\".concat(e[5].length>0?\" \".concat(e[5]):\"\",\" {\")),r+=t(e),n&&(r+=\"}\"),e[2]&&(r+=\"}\"),e[4]&&(r+=\"}\"),r})).join(\"\")},e.i=function(t,r,n,i,o){\"string\"==typeof t&&(t=[[null,t,void 0]]);var a={};if(n)for(var s=0;s0?\" \".concat(l[5]):\"\",\" {\").concat(l[1],\"}\")),l[5]=o),r&&(l[2]?(l[1]=\"@media \".concat(l[2],\" {\").concat(l[1],\"}\"),l[2]=r):l[2]=r),i&&(l[4]?(l[1]=\"@supports (\".concat(l[4],\") {\").concat(l[1],\"}\"),l[4]=i):l[4]=\"\".concat(i)),e.push(l))}},e}},81:t=>{\"use strict\";t.exports=function(t){return t[1]}},529:t=>{var e=-1;function r(t,s,u,c){if(t===s)return t?[[0,t]]:[];if(null!=u){var l=function(t,e,r){var n=\"number\"==typeof r?{index:r,length:0}:r.oldRange,i=\"number\"==typeof r?null:r.newRange,o=t.length,a=e.length;if(0===n.length&&(null===i||0===i.length)){var s=n.index,u=t.slice(0,s),c=t.slice(s),l=i?i.index:null,h=s+a-o;if((null===l||l===h)&&!(h<0||h>a)){var d=e.slice(0,h);if((_=e.slice(h))===c){var p=Math.min(s,h);if((b=u.slice(0,p))===(m=d.slice(0,p)))return f(b,u.slice(p),d.slice(p),c)}}if(null===l||l===s){var g=s,_=(d=e.slice(0,g),e.slice(g));if(d===u){var v=Math.min(o-g,a-g);if((y=c.slice(c.length-v))===(A=_.slice(_.length-v)))return f(u,c.slice(0,c.length-v),_.slice(0,_.length-v),y)}}}if(n.length>0&&i&&0===i.length){var b=t.slice(0,n.index),y=t.slice(n.index+n.length);if(!(a<(p=b.length)+(v=y.length))){var m=e.slice(0,p),A=e.slice(a-v);if(b===m&&y===A)return f(b,t.slice(p,o-v),e.slice(p,a-v),y)}}return null}(t,s,u);if(l)return l}var h=i(t,s),d=t.substring(0,h);h=o(t=t.substring(h),s=s.substring(h));var p=t.substring(t.length-h),g=function(t,a){var s;if(!t)return[[1,a]];if(!a)return[[e,t]];var u=t.length>a.length?t:a,c=t.length>a.length?a:t,l=u.indexOf(c);if(-1!==l)return s=[[1,u.substring(0,l)],[0,c],[1,u.substring(l+c.length)]],t.length>a.length&&(s[0][0]=s[2][0]=e),s;if(1===c.length)return[[e,t],[1,a]];var f=function(t,e){var r=t.length>e.length?t:e,n=t.length>e.length?e:t;if(r.length<4||2*n.length=t.length?[n,a,s,u,f]:null}var s,u,c,l,f,h=a(r,n,Math.ceil(r.length/4)),d=a(r,n,Math.ceil(r.length/2));return h||d?(s=d?h&&h[4].length>d[4].length?h:d:h,t.length>e.length?(u=s[0],c=s[1],l=s[2],f=s[3]):(l=s[0],f=s[1],u=s[2],c=s[3]),[u,c,l,f,s[4]]):null}(t,a);if(f){var h=f[0],d=f[1],p=f[2],g=f[3],_=f[4],v=r(h,p),b=r(d,g);return v.concat([[0,_]],b)}return function(t,r){for(var i=t.length,o=r.length,a=Math.ceil((i+o)/2),s=a,u=2*a,c=new Array(u),l=new Array(u),f=0;fi)g+=2;else if(A>o)p+=2;else if(d&&(w=s+h-y)>=0&&w=(C=i-l[w]))return n(t,r,S,A)}for(var x=-b+_;x<=b-v;x+=2){for(var C,w=s+x,E=(C=x===-b||x!==b&&l[w-1]i)v+=2;else if(E>o)_+=2;else if(!d){var S;if((m=s+h-x)>=0&&m=(C=i-C))return n(t,r,S,A)}}}return[[e,t],[1,r]]}(t,a)}(t=t.substring(0,t.length-h),s=s.substring(0,s.length-h));return d&&g.unshift([0,d]),p&&g.push([0,p]),a(g,c),g}function n(t,e,n,i){var o=t.substring(0,n),a=e.substring(0,i),s=t.substring(n),u=e.substring(i),c=r(o,a),l=r(s,u);return c.concat(l)}function i(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;for(var r=0,n=Math.min(t.length,e.length),i=n,o=0;r=0&&l(t[p][1])){var g=t[p][1].slice(-1);if(t[p][1]=t[p][1].slice(0,-1),h=g+h,d=g+d,!t[p][1]){t.splice(p,1),s--;var _=p-1;t[_]&&1===t[_][0]&&(f++,d=t[_][1]+d,_--),t[_]&&t[_][0]===e&&(u++,h=t[_][1]+h,_--),p=_}}c(t[s][1])&&(g=t[s][1].charAt(0),t[s][1]=t[s][1].slice(1),h+=g,d+=g)}if(s0||d.length>0){h.length>0&&d.length>0&&(0!==(n=i(d,h))&&(p>=0?t[p][1]+=d.substring(0,n):(t.splice(0,0,[0,d.substring(0,n)]),s++),d=d.substring(n),h=h.substring(n)),0!==(n=o(d,h))&&(t[s][1]=d.substring(d.length-n)+t[s][1],d=d.substring(0,d.length-n),h=h.substring(0,h.length-n)));var v=f+u;0===h.length&&0===d.length?(t.splice(s-v,v),s-=v):0===h.length?(t.splice(s-v,v,[1,d]),s=s-v+1):0===d.length?(t.splice(s-v,v,[e,h]),s=s-v+1):(t.splice(s-v,v,[e,h],[1,d]),s=s-v+2)}0!==s&&0===t[s-1][0]?(t[s-1][1]+=t[s][1],t.splice(s,1)):s++,f=0,u=0,h=\"\",d=\"\"}\"\"===t[t.length-1][1]&&t.pop();var b=!1;for(s=1;s=55296&&t<=56319}function u(t){return t>=56320&&t<=57343}function c(t){return u(t.charCodeAt(0))}function l(t){return s(t.charCodeAt(t.length-1))}function f(t,r,n,i){return l(t)||c(i)?null:function(t){for(var e=[],r=0;r0&&e.push(t[r]);return e}([[0,t],[e,r],[1,n],[0,i]])}function h(t,e,n){return r(t,e,n,!0)}h.INSERT=1,h.DELETE=e,h.EQUAL=0,t.exports=h},465:(t,e,r)=>{t=r.nmd(t);var n=\"__lodash_hash_undefined__\",i=9007199254740991,o=\"[object Arguments]\",a=\"[object Boolean]\",s=\"[object Date]\",u=\"[object Function]\",c=\"[object GeneratorFunction]\",l=\"[object Map]\",f=\"[object Number]\",h=\"[object Object]\",d=\"[object Promise]\",p=\"[object RegExp]\",g=\"[object Set]\",_=\"[object String]\",v=\"[object Symbol]\",b=\"[object WeakMap]\",y=\"[object ArrayBuffer]\",m=\"[object DataView]\",A=\"[object Float32Array]\",x=\"[object Float64Array]\",C=\"[object Int8Array]\",w=\"[object Int16Array]\",E=\"[object Int32Array]\",S=\"[object Uint8Array]\",M=\"[object Uint8ClampedArray]\",O=\"[object Uint16Array]\",j=\"[object Uint32Array]\",L=/\\w*$/,k=/^\\[object .+?Constructor\\]$/,T=/^(?:0|[1-9]\\d*)$/,R={};R[o]=R[\"[object Array]\"]=R[y]=R[m]=R[a]=R[s]=R[A]=R[x]=R[C]=R[w]=R[E]=R[l]=R[f]=R[h]=R[p]=R[g]=R[_]=R[v]=R[S]=R[M]=R[O]=R[j]=!0,R[\"[object Error]\"]=R[u]=R[b]=!1;var N=\"object\"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,q=\"object\"==typeof self&&self&&self.Object===Object&&self,D=N||q||Function(\"return this\")(),F=e&&!e.nodeType&&e,I=F&&t&&!t.nodeType&&t,P=I&&I.exports===F;function B(t,e){return t.set(e[0],e[1]),t}function z(t,e){return t.add(e),t}function H(t,e,r,n){var i=-1,o=t?t.length:0;for(n&&o&&(r=t[++i]);++i-1},Mt.prototype.set=function(t,e){var r=this.__data__,n=kt(r,t);return n<0?r.push([t,e]):r[n][1]=e,this},Ot.prototype.clear=function(){this.__data__={hash:new St,map:new(pt||Mt),string:new St}},Ot.prototype.delete=function(t){return qt(this,t).delete(t)},Ot.prototype.get=function(t){return qt(this,t).get(t)},Ot.prototype.has=function(t){return qt(this,t).has(t)},Ot.prototype.set=function(t,e){return qt(this,t).set(t,e),this},jt.prototype.clear=function(){this.__data__=new Mt},jt.prototype.delete=function(t){return this.__data__.delete(t)},jt.prototype.get=function(t){return this.__data__.get(t)},jt.prototype.has=function(t){return this.__data__.has(t)},jt.prototype.set=function(t,e){var r=this.__data__;if(r instanceof Mt){var n=r.__data__;if(!pt||n.length<199)return n.push([t,e]),this;r=this.__data__=new Ot(n)}return r.set(t,e),this};var Ft=lt?$(lt,Object):function(){return[]},It=function(t){return et.call(t)};function Pt(t,e){return!!(e=null==e?i:e)&&(\"number\"==typeof t||T.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=i}(t.length)&&!Vt(t)}var $t=ft||function(){return!1};function Vt(t){var e=Wt(t)?et.call(t):\"\";return e==u||e==c}function Wt(t){var e=typeof t;return!!t&&(\"object\"==e||\"function\"==e)}function Xt(t){return Gt(t)?function(t,e){var r=Ut(t)||function(t){return function(t){return function(t){return!!t&&\"object\"==typeof t}(t)&&Gt(t)}(t)&&tt.call(t,\"callee\")&&(!ut.call(t,\"callee\")||et.call(t)==o)}(t)?function(t,e){for(var r=-1,n=Array(t);++r{t=r.nmd(t);var n=\"__lodash_hash_undefined__\",i=9007199254740991,o=\"[object Arguments]\",a=\"[object Array]\",s=\"[object Boolean]\",u=\"[object Date]\",c=\"[object Error]\",l=\"[object Function]\",f=\"[object Map]\",h=\"[object Number]\",d=\"[object Object]\",p=\"[object Promise]\",g=\"[object RegExp]\",_=\"[object Set]\",v=\"[object String]\",b=\"[object WeakMap]\",y=\"[object ArrayBuffer]\",m=\"[object DataView]\",A=/^\\[object .+?Constructor\\]$/,x=/^(?:0|[1-9]\\d*)$/,C={};C[\"[object Float32Array]\"]=C[\"[object Float64Array]\"]=C[\"[object Int8Array]\"]=C[\"[object Int16Array]\"]=C[\"[object Int32Array]\"]=C[\"[object Uint8Array]\"]=C[\"[object Uint8ClampedArray]\"]=C[\"[object Uint16Array]\"]=C[\"[object Uint32Array]\"]=!0,C[o]=C[a]=C[y]=C[s]=C[m]=C[u]=C[c]=C[l]=C[f]=C[h]=C[d]=C[g]=C[_]=C[v]=C[b]=!1;var w=\"object\"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,E=\"object\"==typeof self&&self&&self.Object===Object&&self,S=w||E||Function(\"return this\")(),M=e&&!e.nodeType&&e,O=M&&t&&!t.nodeType&&t,j=O&&O.exports===M,L=j&&w.process,k=function(){try{return L&&L.binding&&L.binding(\"util\")}catch(t){}}(),T=k&&k.isTypedArray;function R(t,e){for(var r=-1,n=null==t?0:t.length;++rs))return!1;var c=o.get(t);if(c&&o.get(e))return c==e;var l=-1,f=!0,h=2&r?new yt:void 0;for(o.set(t,e),o.set(e,t);++l-1},vt.prototype.set=function(t,e){var r=this.__data__,n=At(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this},bt.prototype.clear=function(){this.size=0,this.__data__={hash:new _t,map:new(it||vt),string:new _t}},bt.prototype.delete=function(t){var e=Mt(this,t).delete(t);return this.size-=e?1:0,e},bt.prototype.get=function(t){return Mt(this,t).get(t)},bt.prototype.has=function(t){return Mt(this,t).has(t)},bt.prototype.set=function(t,e){var r=Mt(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this},yt.prototype.add=yt.prototype.push=function(t){return this.__data__.set(t,n),this},yt.prototype.has=function(t){return this.__data__.has(t)},mt.prototype.clear=function(){this.__data__=new vt,this.size=0},mt.prototype.delete=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r},mt.prototype.get=function(t){return this.__data__.get(t)},mt.prototype.has=function(t){return this.__data__.has(t)},mt.prototype.set=function(t,e){var r=this.__data__;if(r instanceof vt){var n=r.__data__;if(!it||n.length<199)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new bt(n)}return r.set(t,e),this.size=r.size,this};var jt=tt?function(t){return null==t?[]:(t=Object(t),function(e,r){for(var n=-1,i=null==e?0:e.length,o=0,a=[];++n-1&&t%1==0&&t-1&&t%1==0&&t<=i}function Pt(t){var e=typeof t;return null!=t&&(\"object\"==e||\"function\"==e)}function Bt(t){return null!=t&&\"object\"==typeof t}var zt=T?function(t){return function(e){return t(e)}}(T):function(t){return Bt(t)&&It(t.length)&&!!C[xt(t)]};function Ht(t){return null!=(e=t)&&It(e.length)&&!Ft(e)?function(t,e){var r=qt(t),n=!r&&Nt(t),i=!r&&!n&&Dt(t),o=!r&&!n&&!i&&zt(t),a=r||n||i||o,s=a?function(t,e){for(var r=-1,n=Array(t);++r0?n:void 0},t.diff=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),\"object\"!=typeof t&&(t={}),\"object\"!=typeof e&&(e={});var r=Object.keys(t).concat(Object.keys(e)).reduce((function(r,n){return a.default(t[n],e[n])||(r[n]=void 0===e[n]?null:e[n]),r}),{});return Object.keys(r).length>0?r:void 0},t.invert=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),t=t||{};var r=Object.keys(e).reduce((function(r,n){return e[n]!==t[n]&&void 0!==t[n]&&(r[n]=e[n]),r}),{});return Object.keys(t).reduce((function(r,n){return t[n]!==e[n]&&void 0===e[n]&&(r[n]=null),r}),r)},t.transform=function(t,e,r){if(void 0===r&&(r=!1),\"object\"!=typeof t)return e;if(\"object\"==typeof e){if(!r)return e;var n=Object.keys(e).reduce((function(r,n){return void 0===t[n]&&(r[n]=e[n]),r}),{});return Object.keys(n).length>0?n:void 0}}}(i||(i={})),e.default=i},895:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},i=n(r(529)),o=n(r(465)),a=n(r(307)),s=n(r(210)),u=n(r(430)),c=String.fromCharCode(0),l=function(){function t(t){Array.isArray(t)?this.ops=t:null!=t&&Array.isArray(t.ops)?this.ops=t.ops:this.ops=[]}return t.prototype.insert=function(t,e){var r={};return\"string\"==typeof t&&0===t.length?this:(r.insert=t,null!=e&&\"object\"==typeof e&&Object.keys(e).length>0&&(r.attributes=e),this.push(r))},t.prototype.delete=function(t){return t<=0?this:this.push({delete:t})},t.prototype.retain=function(t,e){if(t<=0)return this;var r={retain:t};return null!=e&&\"object\"==typeof e&&Object.keys(e).length>0&&(r.attributes=e),this.push(r)},t.prototype.push=function(t){var e=this.ops.length,r=this.ops[e-1];if(t=o.default(t),\"object\"==typeof r){if(\"number\"==typeof t.delete&&\"number\"==typeof r.delete)return this.ops[e-1]={delete:r.delete+t.delete},this;if(\"number\"==typeof r.delete&&null!=t.insert&&(e-=1,\"object\"!=typeof(r=this.ops[e-1])))return this.ops.unshift(t),this;if(a.default(t.attributes,r.attributes)){if(\"string\"==typeof t.insert&&\"string\"==typeof r.insert)return this.ops[e-1]={insert:r.insert+t.insert},\"object\"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this;if(\"number\"==typeof t.retain&&\"number\"==typeof r.retain)return this.ops[e-1]={retain:r.retain+t.retain},\"object\"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this}}return e===this.ops.length?this.ops.push(t):this.ops.splice(e,0,t),this},t.prototype.chop=function(){var t=this.ops[this.ops.length-1];return t&&t.retain&&!t.attributes&&this.ops.pop(),this},t.prototype.filter=function(t){return this.ops.filter(t)},t.prototype.forEach=function(t){this.ops.forEach(t)},t.prototype.map=function(t){return this.ops.map(t)},t.prototype.partition=function(t){var e=[],r=[];return this.forEach((function(n){(t(n)?e:r).push(n)})),[e,r]},t.prototype.reduce=function(t,e){return this.ops.reduce(t,e)},t.prototype.changeLength=function(){return this.reduce((function(t,e){return e.insert?t+u.default.length(e):e.delete?t-e.delete:t}),0)},t.prototype.length=function(){return this.reduce((function(t,e){return t+u.default.length(e)}),0)},t.prototype.slice=function(e,r){void 0===e&&(e=0),void 0===r&&(r=1/0);for(var n=[],i=u.default.iterator(this.ops),o=0;o0&&n.next(o.retain-c)}for(var l=new t(i);r.hasNext()||n.hasNext();)if(\"insert\"===n.peekType())l.push(n.next());else if(\"delete\"===r.peekType())l.push(r.next());else{var f=Math.min(r.peekLength(),n.peekLength()),h=r.next(f),d=n.next(f);if(\"number\"==typeof d.retain){var p={};\"number\"==typeof h.retain?p.retain=f:p.insert=h.insert;var g=s.default.compose(h.attributes,d.attributes,\"number\"==typeof h.retain);if(g&&(p.attributes=g),l.push(p),!n.hasNext()&&a.default(l.ops[l.ops.length-1],p)){var _=new t(r.rest());return l.concat(_).chop()}}else\"number\"==typeof d.delete&&\"number\"==typeof h.retain&&l.push(d)}return l.chop()},t.prototype.concat=function(e){var r=new t(this.ops.slice());return e.ops.length>0&&(r.push(e.ops[0]),r.ops=r.ops.concat(e.ops.slice(1))),r},t.prototype.diff=function(e,r){if(this.ops===e.ops)return new t;var n=[this,e].map((function(t){return t.map((function(r){if(null!=r.insert)return\"string\"==typeof r.insert?r.insert:c;throw new Error(\"diff() called \"+(t===e?\"on\":\"with\")+\" non-document\")})).join(\"\")})),o=new t,l=i.default(n[0],n[1],r),f=u.default.iterator(this.ops),h=u.default.iterator(e.ops);return l.forEach((function(t){for(var e=t[1].length;e>0;){var r=0;switch(t[0]){case i.default.INSERT:r=Math.min(h.peekLength(),e),o.push(h.next(r));break;case i.default.DELETE:r=Math.min(e,f.peekLength()),f.next(r),o.delete(r);break;case i.default.EQUAL:r=Math.min(f.peekLength(),h.peekLength(),e);var n=f.next(r),u=h.next(r);a.default(n.insert,u.insert)?o.retain(r,s.default.diff(n.attributes,u.attributes)):o.push(u).delete(r)}e-=r}})),o.chop()},t.prototype.eachLine=function(e,r){void 0===r&&(r=\"\\n\");for(var n=u.default.iterator(this.ops),i=new t,o=0;n.hasNext();){if(\"insert\"!==n.peekType())return;var a=n.peek(),s=u.default.length(a)-n.peekLength(),c=\"string\"==typeof a.insert?a.insert.indexOf(r,s)-s:-1;if(c<0)i.push(n.next());else if(c>0)i.push(n.next(c));else{if(!1===e(i,n.next(1).attributes||{},o))return;o+=1,i=new t}}i.length()>0&&e(i,{},o)},t.prototype.invert=function(e){var r=new t;return this.reduce((function(t,n){if(n.insert)r.delete(u.default.length(n));else{if(n.retain&&null==n.attributes)return r.retain(n.retain),t+n.retain;if(n.delete||n.retain&&n.attributes){var i=n.delete||n.retain;return e.slice(t,t+i).forEach((function(t){n.delete?r.push(t):n.retain&&n.attributes&&r.retain(u.default.length(t),s.default.invert(n.attributes,t.attributes))})),t+i}}return t}),0),r.chop()},t.prototype.transform=function(e,r){if(void 0===r&&(r=!1),r=!!r,\"number\"==typeof e)return this.transformPosition(e,r);for(var n=e,i=u.default.iterator(this.ops),o=u.default.iterator(n.ops),a=new t;i.hasNext()||o.hasNext();)if(\"insert\"!==i.peekType()||!r&&\"insert\"===o.peekType())if(\"insert\"===o.peekType())a.push(o.next());else{var c=Math.min(i.peekLength(),o.peekLength()),l=i.next(c),f=o.next(c);if(l.delete)continue;f.delete?a.push(f):a.retain(c,s.default.transform(l.attributes,f.attributes,r))}else a.retain(u.default.length(i.next()));return a.chop()},t.prototype.transformPosition=function(t,e){void 0===e&&(e=!1),e=!!e;for(var r=u.default.iterator(this.ops),n=0;r.hasNext()&&n<=t;){var i=r.peekLength(),o=r.peekType();r.next(),\"delete\"!==o?(\"insert\"===o&&(n=n-r?(t=n-r,this.index+=1,this.offset=0):this.offset+=t,\"number\"==typeof e.delete)return{delete:t};var o={};return e.attributes&&(o.attributes=e.attributes),\"number\"==typeof e.retain?o.retain=t:\"string\"==typeof e.insert?o.insert=e.insert.substr(r,t):o.insert=e.insert,o}return{retain:1/0}},t.prototype.peek=function(){return this.ops[this.index]},t.prototype.peekLength=function(){return this.ops[this.index]?i.default.length(this.ops[this.index])-this.offset:1/0},t.prototype.peekType=function(){return this.ops[this.index]?\"number\"==typeof this.ops[this.index].delete?\"delete\":\"number\"==typeof this.ops[this.index].retain?\"retain\":\"insert\":\"retain\"},t.prototype.rest=function(){if(this.hasNext()){if(0===this.offset)return this.ops.slice(this.index);var t=this.offset,e=this.index,r=this.next(),n=this.ops.slice(this.index);return this.offset=t,this.index=e,[r].concat(n)}return[]},t}();e.default=o},430:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var i,o=n(r(977));!function(t){t.iterator=function(t){return new o.default(t)},t.length=function(t){return\"number\"==typeof t.delete?t.delete:\"number\"==typeof t.retain?t.retain:\"string\"==typeof t.insert?t.insert.length:1}}(i||(i={})),e.default=i},165:function(t,e,r){var n,i;void 0===(i=\"function\"==typeof(n=function(){var t,e={};function r(t,e,r){var n=t.getClientRects();if(2===n.length){var i=t.getBoundingClientRect();return n[e][r]=e.length)return Array.prototype.push.apply(t,e);for(;n1,t.getClientRects||(s.setEnd(o,1),t.getClientRects=t.getBoundingClientRect=2===s.getClientRects().length),!t.getBoundingClientRect){s.setEnd(s.startContainer,s.startOffset);var u=s.getBoundingClientRect();t.getBoundingClientRect=0===u.top&&0===u.left}if(document.body.removeChild(e),!t.getBoundingClientRect){var c=document.createElement(\"p\");c.style.width=\"0px\",c.style.fontSize=\"20px\",c.style.whiteSpace=\"normal\",c.style.wordBreak=\"normal\";var l=document.createTextNode(\"m mm\");c.appendChild(l),document.body.appendChild(c),s.setStart(l,1),s.setEnd(l,2),r(s,1,\"left\")?t.getBoundingClientRect=!0:(s.setStart(l,1),s.setEnd(l,3),r(s,0,\"top\")&&(t.getBoundingClientRect=!0)),document.body.removeChild(c)}var f=window.ActiveXObject&&new Function(\"/*@cc_on return @_jscript_version; @*/\")();t.ieZoom=!!f&&f<=10}return t},e.getClientRects=function(t){var e=this.isBroken();if(e.ieZoom)return n(t.getClientRects());if(!e.getClientRects)return t.getClientRects();var r=[],o=[],a=t.endContainer,s=t.endOffset,u=document.createRange();function c(t){for(var e=0;t=t.previousSibling;)e++;return e}for(;a!==t.commonAncestorContainer;)u.setStart(a,0),u.setEnd(a,s),i(o,u.getClientRects()),s=c(a),a=a.parentNode;return(u=t.cloneRange()).setEnd(a,s),i(r,u.getClientRects()),i(r,o),r},e.getBoundingClientRect=function(t){var e=this.getClientRects(t);if(0===e.length)return null;var r,i=t.getBoundingClientRect(),o=this.isBroken();if(o.ieZoom)return n(i);if(!o.getBoundingClientRect)return i;if(0===i.width&&0===i.height)return e[0];for(var a=0,s=e.length;a{\"use strict\";r.r(e),r.d(e,{default:()=>C});var n=function(){if(\"undefined\"!=typeof Map)return Map;function t(t,e){var r=-1;return t.some((function(t,n){return t[0]===e&&(r=n,!0)})),r}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,\"size\",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var r=t(this.__entries__,e),n=this.__entries__[r];return n&&n[1]},e.prototype.set=function(e,r){var n=t(this.__entries__,e);~n?this.__entries__[n][1]=r:this.__entries__.push([e,r])},e.prototype.delete=function(e){var r=this.__entries__,n=t(r,e);~n&&r.splice(n,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var r=0,n=this.__entries__;r0},t.prototype.connect_=function(){i&&!this.connected_&&(document.addEventListener(\"transitionend\",this.onTransitionEnd_),window.addEventListener(\"resize\",this.refresh),u?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(\"DOMSubtreeModified\",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){i&&this.connected_&&(document.removeEventListener(\"transitionend\",this.onTransitionEnd_),window.removeEventListener(\"resize\",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(\"DOMSubtreeModified\",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,r=void 0===e?\"\":e;s.some((function(t){return!!~r.indexOf(t)}))&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),l=function(t,e){for(var r=0,n=Object.keys(e);r0},t}(),A=\"undefined\"!=typeof WeakMap?new WeakMap:new n,x=function t(e){if(!(this instanceof t))throw new TypeError(\"Cannot call a class as a function.\");if(!arguments.length)throw new TypeError(\"1 argument required, but only 0 present.\");var r=c.getInstance(),n=new m(e,r,this);A.set(this,n)};[\"observe\",\"unobserve\",\"disconnect\"].forEach((function(t){x.prototype[t]=function(){var e;return(e=A.get(this))[t].apply(e,arguments)}}));const C=void 0!==o.ResizeObserver?o.ResizeObserver:x},413:(t,e,r)=>{\"use strict\";r.r(e),r.d(e,{default:()=>v});var n=r(379),i=r.n(n),o=r(795),a=r.n(o),s=r(569),u=r.n(s),c=r(565),l=r.n(c),f=r(216),h=r.n(f),d=r(589),p=r.n(d),g=r(582),_={};_.styleTagTransform=p(),_.setAttributes=l(),_.insert=u().bind(null,\"head\"),_.domAPI=a(),_.insertStyleElement=h(),i()(g.Z,_);const v=g.Z&&g.Z.locals?g.Z.locals:void 0},379:t=>{\"use strict\";var e=[];function r(t){for(var r=-1,n=0;n{\"use strict\";var e={};t.exports=function(t,r){var n=function(t){if(void 0===e[t]){var r=document.querySelector(t);if(window.HTMLIFrameElement&&r instanceof window.HTMLIFrameElement)try{r=r.contentDocument.head}catch(t){r=null}e[t]=r}return e[t]}(t);if(!n)throw new Error(\"Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.\");n.appendChild(r)}},216:t=>{\"use strict\";t.exports=function(t){var e=document.createElement(\"style\");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},565:(t,e,r)=>{\"use strict\";t.exports=function(t){var e=r.nc;e&&t.setAttribute(\"nonce\",e)}},795:t=>{\"use strict\";t.exports=function(t){var e=t.insertStyleElement(t);return{update:function(r){!function(t,e,r){var n=\"\";r.supports&&(n+=\"@supports (\".concat(r.supports,\") {\")),r.media&&(n+=\"@media \".concat(r.media,\" {\"));var i=void 0!==r.layer;i&&(n+=\"@layer\".concat(r.layer.length>0?\" \".concat(r.layer):\"\",\" {\")),n+=r.css,i&&(n+=\"}\"),r.media&&(n+=\"}\"),r.supports&&(n+=\"}\");var o=r.sourceMap;o&&\"undefined\"!=typeof btoa&&(n+=\"\\n/*# sourceMappingURL=data:application/json;base64,\".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o)))),\" */\")),e.styleTagTransform(n,t,e.options)}(e,t,r)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},589:t=>{\"use strict\";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}},607:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0}),e.Cursor=e.default=void 0;var i=n(r(678));e.default=i.default;var o=n(r(353));e.Cursor=o.default,r(413)},353:(t,e,r)=>{\"use strict\";Object.defineProperty(e,\"__esModule\",{value:!0});var n=r(207),i=function(){function t(t,e,r){this.id=t,this.name=e,this.color=r,this.toggleNearCursor=this.toggleNearCursor.bind(this),this._toggleOpenedCursor=this._toggleOpenedCursor.bind(this),this._setHoverState=this._setHoverState.bind(this)}return t.prototype.build=function(e){var r=document.createElement(t.CONTAINER_ELEMENT_TAG);r.classList.add(t.CURSOR_CLASS),r.id=\"ql-cursor-\".concat(this.id),r.innerHTML=e.template;var n=r.getElementsByClassName(t.SELECTION_CLASS)[0],i=r.getElementsByClassName(t.CARET_CONTAINER_CLASS)[0],o=i.getElementsByClassName(t.CARET_CLASS)[0],a=r.getElementsByClassName(t.FLAG_CLASS)[0];return a.style.backgroundColor=this.color,o.style.backgroundColor=this.color,r.getElementsByClassName(t.NAME_CLASS)[0].textContent=this.name,this._hideDelay=\"\".concat(e.hideDelayMs,\"ms\"),this._hideSpeedMs=e.hideSpeedMs,this._positionFlag=e.positionFlag,a.style.transitionDelay=this._hideDelay,a.style.transitionDuration=\"\".concat(this._hideSpeedMs,\"ms\"),this._el=r,this._selectionEl=n,this._caretEl=i,this._flagEl=a,i.addEventListener(\"mouseover\",this._setHoverState,{passive:!0}),this._el},t.prototype.show=function(){this._el.classList.remove(t.HIDDEN_CLASS)},t.prototype.hide=function(){this._el.classList.add(t.HIDDEN_CLASS)},t.prototype.remove=function(){this._el.parentNode.removeChild(this._el)},t.prototype.toggleNearCursor=function(e,r){var n=this._getCoordinates(),i=n.left,o=n.right,a=n.top,s=n.bottom,u=e>=i&&e<=o&&r>=a&&r<=s;return this._caretEl.classList.toggle(t.CONTAINER_HOVER_CLASS,u),u},t.prototype.toggleFlag=function(e){var r=this;this._caretEl.classList.toggle(t.CONTAINER_HOVER_CLASS,e)||(this._flagEl.classList.add(t.NO_DELAY_CLASS),setTimeout((function(){return r._flagEl.classList.remove(t.NO_DELAY_CLASS)}),this._hideSpeedMs))},t.prototype.updateCaret=function(t,e){this._caretEl.style.top=\"\".concat(t.top,\"px\"),this._caretEl.style.left=\"\".concat(t.left,\"px\"),this._caretEl.style.height=\"\".concat(t.height,\"px\"),this._positionFlag?this._positionFlag(this._flagEl,t,e):this._updateCaretFlag(t,e)},t.prototype.updateSelection=function(t,e){var r=this;this._clearSelection(),t=t||[],t=Array.from(t),t=this._sanitize(t),(t=this._sortByDomPosition(t)).forEach((function(t){return r._addSelection(t,e)}))},t.prototype._setHoverState=function(){document.addEventListener(\"mousemove\",this._toggleOpenedCursor,{passive:!0})},t.prototype._toggleOpenedCursor=function(e){var r=this.toggleNearCursor(e.clientX,e.clientY);this._caretEl.classList.toggle(t.CONTAINER_NO_POINTER_CLASS,r),r||document.removeEventListener(\"mousemove\",this._toggleOpenedCursor)},t.prototype._getCoordinates=function(){return this._caretEl.getBoundingClientRect()},t.prototype._updateCaretFlag=function(e,r){this._flagEl.style.width=\"\";var n=this._flagEl.getBoundingClientRect();this._flagEl.classList.remove(t.FLAG_FLIPPED_CLASS),e.left>r.width-n.width&&this._flagEl.classList.add(t.FLAG_FLIPPED_CLASS),this._flagEl.style.left=\"\".concat(e.left,\"px\"),this._flagEl.style.top=\"\".concat(e.top,\"px\"),this._flagEl.style.width=\"\".concat(Math.ceil(n.width),\"px\")},t.prototype._clearSelection=function(){this._selectionEl.innerHTML=\"\"},t.prototype._addSelection=function(t,e){var r=this._selectionBlock(t,e);this._selectionEl.appendChild(r)},t.prototype._selectionBlock=function(e,r){var i=document.createElement(t.SELECTION_ELEMENT_TAG);return i.classList.add(t.SELECTION_BLOCK_CLASS),i.style.top=\"\".concat(e.top-r.top,\"px\"),i.style.left=\"\".concat(e.left-r.left,\"px\"),i.style.width=\"\".concat(e.width,\"px\"),i.style.height=\"\".concat(e.height,\"px\"),i.style.backgroundColor=n(this.color).setAlpha(.3).toString(),i},t.prototype._sortByDomPosition=function(t){return t.sort((function(t,e){return t.top===e.top?t.left-e.left:t.top-e.top}))},t.prototype._sanitize=function(t){var e=this,r=new Set;return t.filter((function(t){if(!t.width||!t.height)return!1;var n=e._serialize(t);return!r.has(n)&&(r.add(n),!0)}))},t.prototype._serialize=function(t){return[\"top:\".concat(t.top),\"right:\".concat(t.right),\"bottom:\".concat(t.bottom),\"left:\".concat(t.left)].join(\";\")},t.CONTAINER_ELEMENT_TAG=\"SPAN\",t.SELECTION_ELEMENT_TAG=\"SPAN\",t.CURSOR_CLASS=\"ql-cursor\",t.SELECTION_CLASS=\"ql-cursor-selections\",t.SELECTION_BLOCK_CLASS=\"ql-cursor-selection-block\",t.CARET_CLASS=\"ql-cursor-caret\",t.CARET_CONTAINER_CLASS=\"ql-cursor-caret-container\",t.CONTAINER_HOVER_CLASS=\"hover\",t.CONTAINER_NO_POINTER_CLASS=\"no-pointer\",t.FLAG_CLASS=\"ql-cursor-flag\",t.FLAG_FLIPPED_CLASS=\"flag-flipped\",t.NAME_CLASS=\"ql-cursor-name\",t.HIDDEN_CLASS=\"hidden\",t.NO_DELAY_CLASS=\"no-delay\",t}();e.default=i},678:function(t,e,r){\"use strict\";var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);i&&!(\"get\"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)\"default\"!==r&&Object.prototype.hasOwnProperty.call(t,r)&&n(e,t,r);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var s=a(r(353)),u=o(r(165)),c=a(r(338)),l=a(r(33)),f=r(895),h=function(){function t(t,e){void 0===e&&(e={}),this._cursors={},this._isObserving=!1,this._handleCursorTouch=this._handleCursorTouch.bind(this),this.quill=t,this.options=this._setDefaults(e),this._container=this.quill.addContainer(this.options.containerClass),this._boundsContainer=this.options.boundsContainer||this.quill.container,this._currentSelection=this.quill.getSelection(),this._registerSelectionChangeListeners(),this._registerTextChangeListener(),this._registerDomListeners()}return t.prototype.createCursor=function(t,e,r){var n=this._cursors[t];if(!n){n=new s.default(t,e,r),this._cursors[t]=n;var i=n.build(this.options);this._container.appendChild(i)}return n},t.prototype.moveCursor=function(t,e){var r=this._cursors[t];r&&(r.range=e,this._updateCursor(r))},t.prototype.removeCursor=function(t){var e=this._cursors[t];e&&(e.remove(),delete this._cursors[t])},t.prototype.update=function(){var t=this;this.cursors().forEach((function(e){return t._updateCursor(e)}))},t.prototype.clearCursors=function(){var t=this;this.cursors().forEach((function(e){return t.removeCursor(e.id)}))},t.prototype.toggleFlag=function(t,e){var r=this._cursors[t];r&&r.toggleFlag(e)},t.prototype.cursors=function(){var t=this;return Object.keys(this._cursors).map((function(e){return t._cursors[e]}))},t.prototype._registerSelectionChangeListeners=function(){var t=this;this.quill.on(this.quill.constructor.events.SELECTION_CHANGE,(function(e){t._currentSelection=e}))},t.prototype._registerTextChangeListener=function(){var t=this;this.quill.on(this.quill.constructor.events.TEXT_CHANGE,(function(e){return t._handleTextChange(e)}))},t.prototype._registerDomListeners=function(){var t=this,e=this.quill.container.getElementsByClassName(\"ql-editor\")[0];e.addEventListener(\"scroll\",(function(){return t.update()}),{passive:!0}),e.addEventListener(\"touchstart\",this._handleCursorTouch,{passive:!0})},t.prototype._handleCursorTouch=function(t){var e=this;this.cursors().forEach((function(r){r.toggleNearCursor(t.pageX,t.pageY),setTimeout((function(){return r.toggleFlag(!1)}),e.options.hideDelayMs)}))},t.prototype._registerResizeObserver=function(){var t=this;if(!this._isObserving){var e=this.quill.container.getElementsByClassName(\"ql-editor\")[0],r=new l.default((function(e){if(!e[0].target.isConnected)return r.disconnect(),void(t._isObserving=!1);t.update()}));r.observe(e),this._isObserving=!0}},t.prototype._updateCursor=function(t){if(this._registerResizeObserver(),!t.range)return t.hide();var e=this._indexWithinQuillBounds(t.range.index),r=this._indexWithinQuillBounds(t.range.index+t.range.length),n=this.quill.getLeaf(e),i=this.quill.getLeaf(r);if(!this._leafIsValid(n)||!this._leafIsValid(i))return t.hide();t.show();var o=this._boundsContainer.getBoundingClientRect(),a=this.quill.getBounds(r);t.updateCaret(a,o);var s=this._lineRanges(t,n,i).reduce((function(t,e){return t.concat(Array.from(u.getClientRects(e)))}),[]);t.updateSelection(s,o)},t.prototype._indexWithinQuillBounds=function(t){var e=this.quill.getLength(),r=e?e-1:0;return t=Math.max(t,0),Math.min(t,r)},t.prototype._leafIsValid=function(t){return t&&t[0]&&t[0].domNode&&t[1]>=0},t.prototype._handleTextChange=function(t){var e=this;window.setTimeout((function(){e.options.transformOnTextChange&&e._transformCursors(t),e.options.selectionChangeSource&&(e._emitSelection(),e.update())}))},t.prototype._emitSelection=function(){this.quill.emitter.emit(this.quill.constructor.events.SELECTION_CHANGE,this.quill.getSelection(),this._currentSelection,this.options.selectionChangeSource)},t.prototype._setDefaults=function(e){return(e=Object.assign({},e)).template||(e.template=t.DEFAULTS.template),e.containerClass||(e.containerClass=t.DEFAULTS.containerClass),null!==e.selectionChangeSource&&(e.selectionChangeSource||(e.selectionChangeSource=t.DEFAULTS.selectionChangeSource)),e.hideDelayMs=Number.isInteger(e.hideDelayMs)?e.hideDelayMs:t.DEFAULTS.hideDelayMs,e.hideSpeedMs=Number.isInteger(e.hideSpeedMs)?e.hideSpeedMs:t.DEFAULTS.hideSpeedMs,e.transformOnTextChange=!!e.transformOnTextChange,e},t.prototype._lineRanges=function(t,e,r){var n=this.quill.getLines(t.range);return n.reduce((function(t,i,o){if(!i.children){var a=document.createRange();return a.selectNode(i.domNode),t.concat(a)}var s=0===o?e:i.path(0).pop(),u=s[0],c=s[1],l=o===n.length-1?r:i.path(i.length()-1).pop(),f=l[0],h=l[1],d=document.createRange();return u.domNode.nodeType===Node.TEXT_NODE?d.setStart(u.domNode,c):d.setStartBefore(u.domNode),f.domNode.nodeType===Node.TEXT_NODE?d.setEnd(f.domNode,h):d.setEndAfter(f.domNode),t.concat(d)}),[])},t.prototype._transformCursors=function(t){var e=this;t=new f(t),this.cursors().filter((function(t){return t.range})).forEach((function(r){r.range.index=t.transformPosition(r.range.index),e._updateCursor(r)}))},t.DEFAULTS={template:c.default,containerClass:\"ql-cursors\",selectionChangeSource:\"api\",hideDelayMs:3e3,hideSpeedMs:400},t}();e.default=h},338:function(t,e,r){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,\"__esModule\",{value:!0});var i=n(r(353)),o='\\n \\n \\n \\n \\n
    \\n \\n
    \\n');e.default=o},207:function(t){t.exports=function(){\"use strict\";const t=/^\\s+/,e=/\\s+$/;function r(n,i){if(i=i||{},(n=n||\"\")instanceof r)return n;if(!(this instanceof r))return new r(n,i);var o=function(r){var n={r:0,g:0,b:0},i=1,o=null,a=null,s=null,u=!1,c=!1;return\"string\"==typeof r&&(r=function(r){r=r.replace(t,\"\").replace(e,\"\").toLowerCase();var n,i=!1;if(y[r])r=y[r],i=!0;else if(\"transparent\"==r)return{r:0,g:0,b:0,a:0,format:\"name\"};return(n=T.rgb.exec(r))?{r:n[1],g:n[2],b:n[3]}:(n=T.rgba.exec(r))?{r:n[1],g:n[2],b:n[3],a:n[4]}:(n=T.hsl.exec(r))?{h:n[1],s:n[2],l:n[3]}:(n=T.hsla.exec(r))?{h:n[1],s:n[2],l:n[3],a:n[4]}:(n=T.hsv.exec(r))?{h:n[1],s:n[2],v:n[3]}:(n=T.hsva.exec(r))?{h:n[1],s:n[2],v:n[3],a:n[4]}:(n=T.hex8.exec(r))?{r:w(n[1]),g:w(n[2]),b:w(n[3]),a:O(n[4]),format:i?\"name\":\"hex8\"}:(n=T.hex6.exec(r))?{r:w(n[1]),g:w(n[2]),b:w(n[3]),format:i?\"name\":\"hex\"}:(n=T.hex4.exec(r))?{r:w(n[1]+\"\"+n[1]),g:w(n[2]+\"\"+n[2]),b:w(n[3]+\"\"+n[3]),a:O(n[4]+\"\"+n[4]),format:i?\"name\":\"hex8\"}:!!(n=T.hex3.exec(r))&&{r:w(n[1]+\"\"+n[1]),g:w(n[2]+\"\"+n[2]),b:w(n[3]+\"\"+n[3]),format:i?\"name\":\"hex\"}}(r)),\"object\"==typeof r&&(R(r.r)&&R(r.g)&&R(r.b)?(l=r.r,f=r.g,h=r.b,n={r:255*x(l,255),g:255*x(f,255),b:255*x(h,255)},u=!0,c=\"%\"===String(r.r).substr(-1)?\"prgb\":\"rgb\"):R(r.h)&&R(r.s)&&R(r.v)?(o=S(r.s),a=S(r.v),n=function(t,e,r){t=6*x(t,360),e=x(e,100),r=x(r,100);var n=Math.floor(t),i=t-n,o=r*(1-e),a=r*(1-i*e),s=r*(1-(1-i)*e),u=n%6;return{r:255*[r,a,o,o,s,r][u],g:255*[s,r,r,a,o,o][u],b:255*[o,o,s,r,r,a][u]}}(r.h,o,a),u=!0,c=\"hsv\"):R(r.h)&&R(r.s)&&R(r.l)&&(o=S(r.s),s=S(r.l),n=function(t,e,r){var n,i,o;function a(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=x(t,360),e=x(e,100),r=x(r,100),0===e)n=i=o=r;else{var s=r<.5?r*(1+e):r+e-r*e,u=2*r-s;n=a(u,s,t+1/3),i=a(u,s,t),o=a(u,s,t-1/3)}return{r:255*n,g:255*i,b:255*o}}(r.h,o,s),u=!0,c=\"hsl\"),r.hasOwnProperty(\"a\")&&(i=r.a)),i=A(i),{ok:u,format:r.format||c,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a:i};var l,f,h}(n);this._originalInput=n,this._r=o.r,this._g=o.g,this._b=o.b,this._a=o.a,this._roundA=Math.round(100*this._a)/100,this._format=i.format||o.format,this._gradientType=i.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=o.ok}function n(t,e,r){t=x(t,255),e=x(e,255),r=x(r,255);var n,i,o=Math.max(t,e,r),a=Math.min(t,e,r),s=(o+a)/2;if(o==a)n=i=0;else{var u=o-a;switch(i=s>.5?u/(2-o-a):u/(o+a),o){case t:n=(e-r)/u+(e>1)+720)%360;--e;)i.h=(i.h+o)%360,a.push(r(i));return a}function b(t,e){e=e||6;for(var n=r(t).toHsv(),i=n.h,o=n.s,a=n.v,s=[],u=1/e;e--;)s.push(r({h:i,s:o,v:a})),a=(a+u)%1;return s}r.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n=this.toRgb();return t=n.r/255,e=n.g/255,r=n.b/255,.2126*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.7152*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))},setAlpha:function(t){return this._a=A(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=i(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=i(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),n=Math.round(100*t.v);return 1==this._a?\"hsv(\"+e+\", \"+r+\"%, \"+n+\"%)\":\"hsva(\"+e+\", \"+r+\"%, \"+n+\"%, \"+this._roundA+\")\"},toHsl:function(){var t=n(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=n(this._r,this._g,this._b),e=Math.round(360*t.h),r=Math.round(100*t.s),i=Math.round(100*t.l);return 1==this._a?\"hsl(\"+e+\", \"+r+\"%, \"+i+\"%)\":\"hsla(\"+e+\", \"+r+\"%, \"+i+\"%, \"+this._roundA+\")\"},toHex:function(t){return o(this._r,this._g,this._b,t)},toHexString:function(t){return\"#\"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[E(Math.round(t).toString(16)),E(Math.round(e).toString(16)),E(Math.round(r).toString(16)),E(M(n))];return i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1)?o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0):o.join(\"\")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return\"#\"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?\"rgb(\"+Math.round(this._r)+\", \"+Math.round(this._g)+\", \"+Math.round(this._b)+\")\":\"rgba(\"+Math.round(this._r)+\", \"+Math.round(this._g)+\", \"+Math.round(this._b)+\", \"+this._roundA+\")\"},toPercentageRgb:function(){return{r:Math.round(100*x(this._r,255))+\"%\",g:Math.round(100*x(this._g,255))+\"%\",b:Math.round(100*x(this._b,255))+\"%\",a:this._a}},toPercentageRgbString:function(){return 1==this._a?\"rgb(\"+Math.round(100*x(this._r,255))+\"%, \"+Math.round(100*x(this._g,255))+\"%, \"+Math.round(100*x(this._b,255))+\"%)\":\"rgba(\"+Math.round(100*x(this._r,255))+\"%, \"+Math.round(100*x(this._g,255))+\"%, \"+Math.round(100*x(this._b,255))+\"%, \"+this._roundA+\")\"},toName:function(){return 0===this._a?\"transparent\":!(this._a<1)&&(m[o(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e=\"#\"+a(this._r,this._g,this._b,this._a),n=e,i=this._gradientType?\"GradientType = 1, \":\"\";if(t){var o=r(t);n=\"#\"+a(o._r,o._g,o._b,o._a)}return\"progid:DXImageTransform.Microsoft.gradient(\"+i+\"startColorstr=\"+e+\",endColorstr=\"+n+\")\"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||\"hex\"!==t&&\"hex6\"!==t&&\"hex3\"!==t&&\"hex4\"!==t&&\"hex8\"!==t&&\"name\"!==t?(\"rgb\"===t&&(r=this.toRgbString()),\"prgb\"===t&&(r=this.toPercentageRgbString()),\"hex\"!==t&&\"hex6\"!==t||(r=this.toHexString()),\"hex3\"===t&&(r=this.toHexString(!0)),\"hex4\"===t&&(r=this.toHex8String(!0)),\"hex8\"===t&&(r=this.toHex8String()),\"name\"===t&&(r=this.toName()),\"hsl\"===t&&(r=this.toHslString()),\"hsv\"===t&&(r=this.toHsvString()),r||this.toHexString()):\"name\"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return r(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(l,arguments)},brighten:function(){return this._applyModification(f,arguments)},darken:function(){return this._applyModification(h,arguments)},desaturate:function(){return this._applyModification(s,arguments)},saturate:function(){return this._applyModification(u,arguments)},greyscale:function(){return this._applyModification(c,arguments)},spin:function(){return this._applyModification(d,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(v,arguments)},complement:function(){return this._applyCombination(p,arguments)},monochromatic:function(){return this._applyCombination(b,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(g,[3])},tetrad:function(){return this._applyCombination(g,[4])}},r.fromRatio=function(t,e){if(\"object\"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&(n[i]=\"a\"===i?t[i]:S(t[i]));t=n}return r(t,e)},r.equals=function(t,e){return!(!t||!e)&&r(t).toRgbString()==r(e).toRgbString()},r.random=function(){return r.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},r.mix=function(t,e,n){n=0===n?0:n||50;var i=r(t).toRgb(),o=r(e).toRgb(),a=n/100;return r({r:(o.r-i.r)*a+i.r,g:(o.g-i.g)*a+i.g,b:(o.b-i.b)*a+i.b,a:(o.a-i.a)*a+i.a})},r.readability=function(t,e){var n=r(t),i=r(e);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},r.isReadable=function(t,e,n){var i,o,a,s,u,c=r.readability(t,e);switch(o=!1,(a=n,\"AA\"!==(s=((a=a||{level:\"AA\",size:\"small\"}).level||\"AA\").toUpperCase())&&\"AAA\"!==s&&(s=\"AA\"),\"small\"!==(u=(a.size||\"small\").toLowerCase())&&\"large\"!==u&&(u=\"small\"),i={level:s,size:u}).level+i.size){case\"AAsmall\":case\"AAAlarge\":o=c>=4.5;break;case\"AAlarge\":o=c>=3;break;case\"AAAsmall\":o=c>=7}return o},r.mostReadable=function(t,e,n){var i,o,a,s,u=null,c=0;o=(n=n||{}).includeFallbackColors,a=n.level,s=n.size;for(var l=0;lc&&(c=i,u=r(e[l]));return r.isReadable(t,u,{level:a,size:s})||!o?u:(n.includeFallbackColors=!1,r.mostReadable(t,[\"#fff\",\"#000\"],n))};var y=r.names={aliceblue:\"f0f8ff\",antiquewhite:\"faebd7\",aqua:\"0ff\",aquamarine:\"7fffd4\",azure:\"f0ffff\",beige:\"f5f5dc\",bisque:\"ffe4c4\",black:\"000\",blanchedalmond:\"ffebcd\",blue:\"00f\",blueviolet:\"8a2be2\",brown:\"a52a2a\",burlywood:\"deb887\",burntsienna:\"ea7e5d\",cadetblue:\"5f9ea0\",chartreuse:\"7fff00\",chocolate:\"d2691e\",coral:\"ff7f50\",cornflowerblue:\"6495ed\",cornsilk:\"fff8dc\",crimson:\"dc143c\",cyan:\"0ff\",darkblue:\"00008b\",darkcyan:\"008b8b\",darkgoldenrod:\"b8860b\",darkgray:\"a9a9a9\",darkgreen:\"006400\",darkgrey:\"a9a9a9\",darkkhaki:\"bdb76b\",darkmagenta:\"8b008b\",darkolivegreen:\"556b2f\",darkorange:\"ff8c00\",darkorchid:\"9932cc\",darkred:\"8b0000\",darksalmon:\"e9967a\",darkseagreen:\"8fbc8f\",darkslateblue:\"483d8b\",darkslategray:\"2f4f4f\",darkslategrey:\"2f4f4f\",darkturquoise:\"00ced1\",darkviolet:\"9400d3\",deeppink:\"ff1493\",deepskyblue:\"00bfff\",dimgray:\"696969\",dimgrey:\"696969\",dodgerblue:\"1e90ff\",firebrick:\"b22222\",floralwhite:\"fffaf0\",forestgreen:\"228b22\",fuchsia:\"f0f\",gainsboro:\"dcdcdc\",ghostwhite:\"f8f8ff\",gold:\"ffd700\",goldenrod:\"daa520\",gray:\"808080\",green:\"008000\",greenyellow:\"adff2f\",grey:\"808080\",honeydew:\"f0fff0\",hotpink:\"ff69b4\",indianred:\"cd5c5c\",indigo:\"4b0082\",ivory:\"fffff0\",khaki:\"f0e68c\",lavender:\"e6e6fa\",lavenderblush:\"fff0f5\",lawngreen:\"7cfc00\",lemonchiffon:\"fffacd\",lightblue:\"add8e6\",lightcoral:\"f08080\",lightcyan:\"e0ffff\",lightgoldenrodyellow:\"fafad2\",lightgray:\"d3d3d3\",lightgreen:\"90ee90\",lightgrey:\"d3d3d3\",lightpink:\"ffb6c1\",lightsalmon:\"ffa07a\",lightseagreen:\"20b2aa\",lightskyblue:\"87cefa\",lightslategray:\"789\",lightslategrey:\"789\",lightsteelblue:\"b0c4de\",lightyellow:\"ffffe0\",lime:\"0f0\",limegreen:\"32cd32\",linen:\"faf0e6\",magenta:\"f0f\",maroon:\"800000\",mediumaquamarine:\"66cdaa\",mediumblue:\"0000cd\",mediumorchid:\"ba55d3\",mediumpurple:\"9370db\",mediumseagreen:\"3cb371\",mediumslateblue:\"7b68ee\",mediumspringgreen:\"00fa9a\",mediumturquoise:\"48d1cc\",mediumvioletred:\"c71585\",midnightblue:\"191970\",mintcream:\"f5fffa\",mistyrose:\"ffe4e1\",moccasin:\"ffe4b5\",navajowhite:\"ffdead\",navy:\"000080\",oldlace:\"fdf5e6\",olive:\"808000\",olivedrab:\"6b8e23\",orange:\"ffa500\",orangered:\"ff4500\",orchid:\"da70d6\",palegoldenrod:\"eee8aa\",palegreen:\"98fb98\",paleturquoise:\"afeeee\",palevioletred:\"db7093\",papayawhip:\"ffefd5\",peachpuff:\"ffdab9\",peru:\"cd853f\",pink:\"ffc0cb\",plum:\"dda0dd\",powderblue:\"b0e0e6\",purple:\"800080\",rebeccapurple:\"663399\",red:\"f00\",rosybrown:\"bc8f8f\",royalblue:\"4169e1\",saddlebrown:\"8b4513\",salmon:\"fa8072\",sandybrown:\"f4a460\",seagreen:\"2e8b57\",seashell:\"fff5ee\",sienna:\"a0522d\",silver:\"c0c0c0\",skyblue:\"87ceeb\",slateblue:\"6a5acd\",slategray:\"708090\",slategrey:\"708090\",snow:\"fffafa\",springgreen:\"00ff7f\",steelblue:\"4682b4\",tan:\"d2b48c\",teal:\"008080\",thistle:\"d8bfd8\",tomato:\"ff6347\",turquoise:\"40e0d0\",violet:\"ee82ee\",wheat:\"f5deb3\",white:\"fff\",whitesmoke:\"f5f5f5\",yellow:\"ff0\",yellowgreen:\"9acd32\"},m=r.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(y);function A(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function x(t,e){(function(t){return\"string\"==typeof t&&-1!=t.indexOf(\".\")&&1===parseFloat(t)})(t)&&(t=\"100%\");var r=function(t){return\"string\"==typeof t&&-1!=t.indexOf(\"%\")}(t);return t=Math.min(e,Math.max(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),Math.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function C(t){return Math.min(1,Math.max(0,t))}function w(t){return parseInt(t,16)}function E(t){return 1==t.length?\"0\"+t:\"\"+t}function S(t){return t<=1&&(t=100*t+\"%\"),t}function M(t){return Math.round(255*parseFloat(t)).toString(16)}function O(t){return w(t)/255}var j,L,k,T=(L=\"[\\\\s|\\\\(]+(\"+(j=\"(?:[-\\\\+]?\\\\d*\\\\.\\\\d+%?)|(?:[-\\\\+]?\\\\d+%?)\")+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")\\\\s*\\\\)?\",k=\"[\\\\s|\\\\(]+(\"+j+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")[,|\\\\s]+(\"+j+\")\\\\s*\\\\)?\",{CSS_UNIT:new RegExp(j),rgb:new RegExp(\"rgb\"+L),rgba:new RegExp(\"rgba\"+k),hsl:new RegExp(\"hsl\"+L),hsla:new RegExp(\"hsla\"+k),hsv:new RegExp(\"hsv\"+L),hsva:new RegExp(\"hsva\"+k),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function R(t){return!!T.CSS_UNIT.exec(t)}return r}()}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={id:n,loaded:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}r.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return r.d(e,{a:e}),e},r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if(\"object\"==typeof globalThis)return globalThis;try{return this||new Function(\"return this\")()}catch(t){if(\"object\"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},r.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),r.nc=void 0;var n=r(607);return n.default})()));", "/**\n * @module bindings/quill\n */\n\nimport * as Y from 'yjs' // eslint-disable-line\n\n/**\n * @typedef {import('y-protocols/awareness').Awareness} Awareness\n\n/**\n * Removes the pending '\\n's if it has no attributes.\n */\nexport const normQuillDelta = delta => {\n if (delta.length > 0) {\n const d = delta[delta.length - 1]\n const insert = d.insert\n if (d.attributes === undefined && insert !== undefined && insert.slice(-1) === '\\n') {\n delta = delta.slice()\n let ins = insert.slice(0, -1)\n while (ins.slice(-1) === '\\n') {\n ins = ins.slice(0, -1)\n }\n delta[delta.length - 1] = { insert: ins }\n if (ins.length === 0) {\n delta.pop()\n }\n return delta\n }\n }\n return delta\n}\n\n/**\n * @param {any} quillCursors\n */\nconst updateCursor = (quillCursors, aw, clientId, doc, type) => {\n try {\n if (aw && aw.cursor && clientId !== doc.clientID) {\n const user = aw.user || {}\n const color = user.color || '#ffa500'\n const name = user.name || `User: ${clientId}`\n quillCursors.createCursor(clientId.toString(), name, color)\n const anchor = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(aw.cursor.anchor), doc)\n const head = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(aw.cursor.head), doc)\n if (anchor && head && anchor.type === type) {\n quillCursors.moveCursor(clientId.toString(), { index: anchor.index, length: head.index - anchor.index })\n }\n } else {\n quillCursors.removeCursor(clientId.toString())\n }\n } catch (err) {\n console.error(err)\n }\n}\n\nexport class QuillBinding {\n /**\n * @param {Y.Text} type\n * @param {any} quill\n * @param {Awareness} [awareness]\n */\n constructor (type, quill, awareness) {\n const doc = /** @type {Y.Doc} */ (type.doc)\n this.type = type\n this.doc = doc\n this.quill = quill\n const quillCursors = quill.getModule('cursors') || null\n this.quillCursors = quillCursors\n // This object contains all attributes used in the quill instance\n this._negatedUsedFormats = {}\n this.awareness = awareness\n this._awarenessChange = ({ added, removed, updated }) => {\n const states = /** @type {Awareness} */ (awareness).getStates()\n added.forEach(id => {\n updateCursor(quillCursors, states.get(id), id, doc, type)\n })\n updated.forEach(id => {\n updateCursor(quillCursors, states.get(id), id, doc, type)\n })\n removed.forEach(id => {\n quillCursors.removeCursor(id.toString())\n })\n }\n /**\n * @param {Y.YTextEvent} event\n */\n this._typeObserver = event => {\n if (event.transaction.origin !== this) {\n const eventDelta = event.delta\n // We always explicitly set attributes, otherwise concurrent edits may\n // result in quill assuming that a text insertion shall inherit existing\n // attributes.\n const delta = []\n for (let i = 0; i < eventDelta.length; i++) {\n const d = eventDelta[i]\n if (d.insert !== undefined) {\n delta.push(Object.assign({}, d, { attributes: Object.assign({}, this._negatedUsedFormats, d.attributes || {}) }))\n } else {\n delta.push(d)\n }\n }\n quill.updateContents(delta, this)\n }\n }\n type.observe(this._typeObserver)\n this._quillObserver = (eventType, delta, state, origin) => {\n if (delta && delta.ops) {\n // update content\n const ops = delta.ops\n ops.forEach(op => {\n if (op.attributes !== undefined) {\n for (const key in op.attributes) {\n if (this._negatedUsedFormats[key] === undefined) {\n this._negatedUsedFormats[key] = false\n }\n }\n }\n })\n if (origin !== this) {\n doc.transact(() => {\n type.applyDelta(ops)\n }, this)\n }\n }\n // always check selection\n if (awareness && quillCursors) {\n const sel = quill.getSelection()\n const aw = /** @type {any} */ (awareness.getLocalState())\n if (sel === null) {\n if (awareness.getLocalState() !== null) {\n awareness.setLocalStateField('cursor', /** @type {any} */ (null))\n }\n } else {\n const anchor = Y.createRelativePositionFromTypeIndex(type, sel.index)\n const head = Y.createRelativePositionFromTypeIndex(type, sel.index + sel.length)\n if (!aw || !aw.cursor || !Y.compareRelativePositions(anchor, aw.cursor.anchor) || !Y.compareRelativePositions(head, aw.cursor.head)) {\n awareness.setLocalStateField('cursor', {\n anchor,\n head\n })\n }\n }\n // update all remote cursor locations\n awareness.getStates().forEach((aw, clientId) => {\n updateCursor(quillCursors, aw, clientId, doc, type)\n })\n }\n }\n quill.on('editor-change', this._quillObserver)\n // This indirectly initializes _negatedUsedFormats.\n // Make sure that this call this after the _quillObserver is set.\n quill.setContents(type.toDelta(), this)\n // init remote cursors\n if (quillCursors !== null && awareness) {\n awareness.getStates().forEach((aw, clientId) => {\n updateCursor(quillCursors, aw, clientId, doc, type)\n })\n awareness.on('change', this._awarenessChange)\n }\n }\n\n destroy () {\n this.type.unobserve(this._typeObserver)\n this.quill.off('editor-change', this._quillObserver)\n if (this.awareness) {\n this.awareness.off('change', this._awarenessChange)\n }\n }\n}\n", "// Generated by js_of_ocaml\n//# buildInfo:effects=false, kind=exe, use-js-string=true, version=5.8.2+5.8.2\n(function(a){typeof\nglobalThis!==\"object\"&&(this?b():(a.defineProperty(a.prototype,\"_T_\",{configurable:true,get:b}),_T_));function\nb(){var\nb=this||self;b.globalThis=b;delete\na.prototype._T_}}(Object));(function(a){window.yjs=require(\"yjs\");window.WebrtcProvider=require(\"y-webrtc\").WebrtcProvider;window.IndexeddbPersistence=require(\"y-indexeddb\").IndexeddbPersistence}(globalThis));(function(a){require(\"quill/dist/quill.core.css\");require(\"quill/dist/quill.bubble.css\");require(\"quill/dist/quill.snow.css\");window.Quill=require(\"quill\").default;window.QuillCursors=require(\"quill-cursors\")}(globalThis));(function(a){window.QuillBinding=require(\"y-quill\").QuillBinding}(globalThis));(function(p){\"use strict\";var\nv=3850876,aE=\" \",ad=\"0\",f1=\"compare: functional value\",f0=\"mkdir\",cu=1000,jI=\"delete\",X=\"vendor/lwd/lib/lwd/lwd_seq.pp.ml\",kt=\"@[\",ks=\"window\",kS=\"console\",dO=\"int_of_string\",fH=\"fs\",ka=\"%u\",kr=\"/static/\",jH=\"%i\",kR=\"%ni\",aX=0xff,fZ=749039939,kq=\"Assert_failure\",aG=737455525,j$=\"camlinternalMod.ml\",jG=\"0x\",j_=0x7ff0,kQ=218,jF=0xdfff,j9=\"End_of_file\",kp=\"OCAMLRUNPARAM\",jE=\": closedir failed\",ko=253,kP=\"Out_of_memory\",jD=\"Not_found\",f6=\"Failure\",dN=\"Unix.Unix_error\",jC=\"style\",j8=\"^\",bW=\"text\",kO=\"length\",fT=\"ENOTDIR\",kn=\"Lwd_seq.rank: node is marked\",bv=936573133,jB=\"%Li\",jz=\"flex\",jA=\"Invalid_argument\",dG=254,bV=\"+\",dI=\"Set.bal\",kN=\", characters \",aV=0xffffff,j7=858694086,km=120,kl=1027,ct=1024,dM=\"Map.bal\",ba=246,j6=\"Pervasives.do_at_exit\",kk=389604418,j5=65536,jy=\"submit\",c=\"vendor/brr_lwd_ui/examples/yjs/main.ml\",fS=0xf,T=16620,jx=\", \",dF=512,fR=-588596599,kL=\"Match_failure\",kM=\"closedir\",jv=\"%li\",jw=1026,kK=-32,ju=157,jt=\"b\",fG=\"nan\",e=\"\",fF=\"rmdir\",fY=\"Fatal error: exception \",j4=\"infinity\",K=\"camlinternalFormat.ml\",j3=\"fd \",kI=\"append\",kJ=\": \",js=174,q=248,j2=\"em\",j1=\"data\",kH=0xe0,kj=24029,j0=0xf0,jZ=\"Sys_error\",ao=0x80,fQ=\"vendor/brr_lwd_ui/bindings/yjs/doc.ml\",ki=\"ENOTEMPTY\",kG=\"EEXIST\",fX=1255,jY=1073741823,dE=\"value\",fE=\" : flags Open_text and Open_binary are not compatible\",kF=\"px\",fP=\"e\",kE=459,fD=\": Not a directory\",fO=\"ENOENT\",kh=\"Stack_overflow\",fN=-605101559,S=15681,jX=\"Array\",kD=\"Undefined_recursive_module\",kC=2147483647,aF=0x8000,cs=\"string\",dH=\"table\",jW=0x800,kg=-48,jq=\"error\",jr=\" : is a directory\",jU=\"@{\",jV=\"Division_by_zero\",jp=\"classList\",a$=\".\",jT=\"(Program not linked with -g, cannot print stack backtrace)\\n\",cq=\"name\",bb=0x3f,kB=492,a_=737456202,fM=\" : file already exists\",bu=128,dL=\": No such file or directory\",jR=\"vendor/lwd/lib/brr-lwd/elwd.ml\",jS=255,dD=\"lwd-to-remove\",cv=256,jo=\"checked\",cr=-976970511,fL=100,jQ=\"id\",fC=\"index out of bounds\",kf=-937474657,aH=\"/\",fB=504440814,dC=252,kA=\"height: \",jn=\"lwdui-virtual-table-row\",fA=\"%d\",kz=383,jl=\"bold\",jm=\": file descriptor already closed\",bs=\"-\",fz=\"EBADF\",jP=\"changes\",aW=951901561,jO=102,fK=-97,ky=\"Printexc.handle_uncaught_exception\",jk=12520,f5=\" : flags Open_rdonly and Open_wronly are not compatible\",a=\"vendor/lwd/lib/lwd/lwd_table.ml\",fW=756711075,ke=\"Fatal error: exception %s\\n\",fJ=4100401,kx=\"class\",jj=\"\\xe2\\x9d\\x8c\",aD=250,jN=199,dK=\"bool\",f3=82908052,f4=\"kind\",bt=611392745,fI=\"cell\",kw=\">\",jM=\"([^/]+)\",kd=\"input\",fV=\"jsError\",ji=103,dB='\"',aI=0xffff,f2=127,fU=737308346,jh=0xdc00,jL=\"documentElement\",kv=\"Sys_blocked_io\",b=\"vendor/lwd/lib/lwd/lwd.ml\",kc=\"not implemented\",jg=\"buffer.ml\",jK=\"Form submitted:\",ku=\"_\",fy=\"target\",jJ=-101336657,kb=\"rem\",dJ=\"_bigarr02\";function\nzq(a,b,c,d,e){if(d<=b)for(var\nf=1;f<=e;f++)c[d+f]=a[b+f];else\nfor(var\nf=e;f>=1;f--)c[d+f]=a[b+f];return 0}function\nzr(a,b,c){var\nd=new\nArray(c+1);d[0]=0;for(var\ne=1,f=b+1;e<=c;e++,f++)d[e]=a[f];return d}function\ncE(a,b,c){var\nd=String.fromCharCode;if(b==0&&c<=4096&&c==a.length)return d.apply(null,a);var\nf=e;for(;0=c.l||c.t==2&&e>=c.c.length)){c.c=a.t==4?cE(a.c,b,e):b==0&&a.c.length==e?a.c:a.c.substr(b,e);c.t=c.c.length==c.l?0:2}else if(c.t==2&&d==c.c.length){c.c+=a.t==4?cE(a.c,b,e):b==0&&a.c.length==e?a.c:a.c.substr(b,e);c.t=c.c.length==c.l?0:2}else{if(c.t!=4)dS(c);var\ng=a.c,h=c.c;if(a.t==4)if(d<=b)for(var\nf=0;f=0;f--)h[d+f]=g[b+f];else{var\ni=Math.min(e,g.length-b);for(var\nf=0;f>=1;if(a==0)return d;b+=b;c++;if(c==9)b.slice(0,1)}}function\ncz(a){if(a.t==2)a.c+=b1(a.l-a.c.length,\"\\0\");else\na.c=cE(a.c,0,a.c.length);a.t=0}function\ngq(a){if(a.length<24){for(var\nb=0;bf2)return false;return true}else\nreturn!/[^\\x00-\\x7f]/.test(a)}function\nlo(a){for(var\nk=e,d=e,h,g,i,b,c=0,j=a.length;cdF){d.substr(0,1);k+=d;d=e;k+=a.slice(c,f)}else\nd+=a.slice(c,f);if(f==j)break;c=f}b=1;if(++c=0xd7ff&&b<0xe000)b=2}else{b=3;if(++c0x10ffff)b=3}}}}}if(b<4){c-=b;d+=\"\\ufffd\"}else if(b>aI)d+=String.fromCharCode(0xd7c0+(b>>10),jh+(b&0x3FF));else\nd+=String.fromCharCode(b);if(d.length>ct){d.substr(0,1);k+=d;d=e}}return k+d}function\naY(a,b,c){this.t=a;this.c=b;this.l=c}aY.prototype.toString=function(){switch(this.t){case\n9:return this.c;default:cz(this);case\n0:if(gq(this.c)){this.t=9;return this.c}this.t=8;case\n8:return this.c}};aY.prototype.toUtf16=function(){var\na=this.toString();if(this.t==9)return a;return lo(a)};aY.prototype.slice=function(){var\na=this.t==4?this.c.slice():this.c;return new\naY(this.t,a,this.l)};function\nk0(a){return new\naY(0,a,a.length)}function\naJ(a){return a}function\nbd(a){return k0(aJ(a))}function\ncy(a,b,c,d,e){aZ(bd(a),b,c,d,e);return 0}function\nlq(a){var\nb=p.process;if(b&&b.env&&b.env[a]!=undefined)return b.env[a];if(p.jsoo_static_env&&p.jsoo_static_env[a])return p.jsoo_static_env[a]}var\ngn=0;(function(){var\nc=lq(kp);if(c!==undefined){var\nb=c.split(\",\");for(var\na=0;a=a.c.length)return 0;case\n0:return a.c.charCodeAt(b);case\n4:return a.c[b]}}function\nzw(a,b){if(b>>>0>=a.l)f8();return bY(a,b)}function\nB(a,b,c){c&=aX;if(a.t!=4){if(b==a.c.length){a.c+=String.fromCharCode(c);if(b+1==a.l)a.t=0;return 0}dS(a)}a.c[b]=c;return 0}function\na0(a,b,c){if(b>>>0>=a.l)f8();return B(a,b,c)}function\nbx(a){return a.toArray()}function\nzx(a,b,c){if(b>>>0>=a.l-7)f8();var\ne=bx(c);for(var\nd=0;d<8;d++)B(a,b+7-d,e[d]);return 0}function\nbe(d,c){var\nf=d.l>=0?d.l:d.l=d.length,e=c.length,b=f-e;if(b==0)return d.apply(null,c);else if(b<0){var\na=d.apply(null,c.slice(0,f));if(typeof\na!==\"function\")return a;return be(a,c.slice(f))}else{switch(b){case\n1:{var\na=function(a){var\nf=new\nArray(e+1);for(var\nb=0;b>>0>=a.length-1)cx();return a}function\nzy(a){if(isFinite(a)){if(Math.abs(a)>=2.2250738585072014e-308)return 0;if(a!=0)return 1;return 2}return isNaN(a)?4:3}function\nla(a){return 0}var\nAt=Math.log2&&Math.log2(1.1235582092889474E+307)==1020;function\nAs(a){if(At)return Math.floor(Math.log2(a));var\nb=0;if(a==0)return-Infinity;if(a>=1)while(a>=2){a/=2;b++}else\nwhile(a<1){a*=2;b--}return b}function\ngd(a){var\nb=new\nFloat32Array(1);b[0]=a;var\nc=new\nInt32Array(b.buffer);return c[0]|0}var\nk7=Math.pow(2,-24);function\nli(a){throw a}function\ngm(){li(U.Division_by_zero)}function\nd(a,b,c){this.lo=a&aV;this.mi=b&aV;this.hi=c&aI}d.prototype.caml_custom=\"_j\";d.prototype.copy=function(){return new\nd(this.lo,this.mi,this.hi)};d.prototype.ucompare=function(a){if(this.hi>a.hi)return 1;if(this.hia.mi)return 1;if(this.mia.lo)return 1;if(this.loc)return 1;if(ba.mi)return 1;if(this.mia.lo)return 1;if(this.lo>24),c=-this.hi+(b>>24);return new\nd(a,b,c)};d.prototype.add=function(a){var\nb=this.lo+a.lo,c=this.mi+a.mi+(b>>24),e=this.hi+a.hi+(c>>24);return new\nd(b,c,e)};d.prototype.sub=function(a){var\nb=this.lo-a.lo,c=this.mi-a.mi+(b>>24),e=this.hi-a.hi+(c>>24);return new\nd(b,c,e)};d.prototype.mul=function(a){var\nb=this.lo*a.lo,c=(b*k7|0)+this.mi*a.lo+this.lo*a.mi,e=(c*k7|0)+this.hi*a.lo+this.mi*a.mi+this.lo*a.hi;return new\nd(b,c,e)};d.prototype.isZero=function(){return(this.lo|this.mi|this.hi)==0};d.prototype.isNeg=function(){return this.hi<<16<0};d.prototype.and=function(a){return new\nd(this.lo&a.lo,this.mi&a.mi,this.hi&a.hi)};d.prototype.or=function(a){return new\nd(this.lo|a.lo,this.mi|a.mi,this.hi|a.hi)};d.prototype.xor=function(a){return new\nd(this.lo^a.lo,this.mi^a.mi,this.hi^a.hi)};d.prototype.shift_left=function(a){a=a&63;if(a==0)return this;if(a<24)return new\nd(this.lo<>24-a,this.hi<>24-a);if(a<48)return new\nd(0,this.lo<>48-a);return new\nd(0,0,this.lo<>a|this.mi<<24-a,this.mi>>a|this.hi<<24-a,this.hi>>a);if(a<48)return new\nd(this.mi>>a-24|this.hi<<48-a,this.hi>>a-24,0);return new\nd(this.hi>>a-48,0,0)};d.prototype.shift_right=function(a){a=a&63;if(a==0)return this;var\nc=this.hi<<16>>16;if(a<24)return new\nd(this.lo>>a|this.mi<<24-a,this.mi>>a|c<<24-a,this.hi<<16>>a>>>16);var\nb=this.hi<<16>>31;if(a<48)return new\nd(this.mi>>a-24|this.hi<<48-a,this.hi<<16>>a-24>>16,b&aI);return new\nd(this.hi<<16>>a-32,b,b)};d.prototype.lsl1=function(){this.hi=this.hi<<1|this.mi>>23;this.mi=(this.mi<<1|this.lo>>23)&aV;this.lo=this.lo<<1&aV};d.prototype.lsr1=function(){this.lo=(this.lo>>>1|this.mi<<23)&aV;this.mi=(this.mi>>>1|this.hi<<23)&aV;this.hi=this.hi>>>1};d.prototype.udivmod=function(a){var\ne=0,c=this.copy(),b=a.copy(),f=new\nd(0,0,0);while(c.ucompare(b)>0){e++;b.lsl1()}while(e>=0){e--;f.lsl1();if(c.ucompare(b)>=0){f.lo++;c=c.sub(b)}b.lsr1()}return{quotient:f,modulus:c}};d.prototype.div=function(a){var\nb=this;if(a.isZero())gm();var\nd=b.hi^a.hi;if(b.hi&aF)b=b.neg();if(a.hi&aF)a=a.neg();var\nc=b.udivmod(a).quotient;if(d&aF)c=c.neg();return c};d.prototype.mod=function(a){var\nb=this;if(a.isZero())gm();var\nd=b.hi;if(b.hi&aF)b=b.neg();if(a.hi&aF)a=a.neg();var\nc=b.udivmod(a).modulus;if(d&aF)c=c.neg();return c};d.prototype.toInt=function(){return this.lo|this.mi<<24};d.prototype.toFloat=function(){return(this.hi<<16)*Math.pow(2,32)+this.mi*Math.pow(2,24)+this.lo};d.prototype.toArray=function(){return[this.hi>>8,this.hi&aX,this.mi>>16,this.mi>>8&aX,this.mi&aX,this.lo>>16,this.lo>>8&aX,this.lo&aX]};d.prototype.lo32=function(){return this.lo|(this.mi&aX)<<24};d.prototype.hi32=function(){return this.mi>>>8&aI|this.hi<<16};function\ndV(a,b,c){return new\nd(a,b,c)}function\ndU(a){if(!isFinite(a)){if(isNaN(a))return dV(1,0,j_);return a>0?dV(0,0,j_):dV(0,0,0xfff0)}var\nf=a==0&&1/a==-Infinity?aF:a>=0?0:aF;if(f)a=-a;var\nb=As(a)+1023;if(b<=0){b=0;a/=Math.pow(2,-jw)}else{a/=Math.pow(2,b-kl);if(a<16){a*=2;b-=1}if(b==0)a/=2}var\nd=Math.pow(2,24),c=a|0;a=(a-c)*d;var\ne=a|0;a=(a-e)*d;var\ng=a|0;c=c&fS|f|b<<4;return dV(g,e,c)}function\nkZ(a,b,c){a.write(32,b.dims.length);a.write(32,b.kind|b.layout<<8);if(b.caml_custom==dJ)for(var\nd=0;d>4;if(d==2047)return(f|g|c&fS)==0?c&aF?-Infinity:Infinity:NaN;var\ne=Math.pow(2,-24),b=(f*e+g)*e+(c&fS);if(d>0){b+=16;b*=Math.pow(2,d-kl)}else\nb*=Math.pow(2,-jw);if(c&aF)b=-b;return b}function\nf7(a){var\nd=a.length,c=1;for(var\nb=0;b>>24&aX|(b&aI)<<8,b>>>16&aI)}function\ngg(a){return a.hi32()}function\ngh(a){return a.lo32()}var\nzt=dJ;function\nbc(a,b,c,d){this.kind=a;this.layout=b;this.dims=c;this.data=d}bc.prototype.caml_custom=zt;bc.prototype.offset=function(a){var\nc=0;if(typeof\na===\"number\")a=[a];if(!(a\ninstanceof\nArray))G(\"bigarray.js: invalid offset\");if(this.dims.length!=a.length)G(\"Bigarray.get/set: bad number of dimensions\");if(this.layout==0)for(var\nb=0;b=this.dims[b])cx();c=c*this.dims[b]+a[b]}else\nfor(var\nb=this.dims.length-1;b>=0;b--){if(a[b]<1||a[b]>this.dims[b])cx();c=c*this.dims[b]+(a[b]-1)}return c};bc.prototype.get=function(a){switch(this.kind){case\n7:var\nd=this.data[a*2+0],b=this.data[a*2+1];return zR(d,b);case\n10:case\n11:var\ne=this.data[a*2+0],c=this.data[a*2+1];return[dG,e,c];default:return this.data[a]}};bc.prototype.set=function(a,b){switch(this.kind){case\n7:this.data[a*2+0]=gh(b);this.data[a*2+1]=gg(b);break;case\n10:case\n11:this.data[a*2+0]=b[1];this.data[a*2+1]=b[2];break;default:this.data[a]=b;break}return 0};bc.prototype.fill=function(a){switch(this.kind){case\n7:var\nc=gh(a),e=gg(a);if(c==e)this.data.fill(c);else\nfor(var\nb=0;be)return 1;if(d!=e){if(!b)return NaN;if(d==d)return 1;if(e==e)return-1}}break;case\n7:for(var\nc=0;ca.data[c+1])return 1;if(this.data[c]>>>0>>0)return-1;if(this.data[c]>>>0>a.data[c]>>>0)return 1}break;case\n2:case\n3:case\n4:case\n5:case\n6:case\n8:case\n9:case\n12:for(var\nc=0;ca.data[c])return 1}break}return 0};function\nbX(a,b,c,d){this.kind=a;this.layout=b;this.dims=c;this.data=d}bX.prototype=new\nbc();bX.prototype.offset=function(a){if(typeof\na!==\"number\")if(a\ninstanceof\nArray&&a.length==1)a=a[0];else\nG(\"Ml_Bigarray_c_1_1.offset\");if(a<0||a>=this.dims[0])cx();return a};bX.prototype.get=function(a){return this.data[a]};bX.prototype.set=function(a,b){this.data[a]=b;return 0};bX.prototype.fill=function(a){this.data.fill(a);return 0};function\nkV(a,b,c,d){var\ne=kX(a);if(f7(c)*e!=d.length)G(\"length doesn't match dims\");if(b==0&&c.length==1&&e==1)return new\nbX(a,b,c,d);return new\nbc(a,b,c,d)}function\naj(a){if(!U.Failure)U.Failure=[q,ak(f6),-3];gl(U.Failure,a)}function\nkW(a,b,c){var\nk=a.read32s();if(k<0||k>16)aj(\"input_value: wrong number of bigarray dimensions\");var\nr=a.read32s(),l=r&aX,q=r>>8&1,j=[];if(c==dJ)for(var\nd=0;d>>32-15;b=cC(b,0x1b873593);a^=b;a=a<<13|a>>>32-13;return(a+(a<<2)|0)+(0xe6546b64|0)|0}function\nzL(a,b){a=V(a,gh(b));a=V(a,gg(b));return a}function\ngb(a,b){return zL(a,dU(b))}function\nkY(a){var\nc=f7(a.dims),d=0;switch(a.kind){case\n2:case\n3:case\n12:if(c>cv)c=cv;var\ne=0,b=0;for(b=0;b+4<=a.data.length;b+=4){e=a.data[b+0]|a.data[b+1]<<8|a.data[b+2]<<16|a.data[b+3]<<24;d=V(d,e)}e=0;switch(c&3){case\n3:e=a.data[b+2]<<16;case\n2:e|=a.data[b+1]<<8;case\n1:e|=a.data[b+0];d=V(d,e)}break;case\n4:case\n5:if(c>bu)c=bu;var\ne=0,b=0;for(b=0;b+2<=a.data.length;b+=2){e=a.data[b+0]|a.data[b+1]<<16;d=V(d,e)}if((c&1)!=0)d=V(d,a.data[b]);break;case\n6:if(c>64)c=64;for(var\nb=0;b64)c=64;for(var\nb=0;b32)c=32;c*=2;for(var\nb=0;b64)c=64;for(var\nb=0;b32)c=32;for(var\nb=0;b0?f(b,a,d):f(a,b,d);if(d&&e!=e)return c;if(+e!=+e)return+e;if((e|0)!=0)return e|0}return c}function\ndY(a){return typeof\na===\"string\"&&!/[^\\x00-\\xff]/.test(a)}function\ndX(a){return a\ninstanceof\naY}function\nk2(a){if(typeof\na===\"number\")return cu;else if(dX(a))return dC;else if(dY(a))return 1252;else if(a\ninstanceof\nArray&&a[0]===a[0]>>>0&&a[0]<=jS){var\nb=a[0]|0;return b==dG?0:b}else if(a\ninstanceof\nString)return jk;else if(typeof\na==\"string\")return jk;else if(a\ninstanceof\nNumber)return cu;else if(a&&a.caml_custom)return fX;else if(a&&a.compare)return 1256;else if(typeof\na==\"function\")return 1247;else if(typeof\na==\"symbol\")return 1251;return 1001}function\nk_(a,b){if(ab?1:0}function\nzv(a,b){a.t&6&&cz(a);b.t&6&&cz(b);return a.cb.c?1:0}function\ndR(a,b,c){var\nf=[];for(;;){if(!(c&&a===b)){var\ne=k2(a);if(e==aD){a=a[1];continue}var\ng=k2(b);if(g==aD){b=b[1];continue}if(e!==g){if(e==cu){if(g==fX)return k1(a,b,-1,c);return-1}if(g==cu){if(e==fX)return k1(b,a,1,c);return 1}return eb)return 1;if(a!=b){if(!c)return NaN;if(a==a)return 1;if(b==b)return-1}break;case\n1001:if(ab)return 1;if(a!=b){if(!c)return NaN;if(a==a)return 1;if(b==b)return-1}break;case\n1251:if(a!==b){if(!c)return NaN;return 1}break;case\n1252:var\na=aJ(a),b=aJ(b);if(a!==b){if(ab)return 1}break;case\n12520:var\na=a.toString(),b=b.toString();if(a!==b){if(ab)return 1}break;case\n246:case\n254:default:if(la(e)){G(\"compare: continuation value\");break}if(a.length!=b.length)return a.length1)f.push(a,b,1);break}}if(f.length==0)return 0;var\nh=f.pop();b=f.pop();a=f.pop();if(h+10)if(b==0&&(c>=a.l||a.t==2&&c>=a.c.length))if(d==0){a.c=e;a.t=2}else{a.c=b1(c,String.fromCharCode(d));a.t=c==a.l?0:2}else{if(a.t!=4)dS(a);for(c+=b;b0&&b===b)return b;a=a.replace(/_/g,e);b=+a;if(a.length>0&&b===b||/^[+-]?nan$/i.test(a))return b;var\nc=/^ *([+-]?)0x([0-9a-f]+)\\.?([0-9a-f]*)(p([+-]?[0-9]+))?/i.exec(a);if(c){var\nd=c[3].replace(/0+$/,e),g=parseInt(c[1]+c[2]+d,16),f=(c[5]|0)-4*d.length;b=g*Math.pow(2,f);return b}if(/^\\+?inf(inity)?$/i.test(a))return Infinity;if(/^-inf(inity)?$/i.test(a))return-Infinity;aj(\"float_of_string\")}function\ngk(a){a=aJ(a);var\ne=a.length;if(e>31)G(\"format_int: format too long\");var\nb={justify:bV,signstyle:bs,filler:aE,alternate:false,base:0,signedconv:false,width:0,uppercase:false,sign:1,prec:-1,conv:\"f\"};for(var\nd=0;d=0&&c<=9){b.width=b.width*10+c;d++}d--;break;case\".\":b.prec=0;d++;while(c=a.charCodeAt(d)-48,c>=0&&c<=9){b.prec=b.prec*10+c;d++}d--;case\"d\":case\"i\":b.signedconv=true;case\"u\":b.base=10;break;case\"x\":b.base=16;break;case\"X\":b.base=16;b.uppercase=true;break;case\"o\":b.base=8;break;case\"e\":case\"f\":case\"g\":b.signedconv=true;b.conv=c;break;case\"E\":case\"F\":case\"G\":b.signedconv=true;b.uppercase=true;b.conv=c.toLowerCase();break}}return b}function\nf$(a,b){if(a.uppercase)b=b.toUpperCase();var\nf=b.length;if(a.signedconv&&(a.sign<0||a.signstyle!=bs))f++;if(a.alternate){if(a.base==8)f+=1;if(a.base==16)f+=2}var\nc=e;if(a.justify==bV&&a.filler==aE)for(var\nd=f;d20){c-=20;a/=Math.pow(10,c);a+=new\nArray(c+1).join(ad);if(b>0)a=a+a$+new\nArray(b+1).join(ad);return a}else\nreturn a.toFixed(b)}}var\nc,f=gk(a),e=f.prec<0?6:f.prec;if(b<0||b==0&&1/b==-Infinity){f.sign=-1;b=-b}if(isNaN(b)){c=fG;f.filler=aE}else if(!isFinite(b)){c=\"inf\";f.filler=aE}else\nswitch(f.conv){case\"e\":var\nc=b.toExponential(e),d=c.length;if(c.charAt(d-3)==fP)c=c.slice(0,d-1)+ad+c.slice(d-1);break;case\"f\":c=j(b,e);break;case\"g\":e=e?e:1;c=b.toExponential(e-1);var\ni=c.indexOf(fP),h=+c.slice(i+1);if(h<-4||b>=1e21||b.toFixed(0).length>e){var\nd=i-1;while(c.charAt(d)==ad)d--;if(c.charAt(d)==a$)d--;c=c.slice(0,d+1)+c.slice(i);d=c.length;if(c.charAt(d-3)==fP)c=c.slice(0,d-1)+ad+c.slice(d-1);break}else{var\ng=e;if(h<0){g-=h+1;c=b.toFixed(g)}else\nwhile(c=b.toFixed(g),c.length>e+1)g--;if(g){var\nd=c.length-1;while(c.charAt(d)==ad)d--;if(c.charAt(d)==a$)d--;c=c.slice(0,d+1)}}break}return f$(f,c)}function\ndT(a,b){if(aJ(a)==fA)return ak(e+b);var\nc=gk(a);if(b<0)if(c.signedconv){c.sign=-1;b=-b}else\nb>>>=0;var\nd=b.toString(c.base);if(c.prec>=0){c.filler=aE;var\nf=c.prec-d.length;if(f>0)d=b1(f,ad)+d}return f$(c,d)}var\nAh=0;function\nae(){return Ah++}function\nH(a){if(gq(a))return a;return lo(a)}function\ncF(){return typeof\np.process!==\"undefined\"&&typeof\np.process.versions!==\"undefined\"&&typeof\np.process.versions.node!==\"undefined\"}function\nAu(){function\na(a){if(a.charAt(0)===aH)return[e,a.substring(1)];return}function\nb(a){var\nh=/^([a-zA-Z]:|[\\\\/]{2}[^\\\\/]+[\\\\/]+[^\\\\/]+)?([\\\\/])?([\\s\\S]*?)$/,b=h.exec(a),c=b[1]||e,f=Boolean(c&&c.charAt(1)!==\":\");if(Boolean(b[2]||f)){var\nd=b[1]||e,g=b[2]||e;return[d,a.substring(d.length+g.length)]}return}return cF()&&p.process&&p.process.platform?p.process.platform===\"win32\"?b:a:a}var\ngr=Au();function\nlm(a){return a.slice(-1)!==aH?a+aH:a}if(cF()&&p.process&&p.process.cwd)var\ncA=p.process.cwd().replace(/\\\\/g,aH);else\nvar\ncA=\"/static\";cA=lm(cA);function\nz6(a){a=H(a);if(!gr(a))a=cA+a;var\ne=gr(a),d=e[1].split(aH),b=[];for(var\nc=0;c1)b.pop();break;case\".\":break;case\"\":break;default:b.push(d[c]);break}b.unshift(e[0]);b.orig=a;return b}function\nAr(a){for(var\ng=e,c=g,b,i,d=0,h=a.length;ddF){c.substr(0,1);g+=c;c=e;g+=a.slice(d,f)}else\nc+=a.slice(d,f);if(f==h)break;d=f}if(b>6);c+=String.fromCharCode(ao|b&bb)}else if(b<0xd800||b>=jF)c+=String.fromCharCode(kH|b>>12,ao|b>>6&bb,ao|b&bb);else if(b>=0xdbff||d+1==h||(i=a.charCodeAt(d+1))jF)c+=\"\\xef\\xbf\\xbd\";else{d++;b=(b<<10)+i-0x35fdc00;c+=String.fromCharCode(j0|b>>18,ao|b>>12&bb,ao|b>>6&bb,ao|b&bb)}if(c.length>ct){c.substr(0,1);g+=c;c=e}}return g+c}function\nas(a){return gq(a)?ak(a):ak(Ar(a))}var\nAv=[\"E2BIG\",\"EACCES\",\"EAGAIN\",fz,\"EBUSY\",\"ECHILD\",\"EDEADLK\",\"EDOM\",kG,\"EFAULT\",\"EFBIG\",\"EINTR\",\"EINVAL\",\"EIO\",\"EISDIR\",\"EMFILE\",\"EMLINK\",\"ENAMETOOLONG\",\"ENFILE\",\"ENODEV\",fO,\"ENOEXEC\",\"ENOLCK\",\"ENOMEM\",\"ENOSPC\",\"ENOSYS\",fT,ki,\"ENOTTY\",\"ENXIO\",\"EPERM\",\"EPIPE\",\"ERANGE\",\"EROFS\",\"ESPIPE\",\"ESRCH\",\"EXDEV\",\"EWOULDBLOCK\",\"EINPROGRESS\",\"EALREADY\",\"ENOTSOCK\",\"EDESTADDRREQ\",\"EMSGSIZE\",\"EPROTOTYPE\",\"ENOPROTOOPT\",\"EPROTONOSUPPORT\",\"ESOCKTNOSUPPORT\",\"EOPNOTSUPP\",\"EPFNOSUPPORT\",\"EAFNOSUPPORT\",\"EADDRINUSE\",\"EADDRNOTAVAIL\",\"ENETDOWN\",\"ENETUNREACH\",\"ENETRESET\",\"ECONNABORTED\",\"ECONNRESET\",\"ENOBUFS\",\"EISCONN\",\"ENOTCONN\",\"ESHUTDOWN\",\"ETOOMANYREFS\",\"ETIMEDOUT\",\"ECONNREFUSED\",\"EHOSTDOWN\",\"EHOSTUNREACH\",\"ELOOP\",\"EOVERFLOW\"];function\na2(a,b,c,d){var\nf=Av.indexOf(a);if(f<0){if(d==null)d=-9999;f=[0,d]}var\ng=[f,as(b||e),as(c||e)];return g}var\nlg={};function\nbg(a){return lg[a]}function\na1(a,b){throw g([0,a].concat(b))}function\nf9(a){if(!(a\ninstanceof\nUint8Array))a=new\nUint8Array(a);return new\naY(4,a,a.length)}function\nm(a){gl(U.Sys_error,a)}function\nlj(a){m(a+dL)}function\ngp(a){if(a.t!=4)dS(a);return a.c}function\naq(a){return a.l}function\nkT(){}function\nY(a){this.data=a}Y.prototype=new\nkT();Y.prototype.constructor=Y;Y.prototype.truncate=function(a){var\nb=this.data;this.data=F(a|0);aZ(b,0,this.data,0,a)};Y.prototype.length=function(){return aq(this.data)};Y.prototype.write=function(a,b,c,d){var\ne=this.length();if(a+d>=e){var\nf=F(a+d),g=this.data;this.data=f;aZ(g,0,this.data,0,e)}aZ(f9(b),c,this.data,a,d);return 0};Y.prototype.read=function(a,b,c,d){var\ne=this.length();if(a+d>=e)d=e-a;if(d){var\nf=F(d|0);aZ(this.data,a,f,0,d);b.set(gp(f),c)}return d};function\nbw(a,b,c){this.file=b;this.name=a;this.flags=c}bw.prototype.err_closed=function(){m(this.name+jm)};bw.prototype.length=function(){if(this.file)return this.file.length();this.err_closed()};bw.prototype.write=function(a,b,c,d){if(this.file)return this.file.write(a,b,c,d);this.err_closed()};bw.prototype.read=function(a,b,c,d){if(this.file)return this.file.read(a,b,c,d);this.err_closed()};bw.prototype.close=function(){this.file=undefined};function\nN(a,b){this.content={};this.root=a;this.lookupFun=b}N.prototype.nm=function(a){return this.root+a};N.prototype.create_dir_if_needed=function(a){var\nd=a.split(aH),c=e;for(var\nb=0;b>>16;a=cC(a,0x85ebca6b|0);a^=a>>>13;a=cC(a,0xc2b2ae35|0);a^=a>>>16;return a}function\nzH(a,b,c,d){var\nj,k,l,h,g,f,e,i,m;h=b;if(h<0||h>cv)h=cv;g=a;f=c;j=[d];k=0;l=1;while(k0){e=j[k++];if(e&&e.caml_custom){if(cB[e.caml_custom]&&cB[e.caml_custom].hash){var\nn=cB[e.caml_custom].hash(e);f=V(f,n);g--}}else if(e\ninstanceof\nArray&&e[0]===(e[0]|0))switch(e[0]){case\n248:f=V(f,e[2]);g--;break;case\n250:j[--k]=e[1];break;default:if(la(e[0]))break;var\no=e.length-1<<10|e[0];f=V(f,o);for(i=1,m=e.length;i=h)break;j[l++]=e[i]}break}else if(dX(e)){f=zI(f,e);g--}else if(dY(e)){f=zM(f,e);g--}else if(typeof\ne===\"string\"){f=gc(f,e);g--}else if(e===(e|0)){f=V(f,e+e+1);g--}else if(typeof\ne===\"number\"){f=gb(f,e);g--}}f=zK(f);return f&0x3FFFFFFF}function\nzN(a,b,c){if(!isFinite(a)){if(isNaN(a))return as(fG);return as(a>0?j4:\"-infinity\")}var\nk=a==0&&1/a==-Infinity?1:a>=0?0:1;if(k)a=-a;var\nf=0;if(a==0);else if(a<1)while(a<1&&f>-1022){a*=2;f--}else\nwhile(a>=2){a/=2;f++}var\nl=f<0?e:bV,g=e;if(k)g=bs;else\nswitch(c){case\n43:g=bV;break;case\n32:g=aE;break;default:break}if(b>=0&&b<13){var\ni=Math.pow(2,b*4);a=Math.round(a*i)/i}var\nd=a.toString(16);if(b>=0){var\nj=d.indexOf(a$);if(j<0)d+=a$+b1(b,ad);else{var\nh=j+1+b;if(d.length>24&aV,a>>31&aI)}function\nzY(a){return a.toInt()}function\nzU(a){return+a.isNeg()}function\nzX(a){return a.neg()}function\nzS(a,b){var\nc=gk(a);if(c.signedconv&&zU(b)){c.sign=-1;b=zX(b)}var\nd=e,i=dW(c.base),h=\"0123456789abcdef\";do{var\ng=b.udivmod(i);b=g.quotient;d=h.charAt(zY(g.modulus))+d}while(!zV(b));if(c.prec>=0){c.filler=aE;var\nf=c.prec-d.length;if(f>0)d=b1(f,ad)+d}return f$(c,d)}function\nk8(a,b){return a.or(b)}function\nk9(a,b){return a.shift_left(b)}function\ngi(a,b){return a.shift_right_unsigned(b)}function\nAi(a){var\nb=0,e=n(a),c=10,d=1;if(e>0)switch(_(a,b)){case\n45:b++;d=-1;break;case\n43:b++;d=1;break}if(b+1=48&&a<=57)return a-48;if(a>=65&&a<=90)return a-55;if(a>=97&&a<=122)return a-87;return-1}function\nk$(a){var\nh=Ai(a),d=h[0],i=h[1],e=h[2],g=n(a),j=-1>>>0,f=d=e)aj(dO);var\nb=c;for(d++;d=e)break;b=e*b+c;if(b>j)aj(dO)}if(d!=g)aj(dO);b=i*b;if(e==10&&(b|0)!=b)aj(dO);return b|0}function\nlb(a){return a.slice(1)}function\ndZ(a,b,c){return a[H(b)].apply(a,lb(c))}function\nz1(a,b){switch(b.length){case\n1:return new\na;case\n2:return new\na(b[1]);case\n3:return new\na(b[1],b[2]);case\n4:return new\na(b[1],b[2],b[3]);case\n5:return new\na(b[1],b[2],b[3],b[4]);case\n6:return new\na(b[1],b[2],b[3],b[4],b[5]);case\n7:return new\na(b[1],b[2],b[3],b[4],b[5],b[6]);case\n8:return new\na(b[1],b[2],b[3],b[4],b[5],b[6],b[7])}function\nc(){return a.apply(this,lb(b))}c.prototype=a.prototype;return new\nc}function\nlc(a){var\nc={};for(var\nb=1;b>>32-e,c)}function\ng(a,b,c,d,e,f,g){return l(b&c|~b&d,a,b,e,f,g)}function\nh(a,b,c,d,e,f,g){return l(b&d|c&~d,a,b,e,f,g)}function\ni(a,b,c,d,e,f,g){return l(b^c^d,a,b,e,f,g)}function\nj(a,b,c,d,e,f,g){return l(c^(b|~d),a,b,e,f,g)}return function(a,b){var\nc=a[0],d=a[1],e=a[2],f=a[3];c=g(c,d,e,f,b[0],7,0xD76AA478);f=g(f,c,d,e,b[1],12,0xE8C7B756);e=g(e,f,c,d,b[2],17,0x242070DB);d=g(d,e,f,c,b[3],22,0xC1BDCEEE);c=g(c,d,e,f,b[4],7,0xF57C0FAF);f=g(f,c,d,e,b[5],12,0x4787C62A);e=g(e,f,c,d,b[6],17,0xA8304613);d=g(d,e,f,c,b[7],22,0xFD469501);c=g(c,d,e,f,b[8],7,0x698098D8);f=g(f,c,d,e,b[9],12,0x8B44F7AF);e=g(e,f,c,d,b[10],17,0xFFFF5BB1);d=g(d,e,f,c,b[11],22,0x895CD7BE);c=g(c,d,e,f,b[12],7,0x6B901122);f=g(f,c,d,e,b[13],12,0xFD987193);e=g(e,f,c,d,b[14],17,0xA679438E);d=g(d,e,f,c,b[15],22,0x49B40821);c=h(c,d,e,f,b[1],5,0xF61E2562);f=h(f,c,d,e,b[6],9,0xC040B340);e=h(e,f,c,d,b[11],14,0x265E5A51);d=h(d,e,f,c,b[0],20,0xE9B6C7AA);c=h(c,d,e,f,b[5],5,0xD62F105D);f=h(f,c,d,e,b[10],9,0x02441453);e=h(e,f,c,d,b[15],14,0xD8A1E681);d=h(d,e,f,c,b[4],20,0xE7D3FBC8);c=h(c,d,e,f,b[9],5,0x21E1CDE6);f=h(f,c,d,e,b[14],9,0xC33707D6);e=h(e,f,c,d,b[3],14,0xF4D50D87);d=h(d,e,f,c,b[8],20,0x455A14ED);c=h(c,d,e,f,b[13],5,0xA9E3E905);f=h(f,c,d,e,b[2],9,0xFCEFA3F8);e=h(e,f,c,d,b[7],14,0x676F02D9);d=h(d,e,f,c,b[12],20,0x8D2A4C8A);c=i(c,d,e,f,b[5],4,0xFFFA3942);f=i(f,c,d,e,b[8],11,0x8771F681);e=i(e,f,c,d,b[11],16,0x6D9D6122);d=i(d,e,f,c,b[14],23,0xFDE5380C);c=i(c,d,e,f,b[1],4,0xA4BEEA44);f=i(f,c,d,e,b[4],11,0x4BDECFA9);e=i(e,f,c,d,b[7],16,0xF6BB4B60);d=i(d,e,f,c,b[10],23,0xBEBFBC70);c=i(c,d,e,f,b[13],4,0x289B7EC6);f=i(f,c,d,e,b[0],11,0xEAA127FA);e=i(e,f,c,d,b[3],16,0xD4EF3085);d=i(d,e,f,c,b[6],23,0x04881D05);c=i(c,d,e,f,b[9],4,0xD9D4D039);f=i(f,c,d,e,b[12],11,0xE6DB99E5);e=i(e,f,c,d,b[15],16,0x1FA27CF8);d=i(d,e,f,c,b[2],23,0xC4AC5665);c=j(c,d,e,f,b[0],6,0xF4292244);f=j(f,c,d,e,b[7],10,0x432AFF97);e=j(e,f,c,d,b[14],15,0xAB9423A7);d=j(d,e,f,c,b[5],21,0xFC93A039);c=j(c,d,e,f,b[12],6,0x655B59C3);f=j(f,c,d,e,b[3],10,0x8F0CCC92);e=j(e,f,c,d,b[10],15,0xFFEFF47D);d=j(d,e,f,c,b[1],21,0x85845DD1);c=j(c,d,e,f,b[8],6,0x6FA87E4F);f=j(f,c,d,e,b[15],10,0xFE2CE6E0);e=j(e,f,c,d,b[6],15,0xA3014314);d=j(d,e,f,c,b[13],21,0x4E0811A1);c=j(c,d,e,f,b[4],6,0xF7537E82);f=j(f,c,d,e,b[11],10,0xBD3AF235);e=j(e,f,c,d,b[2],15,0x2AD7D2BB);d=j(d,e,f,c,b[9],21,0xEB86D391);a[0]=k(c,a[0]);a[1]=k(d,a[1]);a[2]=k(e,a[2]);a[3]=k(f,a[3])}}();function\nzp(a,b,c){var\ne=a.len&bb,d=0;a.len+=c;if(e){var\nf=64-e;if(c=64){a.b8.set(b.subarray(d,d+64),0);dP(a.w,a.b32);c-=64;d+=64}if(c)a.b8.set(b.subarray(d,d+c),0)}function\nzn(a){var\nc=a.len&bb;a.b8[c]=ao;c++;if(c>56){for(var\nb=c;b<64;b++)a.b8[b]=0;dP(a.w,a.b32);for(var\nb=0;b<56;b++)a.b8[b]=0}else\nfor(var\nb=c;b<56;b++)a.b8[b]=0;a.b32[14]=a.len<<3;a.b32[15]=a.len>>29&0x1FFFFFFF;dP(a.w,a.b32);var\ne=new\nUint8Array(16);for(var\nd=0;d<4;d++)for(var\nb=0;b<4;b++)e[d*4+b]=a.w[d]>>8*b&0xFF;return e}function\nAn(a){return ak(cE(a,0,a.length))}function\nz7(a,b,c){var\nd=zo(),e=gp(a);zp(d,e.subarray(b,b+c),c);return An(zn(d))}function\nz8(a,b,c){return z7(bd(a),b,c)}function\nz_(){return 0}var\nbf=new\nArray();function\nld(a){return bf[a]}function\nbz(a){var\nb=ld(a);if(!b.opened)m(\"Cannot flush a closed channel\");if(!b.buffer||b.buffer_curr==0)return 0;if(b.output)b.output(cE(b.buffer,0,b.buffer_curr));else\nb.file.write(b.offset,b.buffer,0,b.buffer_curr);b.offset+=b.buffer_curr;b.buffer_curr=0;return 0}function\nAp(a,b){if(b.name)try{var\nd=require(fH),c=d.openSync(b.name,\"rs\");return new\nav(c,b)}catch(f){}return new\nav(a,b)}var\nd2=new\nArray(3);function\ncw(a,b){Y.call(this,F(0));this.log=function(a){return 0};if(a==1&&typeof\nconsole.log==\"function\")this.log=console.log;else if(a==2&&typeof\nconsole.error==\"function\")this.log=console.error;else if(typeof\nconsole.log==\"function\")this.log=console.log;this.flags=b}cw.prototype.length=function(){return 0};cw.prototype.write=function(a,b,c,d){if(this.log){if(d>0&&c>=0&&c+d<=b.length&&b[c+d-1]==10)d--;var\ne=F(d);aZ(f9(b),c,e,0,d);this.log(e.toUtf16());return 0}m(this.fd+jm)};cw.prototype.read=function(a,b,c,d){m(this.fd+\": file descriptor is write only\")};cw.prototype.close=function(){this.log=undefined};function\nd3(a,b){if(b==undefined)b=d2.length;d2[b]=a;return b|0}function\nAx(a,b,c){var\nd={};while(b){switch(b[1]){case\n0:d.rdonly=1;break;case\n1:d.wronly=1;break;case\n2:d.append=1;break;case\n3:d.create=1;break;case\n4:d.truncate=1;break;case\n5:d.excl=1;break;case\n6:d.binary=1;break;case\n7:d.text=1;break;case\n8:d.nonblock=1;break}b=b[2]}if(d.rdonly&&d.wronly)m(aJ(a)+f5);if(d.text&&d.binary)m(aJ(a)+fE);var\ne=lr(a),f=e.device.open(e.rest,d);return d3(f,undefined)}(function(){function\na(a,b){return cF()?Ap(a,b):new\ncw(a,b)}d3(a(0,{rdonly:1,altname:\"/dev/stdin\",isCharacterDevice:true}),0);d3(a(1,{buffered:2,wronly:1,isCharacterDevice:true}),1);d3(a(2,{buffered:2,wronly:1,isCharacterDevice:true}),2)}());function\nz$(a){var\nb=d2[a];if(b.flags.wronly)m(j3+a+\" is writeonly\");var\nd=null,c={file:b,offset:b.flags.append?b.length():0,fd:a,opened:true,out:false,buffer_curr:0,buffer_max:0,buffer:new\nUint8Array(j5),refill:d};bf[c.fd]=c;return c.fd}function\nle(a){var\nb=d2[a];if(b.flags.rdonly)m(j3+a+\" is readonly\");var\nd=b.flags.buffered!==undefined?b.flags.buffered:1,c={file:b,offset:b.flags.append?b.length():0,fd:a,opened:true,out:true,buffer_curr:0,buffer:new\nUint8Array(j5),buffered:d};bf[c.fd]=c;return c.fd}function\nAa(){var\nb=0;for(var\na=0;ae.buffer.length){var\ng=new\nUint8Array(e.buffer_curr+b.length);g.set(e.buffer);e.buffer=g}switch(e.buffered){case\n0:e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;bz(a);break;case\n1:e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;if(e.buffer_curr>=e.buffer.length)bz(a);break;case\n2:var\nf=b.lastIndexOf(10);if(f<0){e.buffer.set(b,e.buffer_curr);e.buffer_curr+=b.length;if(e.buffer_curr>=e.buffer.length)bz(a)}else{e.buffer.set(b.subarray(0,f+1),e.buffer_curr);e.buffer_curr+=f+1;bz(a);e.buffer.set(b.subarray(f+1),e.buffer_curr);e.buffer_curr+=b.length-f-1}break}return 0}function\nAb(a,b,c,d){var\nb=gp(b);return Ac(a,b,c,d)}function\ngj(a,b,c,d){return Ab(a,bd(b),c,d)}function\nlf(a,b){var\nc=ak(String.fromCharCode(b));gj(a,c,0,1);return 0}function\nAd(a,b){if(b==0)gm();return a%b}function\ncD(a,b){return+(dR(a,b,false)!=0)}function\nAf(a,b){var\nd=new\nArray(b+1);d[0]=a;for(var\nc=1;c<=b;c++)d[c]=0;return d}function\nAg(a,b){a[0]=aD;a[1]=b;return 0}function\naw(a){if(a\ninstanceof\nArray&&a[0]==a[0]>>>0)return a[0];else if(dX(a))return dC;else if(dY(a))return dC;else if(a\ninstanceof\nFunction||typeof\na==\"function\")return 247;else if(a&&a.caml_custom)return jS;else\nreturn cu}function\nzu(a){var\nc={};if(a)for(var\nb=1;b=0)a=e;else\naj(\"caml_register_global: cannot locate \"+d)}}U[a+1]=b;if(c)U[c]=b}function\ngo(a,b){lg[aJ(a)]=b;return 0}function\nAm(){G(fC)}function\ny(a,b){if(b>>>0>=n(a))Am();return _(a,b)}function\nd1(a){a.t&6&&cz(a);return ak(a.c)}function\nAo(){return 0x7FFFFFFF/4|0}function\nAj(){li(U.Not_found)}function\nll(a){var\nb=lq(H(a));if(b===undefined)Aj();return as(b)}function\nAq(){if(p.crypto)if(p.crypto.getRandomValues){var\na=p.crypto.getRandomValues(new\nInt32Array(4));return[0,a[0],a[1],a[2],a[3]]}else if(p.crypto.randomBytes){var\na=new\nInt32Array(p.crypto.randomBytes(16).buffer);return[0,a[0],a[1],a[2],a[3]]}var\nb=new\nDate().getTime(),c=b^0xffffffff*Math.random();return[0,c]}function\nbA(a){var\nb=1;while(a&&a.joo_tramp){a=a.joo_tramp.apply(null,a.joo_args);b++}return a}function\nr(a,b){return{joo_tramp:a,joo_args:b}}function\nln(a,b){if(b.fun){a.fun=b.fun;return 0}if(typeof\nb===\"function\"){a.fun=b;return 0}var\nc=b.length;while(c--)a[c]=b[c];return 0}function\nL(a){{if(a\ninstanceof\nArray)return a;var\nb;if(p.RangeError&&a\ninstanceof\np.RangeError&&a.message&&a.message.match(/maximum call stack/i))b=U.Stack_overflow;else if(p.InternalError&&a\ninstanceof\np.InternalError&&a.message&&a.message.match(/too much recursion/i))b=U.Stack_overflow;else if(a\ninstanceof\np.Error&&bg(fV))b=[0,bg(fV),a];else\nb=[0,U.Failure,as(String(a))];if(a\ninstanceof\np.Error)b.js_error=a;return b}}function\nz0(a){switch(a[2]){case-8:case-11:case-12:return 1;default:return 0}}function\nzE(a){var\nb=e;if(a[0]==0){b+=a[1][1];if(a.length==3&&a[2][0]==0&&z0(a[1]))var\nf=a[2],g=1;else\nvar\ng=2,f=a;b+=\"(\";for(var\nd=g;dg)b+=jx;var\nc=f[d];if(typeof\nc==\"number\")b+=c.toString();else if(c\ninstanceof\naY)b+=dB+c.toString()+dB;else if(typeof\nc==\"string\")b+=dB+c.toString()+dB;else\nb+=ku}b+=\")\"}else if(a[0]==q)b+=a[1];return b}function\nk4(a){if(a\ninstanceof\nArray&&(a[0]==0||a[0]==q)){var\nc=bg(ky);if(c)dQ(c,[a,false]);else{var\nd=zE(a),b=bg(j6);if(b)dQ(b,[0]);console.error(fY+d);if(a.js_error)throw a.js_error}}else\nthrow a}function\nAl(){var\nc=p.process;if(c&&c.on)c.on(\"uncaughtException\",function(a,b){k4(a);c.exit(2)});else if(p.addEventListener)p.addEventListener(jq,function(a){if(a.error)k4(a.error)})}Al();function\nh(a,b){return(a.l>=0?a.l:a.l=a.length)==1?a(b):be(a,[b])}function\ni(a,b,c){return(a.l>=0?a.l:a.l=a.length)==2?a(b,c):be(a,[b,c])}function\nx(a,b,c,d){return(a.l>=0?a.l:a.l=a.length)==3?a(b,c,d):be(a,[b,c,d])}function\nfx(a,b,c,d,e,f){return(a.l>=0?a.l:a.l=a.length)==5?a(b,c,d,e,f):be(a,[b,c,d,e,f])}function\nzm(a,b,c,d,e,f,g,h){return(a.l>=0?a.l:a.l=a.length)==7?a(b,c,d,e,f,g,h):be(a,[b,c,d,e,f,g,h])}var\nAw=undefined;zF();var\nd6=[q,kP,-1],gu=[q,jZ,-2],b3=[q,f6,-3],cH=[q,jA,-4],ax=[q,jD,-7],gs=[q,kL,-8],gt=[q,kh,-9],f=[q,kq,-11],b4=[q,kD,-12],zl=[4,0,0,0,[12,45,[4,0,0,0,0]]],es=[0,[11,'File \"',[2,0,[11,'\", line ',[4,0,0,0,[11,kN,[4,0,0,0,[12,45,[4,0,0,0,[11,kJ,[2,0,0]]]]]]]]]],'File \"%s\", line %d, characters %d-%d: %s'],i3=f4,br=\"content\",i9=\"columns\",i_=\"rows\",fr=jQ,fs=f4,i$=cq,ja=\"page_content\";ar(11,b4,kD);ar(10,f,kq);ar(9,[q,kv,-10],kv);ar(8,gt,kh);ar(7,gs,kL);ar(6,ax,jD);ar(5,[q,jV,-6],jV);ar(4,[q,j9,-5],j9);ar(3,cH,jA);ar(2,b3,f6);ar(1,gu,jZ);ar(0,d6,kP);var\nlB=\"output_substring\",lx=a$,lu=\"true\",lv=\"false\",lF=\"CamlinternalLazy.Undefined\",lJ=\"option is None\",lM=\"\\\\\\\\\",lN=\"\\\\'\",lO=\"\\\\b\",lP=\"\\\\t\",lQ=\"\\\\n\",lR=\"\\\\r\",lZ=\"List.init\",lW=\"hd\",l_=\"String.blit / Bytes.blit_string\",l9=\"Bytes.blit\",l8=\"String.sub / Bytes.sub\",mh=\"String.contains_from / Bytes.contains_from\",mo=\"Array.blit\",mn=\"Array.sub\",ml=\"Array.init\",mv=[0,\"set.ml\",570,18],mr=dI,ms=dI,mt=dI,mu=dI,mC=\"Map.remove_min_elt\",my=dM,mz=dM,mA=dM,mB=dM,mD=\"Stdlib.Stack.Empty\",mH=\"Stdlib.Queue.Empty\",mT=\"Buffer.add_substring/add_subbytes\",mQ=\"Buffer.add: cannot grow buffer\",mP=[0,jg,93,2],mO=[0,jg,94,2],mM=\"Buffer.sub\",m4=\"%c\",m5=\"%s\",m6=jH,m7=jv,m8=kR,m9=jB,m_=\"%f\",m$=\"%B\",na=\"%{\",nb=\"%}\",nc=\"%(\",nd=\"%)\",ne=\"%a\",nf=\"%t\",ng=\"%?\",nh=\"%r\",ni=\"%_r\",nj=[0,K,850,23],nu=[0,K,814,21],nm=[0,K,815,21],nv=[0,K,818,21],nn=[0,K,819,21],nw=[0,K,822,19],no=[0,K,823,19],nx=[0,K,826,22],np=[0,K,827,22],ny=[0,K,831,30],nq=[0,K,832,30],ns=[0,K,836,26],nk=[0,K,837,26],nt=[0,K,846,28],nl=[0,K,847,28],nr=[0,K,851,23],oK=[0,K,1558,4],oL=\"Printf: bad conversion %[\",oM=[0,K,1626,39],oN=[0,K,1649,31],oO=[0,K,1650,31],oP=\"Printf: bad conversion %_\",oQ=jU,oR=kt,oS=jU,oT=kt,oX=[0,[11,\"invalid box description \",[3,0,0]],\"invalid box description %S\"],oW=[0,0,4],oF=fG,oD=\"neg_infinity\",oE=j4,oC=a$,ox=[0,ji],ol=\"%+nd\",om=\"% nd\",oo=\"%+ni\",op=\"% ni\",oq=\"%nx\",or=\"%#nx\",os=\"%nX\",ot=\"%#nX\",ou=\"%no\",ov=\"%#no\",ok=\"%nd\",on=kR,ow=\"%nu\",n9=\"%+ld\",n_=\"% ld\",oa=\"%+li\",ob=\"% li\",oc=\"%lx\",od=\"%#lx\",oe=\"%lX\",of=\"%#lX\",og=\"%lo\",oh=\"%#lo\",n8=\"%ld\",n$=jv,oi=\"%lu\",nV=\"%+Ld\",nW=\"% Ld\",nY=\"%+Li\",nZ=\"% Li\",n0=\"%Lx\",n1=\"%#Lx\",n2=\"%LX\",n3=\"%#LX\",n4=\"%Lo\",n5=\"%#Lo\",nU=\"%Ld\",nX=jB,n6=\"%Lu\",nH=\"%+d\",nI=\"% d\",nK=\"%+i\",nL=\"% i\",nM=\"%x\",nN=\"%#x\",nO=\"%X\",nP=\"%#X\",nQ=\"%o\",nR=\"%#o\",nG=fA,nJ=jH,nS=ka,mW=\"@]\",mX=\"@}\",mY=\"@?\",mZ=\"@\\n\",m0=\"@.\",m1=\"@@\",m2=\"@%\",m3=\"@\",nz=\"CamlinternalFormat.Type_mismatch\",o2=e,o3=[0,[11,jx,[2,0,[2,0,0]]],\", %s%s\"],pz=[0,[11,fY,[2,0,[12,10,0]]],ke],pA=[0,[11,\"Fatal error in uncaught exception handler: exception \",[2,0,[12,10,0]]],\"Fatal error in uncaught exception handler: exception %s\\n\"],py=\"Fatal error: out of memory in uncaught exception handler\",pv=[0,[11,fY,[2,0,[12,10,0]]],ke],pp=[0,[2,0,[12,10,0]],\"%s\\n\"],pq=[0,[11,jT,0],jT],pg=\"Raised at\",ph=\"Re-raised at\",pi=\"Raised by primitive operation at\",pj=\"Called from\",pk=\" (inlined)\",pm=e,pl=[0,[2,0,[12,32,[2,0,[11,' in file \"',[2,0,[12,34,[2,0,[11,\", line \",[4,0,0,0,[11,kN,zl]]]]]]]]]],'%s %s in file \"%s\"%s, line %d, characters %d-%d'],pn=[0,[2,0,[11,\" unknown location\",0]],\"%s unknown location\"],o$=\"Out of memory\",pa=\"Stack overflow\",pb=\"Pattern matching failed\",pc=\"Assertion failed\",pd=\"Undefined recursive module\",o5=[0,[12,40,[2,0,[2,0,[12,41,0]]]],\"(%s%s)\"],o6=e,o7=e,o8=[0,[12,40,[2,0,[12,41,0]]],\"(%s)\"],o1=[0,[4,0,0,0,0],fA],oZ=[0,[3,0,0],\"%S\"],o0=ku,ps=[0,e,\"(Cannot print locations:\\n bytecode executable program file not found)\",\"(Cannot print locations:\\n bytecode executable program file appears to be corrupt)\",\"(Cannot print locations:\\n bytecode executable program file has wrong magic number)\",\"(Cannot print locations:\\n bytecode executable program file cannot be opened;\\n -- too many open files. Try running with OCAMLRUNPARAM=b=2)\"],pE=\"Fun.Finally_raised: \",pC=\"Stdlib.Fun.Finally_raised\",pI=\"x\",pP=\"Hashtbl: unsupported hash table format\",pL=e,qA=[3,0,3],qB=a$,qu=kw,qv=\"<\\/\",qw=e,qq=kw,qr=\"<\",qs=e,qo=\"\\n\",qj=e,qk=e,ql=e,qm=e,p7=[0,e],p2=e,p3=e,p4=e,p5=e,pY=[0,e,0,e],pU=\"Stdlib.Format.String_tag\",qN=[0,j$,72,5],qO=[0,j$,81,2],qP=\"CamlinternalMod.update_mod: not a module\",qL=\"CamlinternalMod.init_mod: not a module\",qQ=\"Jsoo_runtime.Error.Exn\",qR=fV,qV=[0,b,ju,10],qX=[0,b,179,10],qZ=[0,b,191,10],q2=[0,b,kQ,17],q$=[0,b,367,16],ra=[0,b,368,18],rb=[0,b,372,15],rc=[0,b,377,15],rd=[0,b,kz,15],re=[0,b,386,10],rf=[0,b,362,16],rg=[0,b,517,12],rh=[0,b,kE,14],rs=[0,b,686,27],rr=[0,b,651,27],rl=[0,b,560,16],ri=[0,b,550,23],rj=[0,b,544,14],q_=[0,b,334,9],q6=[0,b,309,9],q5=[0,b,305,9],q4=[0,[11,\"Lwd: unsafe mutation (variable invalidated during evaluation) at\\n\",[15,0]],\"Lwd: unsafe mutation (variable invalidated during evaluation) at\\n%a\"],q1=[0,b,jN,14],qY=[0,b,186,14],qW=[0,b,169,14],qU=[0,b,152,14],rm=\"Lwd.Release_failure\",rz=[0,a,64,12],rJ=[0,a,bu,21],rS=[0,a,205,18],rR=[0,a,kQ,9],rU=[0,a,224,18],rT=[0,a,237,9],rV=[0,a,240,21],rW=[0,a,aD,21],rX=[0,a,260,21],rZ=[0,a,296,14],sm=[0,a,553,18],sn=[0,a,557,12],so=[0,a,546,14],sl=[0,a,538,21],sj=[0,a,531,14],sh=[0,a,523,14],sf=[0,a,kB,29],se=[0,a,499,29],sd=[0,a,462,21],r_=[0,a,420,10],r$=[0,a,423,15],sa=[0,a,435,10],sb=[0,a,457,2],r5=[0,a,371,24],r6=[0,a,391,16],r7=[0,a,394,2],r2=[0,a,315,18],r1=[0,a,317,9],rO=[0,a,193,4],rN=[0,a,jN,21],rL=[0,a,js,4],rM=[0,a,177,14],rG=[0,a,113,14],rE=[0,a,jO,14],rC=[0,a,93,14],rA=[0,a,82,21],ry=[0,a,39,4],rx=[0,a,45,21],rv=[0,a,32,14],sR=[0,X,571,12],sC=[0,X,321,37],sD=[0,X,322,37],sF=[0,X,346,10],sG=[0,X,357,42],sE=[0,X,337,37],sI=[0,X,375,10],sJ=[0,X,kz,42],sH=[0,X,338,37],sM=[0,X,425,16],sP=[0,X,513,50],sN=[0,X,480,6],sL=[0,X,395,14],su=[0,X,js,57],sv=[0,X,182,57],sw=[0,X,238,11],sp=kn,sq=kn,tG=\"debug\",tF=\"warn\",tD=jq,tB=\"log\",tK=\"isSecureContext\",t1=[0,jR,233,16],tZ=[0,jR,201,16],tU=[0,0,0],tS=[0,0,0],uw=e,uv=e,ul=[0,[0,S,kf],0],um=[0,[0,S,f3],[0,aG,0]],un=[0,[0,S,fR],[0,aG,0]],uo=[0,[0,S,fJ],[0,aG,0]],up=[0,[0,S,fN],[0,aG,0]],uq=[0,[0,S,fW],[0,aG,0]],ur=[0,[0,S,fZ],[0,aG,0]],us=[0,[0,S,fU],[0,aG,0]],ut=[0,[0,S,kf],[0,aG,0]],uc=[0,[0,S,f3],0],ud=[0,[0,S,fR],0],ue=[0,jJ,0],uf=[0,[0,S,fJ],0],ug=[0,[0,S,fN],0],uh=[0,[0,S,fW],0],ui=[0,[0,S,fZ],0],uj=[0,aG,0],uk=[0,[0,S,fU],0],ua=[0,[11,\"\\x1b[\",[4,0,0,0,[12,109,0]]],\"\\x1b[%dm\"],ub=\"CCFormat.ANSI_codes.No_such_style\",ux=\"CCFormat.Style\",uS=[0,0],uT=\"CCFQueue.Empty\",uU=[0,0],u4=\"content-box\",u5=\"border-box\",u6=\"device-pixel-content-box\",vh=kc,ve=[0,[8,[0,0,0],0,0,[11,kF,0]],\"%fpx\"],vf=[0,[8,[0,0,0],0,0,[11,kb,0]],\"%frem\"],vg=[0,[8,[0,0,0],0,0,[11,j2,0]],\"%fem\"],vb=kF,vc=kb,vd=j2,vk=\"Common.Utils.Forward_ref.Not_set\",vm=\"Common.Utils.Forward_ref.Already_set\",vq=[1,[0,3854881,\"Failed to unmarshal data\"]],vu=[1,-358247754],vs=[0,[11,\"Multiple persitent var are using the key \",[2,0,0]],\"Multiple persitent var are using the key %s\"],vE=\"TODO not implemented\",vK=[0,80,[0,\"lwdui-controlled-scroll-wrapper\"]],vL=[0,80,\"lwdui-controlled-scroll-controls\"],vM=\"Show playing\",vQ=jy,vO=e,vP=bW,vT=[0,80,bW],vR=[0,[2,0,[11,\"--id\",0]],\"%s--id\"],vU=[0,[2,0,[11,\"-id\",0]],\"%s-id\"],vV=[0,80,\"checkbox\"],v7=[0,[11,kA,[2,0,0]],\"height: %s\"],v3=[0,[2,0,[12,32,[2,0,0]]],\"%s %s\"],v1=\"grid-template-columns\",v2=[0,[2,0,[11,kJ,[2,0,[12,59,0]]]],\"%s: %s;\"],v4=e,v8=[1,4.],wb=[0,80,jn],v$=[0,[11,\"height: calc(\",[2,0,[11,\" * \",[4,3,0,0,[11,\");\",0]]]]],\"height: calc(%s * %i);\"],wa=[0,[11,kA,[2,0,[11,\" !important;\",0]]],\"height: %s !important;\"],wc=[0,80,[0,\"lwdui-lazy-table-content\"]],wd=[0,80,[0,\"lwdui-lazy-table-content-wrapper\"]],we=[0,\"lwdui-lazy-table\",0],wv=[0,[3,0,[11,\" is not a valid action\",0]],\"%S is not a valid action\"],wn=\"retain\",wo=\"insert\",wp=jI,wq=[0,fQ,72,22],wi=[0,[0,0,0,0,0,0,0]],wj=[0,fQ,49,6],wk=[0,[0,0,[0,[0,0]],0,0,0,0,0,0]],wl=[0,fQ,ju,6],wr=[0,[0,0,0,0,0,0,0]],ww=[0,[0,0,[0,[0,0]],0,0,0,0,0,0]],wL=[0,[11,\"stun:\",[2,0,0]],\"stun:%s\"],wJ=\"signaling\",wK=[0,\"stun.l.google.com:19302\",[0,\"stun2.l.google.com:19302\",[0,\"stun3.l.google.com:19302\",[0,\"stun4.l.google.com:19302\",0]]]],wM=\"peerOpts\",wY=\"toolbar\",wX=\"cursors\",wW=\"bubble\",wZ=\"snow\",wQ=jl,wR=\"italic\",wS=\"underline\",wT=\"strike\",wU=\"link\",w$=[0,[11,\"vector length is \",[4,0,0,0,[11,\", but data array has length \",[4,0,0,0,[11,\" (racy access?)\",0]]]]],\"vector length is %d, but data array has length %d (racy access?)\"],w9=[0,[11,\"index \",[4,0,0,0,[11,\" is out of range [0, \",[4,0,0,0,[12,41,0]]]]],\"index %d is out of range [0, %d)\"],w5=[0,[11,\"invalid segment (ofs = \",[4,0,0,0,[11,\", len = \",[4,0,0,0,[11,\") in a sequence of length \",[4,0,0,0,0]]]]]],\"invalid segment (ofs = %d, len = %d) in a sequence of length %d\"],xm=\"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\",zc=\"tbl\",zd=[0,\"Create new table:\",0],y_=kc,y$=[0,80,[0,dH]],za=[0,80,[0,jz]],y5=\"Found\",y6=jj,y7=\"1fr\",y8=\"a\",y4=[2,5.],y2=[0,c,781,19],y1=[0,80,\"Add row\"],yU=[0,1],yT=\"Add map with id \",yV=[0,1],yY=e,yZ=e,yW=[0,a_,1],yX=[0,a_,0],y0=[0,c,762,18],yQ=[0,c,710,25],yP=e,yR=[0,c,702,23],yN=jK,yO=\"Form valid:\",yG=[0,0,0],yH=[0,80,\"Add column\"],yI=[0,[0,cs,\"String\"],[0,[0,dK,\"Checkbox\"],[0,[0,bW,\"Richtext\"],0]]],yJ=[0,f4,cs,0],yK=[0,0],yL=[0,\"demo\"],yM=[0,1],yD=\"DELETE ROW\",yE=jj,yC=[0,c,622,17],yx=[0,80,[0,fI]],yy=[0,[0,0,[0,1,[0,2,0]]]],yz=[0,1],yA=[0,0],yt=e,yu=e,yv=[0,80,[0,fI]],yo=jK,yp=\" -> \",yn=[0,0],yl=[0,0],ym=[0,80,\"Update\"],yh=e,yi=e,yj=[0,80,[0,\"cell-edit-btn\"]],yk=\"\\xe2\\x9c\\x8f\\xef\\xb8\\x8f\",yq=[0,80,[0,\"cell-edit-overlay\"]],yr=[0,80,[0,fI]],x4=\"GET\",x3=[0,c,419,17],x2=[0,c,434,11],x7=[0,c,449,19],x6=[0,c,kE,13],x5=[0,c,439,13],x8=[0,c,466,11],yc=[0,c,484,19],yb=[0,c,479,19],x9=[0,c,472,13],x$=[0,c,488,15],ya=[0,c,kB,15],x_=[0,c,493,11],ye=e,yf=[0,c,505,17],yd=[0,c,508,11],xX=cq,xY=j1,xR=\"New column kind:\",xP=[0,c,294,13],xL=dK,xM=bW,xN=dH,xO=cs,xH=\"Old value:\",xI=\"Action: delete\",xJ=\"Key:\",xK=[0,c,219,15],xG=\"On_change\",xF=[0,c,144,22],xD=\"[blit v(%i) %i %i v'(%i)]\",xA=[0,c,87,18],xx=\"PEERS\",xv=\"STATUS\",xt=[0,\"SYNCED!\",0],xp=\"modules/cursors\",xq=[0,[0,\"wss://p2p.u31.fr\",0]],xr=\"testroom5267564\",xs=\"zedoc\",xu=\"synced\",xw=\"status\",xy=\"peers\",xU=cq,xV=j1,ze=[0,80,\"Add table\"],zh=[0,80,[0,jz]];function\nz(a){if(typeof\na===\"number\")return 0;switch(a[0]){case\n0:return[0,z(a[1])];case\n1:return[1,z(a[1])];case\n2:return[2,z(a[1])];case\n3:return[3,z(a[1])];case\n4:return[4,z(a[1])];case\n5:return[5,z(a[1])];case\n6:return[6,z(a[1])];case\n7:return[7,z(a[1])];case\n8:var\nc=a[1];return[8,c,z(a[2])];case\n9:var\nb=a[1];return[9,b,b,z(a[3])];case\n10:return[10,z(a[1])];case\n11:return[11,z(a[1])];case\n12:return[12,z(a[1])];case\n13:return[13,z(a[1])];default:return[14,z(a[1])]}}function\nW(a,b){if(typeof\na===\"number\")return b;switch(a[0]){case\n0:return[0,W(a[1],b)];case\n1:return[1,W(a[1],b)];case\n2:return[2,W(a[1],b)];case\n3:return[3,W(a[1],b)];case\n4:return[4,W(a[1],b)];case\n5:return[5,W(a[1],b)];case\n6:return[6,W(a[1],b)];case\n7:return[7,W(a[1],b)];case\n8:var\nc=a[1];return[8,c,W(a[2],b)];case\n9:var\nd=a[2],e=a[1];return[9,e,d,W(a[3],b)];case\n10:return[10,W(a[1],b)];case\n11:return[11,W(a[1],b)];case\n12:return[12,W(a[1],b)];case\n13:return[13,W(a[1],b)];default:return[14,W(a[1],b)]}}function\nw(a,b){if(typeof\na===\"number\")return b;switch(a[0]){case\n0:return[0,w(a[1],b)];case\n1:return[1,w(a[1],b)];case\n2:var\nc=a[1];return[2,c,w(a[2],b)];case\n3:var\nd=a[1];return[3,d,w(a[2],b)];case\n4:var\ne=a[3],f=a[2],g=a[1];return[4,g,f,e,w(a[4],b)];case\n5:var\nh=a[3],i=a[2],j=a[1];return[5,j,i,h,w(a[4],b)];case\n6:var\nk=a[3],l=a[2],m=a[1];return[6,m,l,k,w(a[4],b)];case\n7:var\nn=a[3],o=a[2],p=a[1];return[7,p,o,n,w(a[4],b)];case\n8:var\nq=a[3],r=a[2],s=a[1];return[8,s,r,q,w(a[4],b)];case\n9:var\nt=a[1];return[9,t,w(a[2],b)];case\n10:return[10,w(a[1],b)];case\n11:var\nu=a[1];return[11,u,w(a[2],b)];case\n12:var\nv=a[1];return[12,v,w(a[2],b)];case\n13:var\nx=a[2],y=a[1];return[13,y,x,w(a[3],b)];case\n14:var\nz=a[2],A=a[1];return[14,A,z,w(a[3],b)];case\n15:return[15,w(a[1],b)];case\n16:return[16,w(a[1],b)];case\n17:var\nB=a[1];return[17,B,w(a[2],b)];case\n18:var\nC=a[1];return[18,C,w(a[2],b)];case\n19:return[19,w(a[1],b)];case\n20:var\nD=a[2],E=a[1];return[20,E,D,w(a[3],b)];case\n21:var\nF=a[1];return[21,F,w(a[2],b)];case\n22:return[22,w(a[1],b)];case\n23:var\nG=a[1];return[23,G,w(a[2],b)];default:var\nH=a[2],I=a[1];return[24,I,H,w(a[3],b)]}}function\nd4(a){return[0,a]}function\ncG(a){return a[1]}function\nd5(a,b,c){return a[1]===b?(a[1]=c,1):0}function\naK(a){throw g([0,b3,a],1)}function\nt(a){throw g([0,cH,a],1)}function\ncI(a){return 0<=a?a:-a|0}var\ngv=kC;function\nay(a,b){return a+b}function\nlw(b){var\ne=n(b);return function(a){var\nc=a;for(;;){if(e<=c)return ay(b,lx);var\nd=y(b,c);a:{if(48<=d){if(58>d)break a}else if(45===d)break a;return b}c=c+1|0}}(0)}function\ngw(a,b){if(!a)return b;var\nc=a[1];return[0,c,gw(a[2],b)]}z$(0);var\nlz=le(1),at=le(2);function\nb5(a,b){gj(a,b,0,n(b));return}function\ngx(a){b5(at,a);lf(at,10);return bz(at)}var\nd7=d4(function(a){return function(a){var\nb=a;for(;;){if(!b)return 0;var\nd=b[2],e=b[1];try{bz(e)}catch(f){var\nc=L(f);if(c[1]!==gu)throw g(c,0)}b=d}}(Aa(0))});function\nd8(a){return h(cG(d7),0)}go(j6,d8);function\nls(a){return a^-1}function\nlt(a){return a?lu:lv}function\nly(a){return lw(ga(\"%.12g\",a))}function\nlA(a,b,c,d){if(0<=c&&0<=d&&(n(b)-d|0)>=c)return gj(a,b,c,d);return t(lB)}function\nlC(c){for(;;){var\nd=d4(1),a=cG(d7);let\ne=d,f=a;var\nb=1-d5(d7,a,function(a){if(d5(e,1,0))h(c,0);return h(f,0)});if(!b)return b}}function\ncJ(a){return bz(a)}function\nlD(a,b){lf(a,b);return}var\nd9=Ao(0),b6=(4*d9|0)-1|0;function\nlE(a){return 1-(typeof\na===\"number\"?1:0)}var\nlG=[q,lF,ae(0)];function\nlH(a){throw g(lG,1)}function\ncK(a){var\nd=a[1];a[1]=lH;try{var\nc=h(d,0);Ag(a,c);return c}catch(f){var\nb=L(f);a[1]=function(a){throw g(b,0)};throw g(b,0)}}function\nlI(a){var\nb=aw(a);if(b!==aD&&b!==ba&&b!==ko)return a;return z3(a)}function\ncL(a){return a?a[1]:t(lJ)}function\nd_(a,b){return b?[0,h(a,b[1])]:0}function\ngy(a){return a?1:0}function\nlK(a,b){return a===b?1:0}function\nlL(a){a:{if(40<=a){if(92===a)return lM;if(f2>a)break a}else{if(32<=a){if(39<=a)return lN;break a}if(14>a)switch(a){case\n8:return lO;case\n9:return lP;case\n10:return lQ;case\n13:return lR}}var\nb=F(4);B(b,0,92);B(b,1,48+(a/fL|0)|0);B(b,2,48+((a/10|0)%10|0)|0);B(b,3,48+(a%10|0)|0);return d1(b)}var\nc=F(1);B(c,0,a);return d1(c)}function\nlS(a){return 25>>0?a:a+kK|0}function\nlT(a,b){var\nd=a,c=b;for(;;){if(!c)return d;d=d+1|0;c=c[2]}}function\ngz(a){return lT(0,a)}function\nbB(a,b){var\nc=a,d=b;for(;;){if(!c)return d;var\ne=[0,c[1],d];c=c[2];d=e}}function\na3(a){return bB(a,0)}function\ngA(a,b,c){if(b<=a)return 0;var\nd=h(c,a);return[0,d,gA(a+1|0,b,c)]}function\nlU(a,b){return[0,a,b]}function\nlV(a){return a?a[1]:aK(lW)}function\nlX(a,b,c,d){var\nf=a,e=b;for(;;){if(c<=e)return f;f=[0,h(d,e),f];e=e+1|0}}function\nd$(a){if(!a)return 0;var\nb=a[1];return gw(b,d$(a[2]))}function\ncM(a,b){if(!b)return 0;var\nc=b[2],d=h(a,b[1]);return[0,d,cM(a,c)]}function\na4(a,b){var\nc=b;for(;;){if(!c)return 0;var\nd=c[2];h(a,c[1]);c=d}}function\ngB(a,b,c){var\ne=b,d=c;for(;;){if(!d)return e;var\nf=d[2];e=i(a,e,d[1]);d=f}}function\ngC(g){function\nb(a,b){var\nd=a,c=b;for(;;){if(!c)return a3(d);var\ne=c[2],f=h(g,c[1]);if(f){d=[0,f[1],d];c=e}else\nc=e}}var\nc=0;return function(a){return b(c,a)}}function\nlY(a,b){return 0<=a?50>1,s=p(r,b),D=s[1],t=p(a-r|0,s[2]),E=t[2];return[0,B(D,t[1],0),E]}function\np(a,b){if(2===a){if(b){var\nj=b[2];if(j){var\nk=j[1],g=b[1],B=j[2],q=i(d,g,k),C=0===q?[0,g,0]:0>1,s=h(r,b),D=s[1],t=h(a-r|0,s[2]),E=t[2];return[0,A(D,t[1],0),E]}var\na=gz(b);return 2<=a?h(a,b)[1]:b}function\ngD(a,b){return b<=a?a:b}function\ngE(a){return e+a}function\nl4(a,b){return k_(a,b)}function\nl5(a,b){return a<=b?a:b}function\nbh(a,b){var\nc=F(a);zC(c,0,a,b);return c}var\nl6=F(0);function\ngF(a){var\nb=aq(a),c=F(b);aZ(a,0,c,0,b);return c}function\nea(a,b,c){if(0<=b&&0<=c&&(aq(a)-c|0)>=b){var\nd=F(c);aZ(a,b,d,0,c);return d}return t(l8)}function\neb(a,b,c){return d1(ea(a,b,c))}function\ngG(a,b,c,d,e){if(0<=e&&0<=b&&(aq(a)-e|0)>=b&&0<=d&&(aq(c)-e|0)>=d){aZ(a,b,c,d,e);return}return t(l9)}function\naL(a,b,c,d,e){if(0<=e&&0<=b&&(n(a)-e|0)>=b&&0<=d&&(aq(c)-e|0)>=d){cy(a,b,c,d,e);return}return t(l_)}function\ngH(a){var\nb=a-9|0;a:{if(4>>0){if(23!==b)break a}else if(2===b)break a;return 1}return 0}function\nmb(a,b){var\nd=aq(b);if(0===d)return b;var\ne=F(d),f=d-1|0,g=0;if(f>=0){var\nc=g;for(;;){B(e,c,h(a,bY(b,c)));var\ni=c+1|0;if(f===c)break;c=i}}return e}function\ngI(a,b,c){zx(a,b,zP(c));return}function\ngJ(a,b,c){a0(a,b,c);return}function\ngK(a,b){return zw(a,b)}function\ncN(a){return bd(a)}function\n$(a){return d1(a)}function\nl7(a){return gF(bd(a))}function\nl$(a){var\nd=aq(a),b=[0,0];for(;;){if(b[1]>=d)break;if(!gH(bY(a,b[1])))break;b[1]++}var\nc=[0,d-1|0];for(;;){if(b[1]<=c[1]&&gH(bY(a,c[1]))){c[1]--;continue}return b[1]<=c[1]?ea(a,b[1],(c[1]-b[1]|0)+1|0):l6}}function\nma(a){var\nb=[0,0],j=aq(a)-1|0,l=0;if(j>=0){var\ng=l;for(;;){var\ne=bY(a,g);a:{b:{c:{if(32<=e){var\nh=e-34|0;if(58>>0){if(93<=h)break c}else if(56>>0)break b;var\ni=1;break a}if(11<=e){if(13===e)break b}else if(8<=e)break b}var\ni=4;break a}var\ni=2}b[1]=b[1]+i|0;var\no=g+1|0;if(j===g)break;g=o}}if(b[1]===aq(a))return gF(a);var\nc=F(b[1]);b[1]=0;var\nk=aq(a)-1|0,m=0;if(k>=0){var\nf=m;for(;;){var\nd=bY(a,f);a:{b:{c:{if(35<=d){if(92!==d){if(f2<=d)break c;break b}}else{if(32>d){if(14<=d)break c;switch(d){case\n8:B(c,b[1],92);b[1]++;B(c,b[1],98);break a;case\n9:B(c,b[1],92);b[1]++;B(c,b[1],116);break a;case\n10:B(c,b[1],92);b[1]++;B(c,b[1],110);break a;case\n13:B(c,b[1],92);b[1]++;B(c,b[1],114);break a;default:break c}}if(34>d)break b}B(c,b[1],92);b[1]++;B(c,b[1],d);break a}B(c,b[1],92);b[1]++;B(c,b[1],48+(d/fL|0)|0);b[1]++;B(c,b[1],48+((d/10|0)%10|0)|0);b[1]++;B(c,b[1],48+(d%10|0)|0);break a}B(c,b[1],d)}b[1]++;var\nn=f+1|0;if(k===f)break;f=n}}return c}function\nmc(a){return mb(lS,a)}function\ncO(a,b){return $(bh(a,b))}function\nec(a,b,c){return $(ea(cN(a),b,c))}function\ngL(a){var\nb=a-9|0;a:{if(4>>0){if(23!==b)break a}else if(2===b)break a;return 1}return 0}function\nmf(a,b,c,d){var\ne=c;for(;;){if(b<=e)throw g(ax,1);if(_(a,e)===d)return e;e=e+1|0}}function\nmg(a,b,c){var\nd=n(a);if(0<=b&&d>=b)try{mf(a,d,b,c);var\nf=1;return f}catch(f){var\ne=L(f);if(e===ax)return 0;throw g(e,0)}return t(mh)}function\ned(a,b){return lk(a,b)}function\nmd(a){if(a==e)return a;if(!gL(_(a,0))&&!gL(_(a,n(a)-1|0)))return a;return $(l$(cN(a)))}function\nme(a){return function(a,b,c){var\nd=c;for(;;){if(b<=d)return a;var\ne=_(a,d)+kK|0;a:{if(59>>0){if(33>>0)break a}else if(2===e)break a;d=d+1|0;continue}return $(ma(cN(a)))}}(a,n(a),0)}function\nmi(a,b){return mg(a,0,b)}function\nmj(a){return $(mc(cN(a)))}function\nmk(a,b){return a==b?1:0}function\ngM(a,b){if(0===a)return[0];if(0>a)return t(ml);var\nd=ap(a,h(b,0)),e=a-1|0,f=1;if(e>=1){var\nc=f;for(;;){d[1+c]=h(b,c);var\ng=c+1|0;if(e===c)break;c=g}}return d}function\ncP(a,b,c,d,e){if(0<=e&&0<=b&&(a.length-1-e|0)>=b&&0<=d&&(c.length-1-e|0)>=d)return zq(a,b,c,d,e);return t(mo)}function\ngN(a,b){var\nd=b.length-2|0,e=0;if(d>=0){var\nc=e;for(;;){h(a,b[1+c]);var\nf=c+1|0;if(d===c)break;c=f}}return 0}function\ngO(a,b){var\nd=b.length-1;if(0===d)return[0];var\ne=ap(d,h(a,b[1])),f=d-1|0,g=1;if(f>=1){var\nc=g;for(;;){e[1+c]=h(a,b[1+c]);var\ni=c+1|0;if(f===c)break;c=i}}return e}function\nmp(a,b){var\nd=a,c=b;for(;;){if(!c)return d;d=d+1|0;c=c[2]}}function\nee(a){if(!a)return[0];var\nb=a[2],c=a[1],e=ap(mp(0,a),c);return function(a,b){var\nd=a,c=b;for(;;){if(!c)return e;var\nf=c[2];e[1+d]=c[1];d=d+1|0;c=f}}(1,b)}function\nmm(a,b,c){if(0<=b&&0<=c&&(a.length-1-c|0)>=b)return zr(a,b,c);return t(mn)}function\nmq(k){function\nj(a){return a?a[4]:0}function\nd(a,b,c){var\nd=a?a[4]:0,e=c?c[4]:0,f=e<=d?d+1|0:e+1|0;return[0,a,b,c,f]}function\nl(a,b,c){var\ng=a?a[4]:0,h=c?c[4]:0;if((h+2|0)=h){var\nw=h<=g?g+1|0:h+1|0;return[0,a,b,c,w]}if(!c)return t(mu);var\nk=c[3],m=c[2],f=c[1],r=j(f);if(r<=j(k))return d(d(a,b,f),m,k);if(!f)return t(mt);var\ns=f[2],u=f[1],v=d(f[3],m,k);return d(d(a,b,u),s,v)}function\nc(a,b){if(!b)return[0,0,a,0,1];var\nd=b[3],e=b[2],f=b[1],g=i(k[1],a,e);if(0===g)return b;if(0<=g){var\nh=c(a,d);return d===h?b:l(f,e,h)}var\nj=c(a,f);return f===j?b:l(j,e,d)}function\nb(a){return[0,0,a,0,1]}var\nm=0;function\ne(a,b){var\nc=b;for(;;){if(!c)return;var\nd=c[3],f=c[2];e(a,c[1]);h(a,f);c=d}}function\nn(a,b){var\nd=a,c=b;for(;;){if(!c)return d;var\ne=c[2],f=c[1];d=[0,e,n(d,c[3])];c=f}}function\no(a,b,c){var\nd=c;for(;;){if(!d)return;var\ne=d[3],f=d[1];d=h(b,d[2])?e:f}}function\np(a){function\nc(a,b){if(3>=a>>>0)switch(a){case\n0:return[0,0,b];case\n1:if(b)return[0,[0,0,b[1],0,1],b[2]];break;case\n2:if(b){var\nh=b[2];if(h)return[0,[0,[0,0,b[1],0,1],h[1],0,2],h[2]]}break;default:if(b){var\ni=b[2];if(i){var\nj=i[2];if(j)return[0,[0,[0,0,b[1],0,1],i[1],[0,0,j[1],0,1],2],j[2]]}}}var\nk=a/2|0,l=c(k,b),e=l[2],n=l[1];if(!e)throw g([0,f,mv],1);var\no=e[1],m=c((a-k|0)-1|0,e[2]),p=m[2];return[0,d(n,o,m[1]),p]}return c(gz(a),a)[1]}return[0,,,,c,,,,,,,,,,,,,m,,,,,,,,,,,,,,e,,,,,,,,function(a){return n(0,a)},,,,,,,,,,,function(a,b){var\nc=b;for(;;){if(!c)return;var\nd=c[2],e=c[3],f=c[1];if(h(a,d))return o(d,a,e);c=f}},,,,,,,function(a){if(!a)return m;var\nf=a[2],d=a[1];if(!f)return b(d);var\ng=f[2],e=f[1];if(!g)return c(e,b(d));var\nh=g[2],i=g[1];if(!h)return c(i,c(e,b(d)));var\nj=h[2],l=h[1];if(!j)return c(l,c(i,c(e,b(d))));if(j[2])return p(l3(k[1],a));var\nn=j[1];return c(n,c(l,c(i,c(e,b(d)))))}]}function\nmw(a){var\nb=mq(a);return[0,b[17],,,b[4],,,,,,,,,,b[31],,,,,,,,,b[39],,,,,,,,,,,,,b[50],b[57]]}function\nmx(f){function\nh(a){return a?a[5]:0}function\ne(a,b,c,d){var\ne=h(a),f=h(d),g=f<=e?e+1|0:f+1|0;return[0,a,b,c,d,g]}function\nd(a,b,c,d){var\ni=a?a[5]:0,j=d?d[5]:0;if((j+2|0)=j){var\nB=j<=i?i+1|0:j+1|0;return[0,a,b,c,d,B]}if(!d)return t(mB);var\nl=d[4],o=d[3],p=d[2],g=d[1],w=h(g);if(w<=h(l))return e(e(a,b,c,g),p,o,l);if(!g)return t(mA);var\nx=g[3],y=g[2],z=g[1],A=e(g[4],p,o,l);return e(e(a,b,c,z),y,x,A)}function\nj(a,b,c){if(!c)return[0,0,a,b,0,1];var\ne=c[4],h=c[3],k=c[2],g=c[1],o=c[5],l=i(f[1],a,k);if(0===l)return h===b?c:[0,g,a,b,e,o];if(0<=l){var\nm=j(a,b,e);return e===m?c:d(g,k,h,m)}var\nn=j(a,b,g);return g===n?c:d(n,k,h,e)}function\nn(a){var\nb=a;for(;;){if(!b)throw g(ax,1);var\nc=b[1];if(!c)return[0,b[2],b[3]];b=c}}function\nc(a){if(!a)return t(mC);var\nb=a[1];if(!b)return a[4];var\ne=a[4],f=a[3],g=a[2];return d(c(b),g,f,e)}function\no(a,b){if(!a)return b;if(!b)return a;var\ne=n(b),f=e[2],g=e[1];return d(a,g,f,c(b))}function\nk(a,b){if(!b)return 0;var\nc=b[4],h=b[3],g=b[2],e=b[1],j=i(f[1],a,g);if(0===j)return o(e,c);if(0<=j){var\nl=k(a,c);return c===l?b:d(e,g,h,l)}var\nm=k(a,e);return e===m?b:d(m,g,h,c)}function\nl(a,b){var\nc=b;for(;;){if(!c)return 0;var\nd=c[4],e=c[3],f=c[2];l(a,c[1]);i(a,f,e);c=d}}function\nm(a,b,c){var\nd=b,e=c;for(;;){if(!d)return e;var\nf=d[4],g=d[3],h=d[2],i=x(a,h,g,m(a,d[1],e));d=f;e=i}}return[0,,,,,0,,j,function(a,b){var\nc=b;for(;;){if(!c)throw g(ax,1);var\ne=c[4],h=c[3],j=c[1],d=i(f[1],a,c[2]);if(0===d)return h;var\nk=0<=d?e:j;c=k}},,,,,,,,,function(a,b){var\nc=b;for(;;){if(!c)return 0;var\ne=c[4],g=c[3],h=c[1],d=i(f[1],a,c[2]);if(0===d)return[0,g];var\nj=0<=d?e:h;c=j}},,,,,,,k,,l,,,m]}function\nef(a){var\nb=mx(a);return[0,b[5],,,b[7],,,b[24],,,,,b[26],b[29],,,,,,,,,,,,,,,b[8],b[17]]}var\neg=[q,mD,ae(0)];function\nbC(a){return[0,0,0]}function\nb7(a){a[1]=0;a[2]=0;return}function\na5(a,b){b[1]=[0,a,b[1]];b[2]=b[2]+1|0;return 0}function\nbD(a){var\nb=a[1];if(!b)return 0;var\nc=b[1];a[1]=b[2];a[2]=a[2]-1|0;return[0,c]}function\nbE(a){var\nb=a[1];return b?[0,b[1]]:0}function\nmE(a){var\nb=a[1];if(!b)throw g(eg,1);a[1]=b[2];a[2]=a[2]-1|0;return}function\nmF(a){if(a[1])return;throw g(eg,1)}function\nmG(a,b){return a4(a,b[1])}var\nmI=[q,mH,ae(0)];function\neh(a){return[0,0,0,0]}function\nei(a){a[1]=0;a[2]=0;a[3]=0;return}function\nej(a,b){var\nc=[0,a,0],d=b[3];return d?(b[1]=b[1]+1|0,d[2]=c,b[3]=c,0):(b[1]=1,b[2]=c,b[3]=c,0)}function\ngP(a){var\nb=a[2];if(!b)throw g(mI,1);var\nc=b[1];if(b[2]){var\nd=b[2];a[1]=a[1]-1|0;a[2]=d;return c}ei(a);return c}function\nek(a){return 0===a[1]?1:0}function\nmJ(a){var\nb=a[2];return b?[0,b[1]]:0}function\nmK(a){var\nb=a[2];if(!b)return 0;var\nc=b[1];if(b[2]){var\nd=b[2];a[1]=a[1]-1|0;a[2]=d;return[0,c]}ei(a);return[0,c]}function\nb8(a){var\nb=1<=a?a:1,c=b6=(d+b|0))break;c[1]=2*c[1]|0}if(b6a[3])throw g([0,f,mP],1);if((d+b|0)<=a[3])return;throw g([0,f,mO],1)}function\nb9(a,b){var\nc=n(b),d=a[2]+c|0;if(a[3]=b)return eb(a[1],b,c);return t(mM)}function\nmN(a){return a[2]}function\nmR(a,b){var\nc=a[2];if(a[3]<=c)el(a,1);B(a[1],c,b);a[2]=c+1|0;return}function\nmS(a,b,c,d){var\ne=c<0?1:0;if(e)var\nf=e;else\nvar\nh=d<0?1:0,f=h||((n(b)-d|0)e){if(32!==e){if(43>e)break a;switch(e-43|0){case\n5:c:if(c<(d+2|0)&&1=(d+1|0))break a;var\nf=bh(d+1|0,48);a0(f,0,e);aL(b,1,f,(d-c|0)+2|0,c-1|0);return $(f)}if(71<=e){if(5>>0)break a}else if(65>e)break a}if(ca)return b;var\nh=[0,0],i=n(b)-1|0,o=0;if(i>=0){var\nd=o;for(;;){if(9>=_(b,d)+kg>>>0)h[1]++;var\nr=d+1|0;if(i===d)break;d=r}}var\nj=h[1],k=F(n(b)+((j-1|0)/3|0)|0),l=[0,0];function\ne(a){a0(k,l[1],a);l[1]++;return}var\nf=[0,((j-1|0)%3|0)+1|0],m=n(b)-1|0,p=0;if(m>=0){var\nc=p;for(;;){var\ng=_(b,c);if(9>>0)e(g);else{if(0===f[1]){e(95);f[1]=3}f[1]--;e(g)}var\nq=c+1|0;if(m===c)break;c=q}}return $(k)}function\noy(a,b){return cS(a,dT(nF(a),b))}function\noz(a,b){return cS(a,dT(n7(a),b))}function\noA(a,b){return cS(a,dT(oj(a),b))}function\noB(a,b){return cS(a,zS(nT(a),b))}function\naM(d,b,c){function\na(a){switch(d[1]){case\n0:var\ne=45;break;case\n1:var\ne=43;break;default:var\ne=32}return zN(c,b,e)}function\ne(a){var\nb=zy(c);return 3===b?c<0.?oD:oE:4<=b?oF:a}function\nf(b){var\ne=n(b);return function(a){var\nc=a;for(;;){if(c===e)return 0;var\nd=y(b,c)-46|0;a:{if(23>>0){if(55===d)break a}else if(21>>0)break a;c=c+1|0;continue}return 1}}(0)?b:ay(b,oC)}switch(d[2]){case\n5:return e(f(ga(gU(d,b),c)));case\n6:return a(0);case\n7:return mj(a(0));case\n8:return e(a(0));default:return ga(gU(d,b),c)}}function\noG(a){var\nb=lL(a),c=n(b),d=bh(c+2|0,39);cy(b,0,d,1,c);return $(d)}function\noH(a){var\nb=gQ(16);en(b,a);return gS(b)}function\nco(a,b,c,d){var\nk=b,j=c,e=d;for(;;){if(typeof\ne===\"number\")return h(k,j);switch(e[0]){case\n0:var\nt=e[1];return function(a){return o(k,[5,j,a],t)};case\n1:var\nu=e[1];return function(a){return o(k,[4,j,oG(a)],u)};case\n2:return eo(k,j,e[2],e[1],function(a){return a});case\n3:return eo(k,j,e[2],e[1],nE);case\n4:return cT(k,j,e[4],e[2],e[3],oy,e[1]);case\n5:return cT(k,j,e[4],e[2],e[3],oz,e[1]);case\n6:return cT(k,j,e[4],e[2],e[3],oA,e[1]);case\n7:return cT(k,j,e[4],e[2],e[3],oB,e[1]);case\n8:return oI(k,j,e[4],e[2],e[3],e[1]);case\n9:return eo(k,j,e[2],e[1],lt);case\n10:j=[7,j];e=e[1];break;case\n11:j=[2,j,e[1]];e=e[2];break;case\n12:j=[3,j,e[1]];e=e[2];break;case\n13:var\nv=e[3],x=oH(e[2]);return function(a){return o(k,[4,j,x],v)};case\n14:var\ny=e[3],z=e[2];return function(a){return o(k,j,w(nD(a[1],z),y))};case\n15:var\nA=e[1];return function(c,b){return o(k,[6,j,function(a){return i(c,a,b)}],A)};case\n16:var\nB=e[1];return function(a){return o(k,[6,j,a],B)};case\n17:j=[0,j,e[1]];e=e[2];break;case\n18:var\nl=e[1];if(0===l[0]){let\nb=j,c=k,d=e[2];k=function(a){return o(c,[1,b,[0,a]],d)};j=0;e=l[1][1]}else{let\nb=j,c=k,d=e[2];k=function(a){return o(c,[1,b,[1,a]],d)};j=0;e=l[1][1]}break;case\n19:throw g([0,f,oK],1);case\n20:var\nC=e[3],D=[8,j,oL];return function(a){return o(k,D,C)};case\n21:var\nE=e[2];return function(a){return o(k,[4,j,dT(ka,a)],E)};case\n22:var\nF=e[1];return function(a){return o(k,[5,j,a],F)};case\n23:var\nm=e[2],n=e[1];return a<50?jc(a+1|0,k,j,n,m):r(jc,[0,k,j,n,m]);default:var\np=e[3],q=e[1],s=h(e[2],0);return a<50?ft(a+1|0,k,j,p,q,s):r(ft,[0,k,j,p,q,s])}}}function\no(a,b,c){return bA(co(0,a,b,c))}function\njc(a,b,c,d,e){if(typeof\nd===\"number\")switch(d){case\n0:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n1:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n2:throw g([0,f,oM],1);default:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e])}switch(d[0]){case\n0:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n1:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n2:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n3:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n4:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n5:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n6:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n7:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n8:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);case\n9:var\nh=d[2];return a<50?fu(a+1|0,b,c,h,e):r(fu,[0,b,c,h,e]);case\n10:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e]);default:return a<50?s(a+1|0,b,c,e):r(s,[0,b,c,e])}}function\nfu(a,h,c,d,e){if(typeof\nd===\"number\")return a<50?s(a+1|0,h,c,e):r(s,[0,h,c,e]);switch(d[0]){case\n0:var\nb=d[1];return function(a){return af(h,c,b,e)};case\n1:var\ni=d[1];return function(a){return af(h,c,i,e)};case\n2:var\nj=d[1];return function(a){return af(h,c,j,e)};case\n3:var\nk=d[1];return function(a){return af(h,c,k,e)};case\n4:var\nl=d[1];return function(a){return af(h,c,l,e)};case\n5:var\nm=d[1];return function(a){return af(h,c,m,e)};case\n6:var\nn=d[1];return function(a){return af(h,c,n,e)};case\n7:var\no=d[1];return function(a){return af(h,c,o,e)};case\n8:var\np=d[2];return function(a){return af(h,c,p,e)};case\n9:var\nq=d[3],t=d[2],u=I(D(d[1]),t);return function(a){return af(h,c,W(u,q),e)};case\n10:var\nv=d[1];return function(a,b){return af(h,c,v,e)};case\n11:var\nw=d[1];return function(a){return af(h,c,w,e)};case\n12:var\nx=d[1];return function(a){return af(h,c,x,e)};case\n13:throw g([0,f,oN],1);default:throw g([0,f,oO],1)}}function\naf(a,b,c,d){return bA(fu(0,a,b,c,d))}function\ns(a,b,c,d){var\ne=[8,c,oP];return a<50?co(a+1|0,b,e,d):r(co,[0,b,e,d])}function\neo(g,f,c,d,e){if(typeof\nd===\"number\")return function(a){return o(g,[4,f,h(e,a)],c)};if(0===d[0]){var\nb=d[2],i=d[1];return function(a){return o(g,[4,f,ab(i,b,h(e,a))],c)}}var\nj=d[1];return function(a,b){return o(g,[4,f,ab(j,a,h(e,b))],c)}}function\ncT(k,j,h,d,e,f,g){if(typeof\nd===\"number\"){if(typeof\ne===\"number\")return e?function(a,b){return o(k,[4,j,bG(a,i(f,g,b))],h)}:function(a){return o(k,[4,j,i(f,g,a)],h)};var\nb=e[1];return function(a){return o(k,[4,j,bG(b,i(f,g,a))],h)}}if(0===d[0]){var\nc=d[2],l=d[1];if(typeof\ne===\"number\")return e?function(a,b){return o(k,[4,j,ab(l,c,bG(a,i(f,g,b)))],h)}:function(a){return o(k,[4,j,ab(l,c,i(f,g,a))],h)};var\nn=e[1];return function(a){return o(k,[4,j,ab(l,c,bG(n,i(f,g,a)))],h)}}var\nm=d[1];if(typeof\ne===\"number\")return e?function(a,b,c){return o(k,[4,j,ab(m,a,bG(b,i(f,g,c)))],h)}:function(a,b){return o(k,[4,j,ab(m,a,i(f,g,b))],h)};var\np=e[1];return function(a,b){return o(k,[4,j,ab(m,a,bG(p,i(f,g,b)))],h)}}function\noI(i,h,g,d,e,f){if(typeof\nd===\"number\"){if(typeof\ne===\"number\")return e?function(a,b){return o(i,[4,h,aM(f,a,b)],g)}:function(a){return o(i,[4,h,aM(f,em(f),a)],g)};var\nb=e[1];return function(a){return o(i,[4,h,aM(f,b,a)],g)}}if(0===d[0]){var\nc=d[2],j=d[1];if(typeof\ne===\"number\")return e?function(a,b){return o(i,[4,h,ab(j,c,aM(f,a,b))],g)}:function(a){return o(i,[4,h,ab(j,c,aM(f,em(f),a))],g)};var\nl=e[1];return function(a){return o(i,[4,h,ab(j,c,aM(f,l,a))],g)}}var\nk=d[1];if(typeof\ne===\"number\")return e?function(a,b,c){return o(i,[4,h,ab(k,a,aM(f,b,c))],g)}:function(a,b){return o(i,[4,h,ab(k,a,aM(f,em(f),b))],g)};var\nm=e[1];return function(a,b){return o(i,[4,h,ab(k,a,aM(f,m,b))],g)}}function\nft(a,b,c,d,e,f){if(e){var\ni=e[1];return function(a){return oJ(b,c,d,i,h(f,a))}}var\ng=[4,c,f];return a<50?co(a+1|0,b,g,d):r(co,[0,b,g,d])}function\noJ(a,b,c,d,e){return bA(ft(0,a,b,c,d,e))}function\naN(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;switch(c[0]){case\n0:var\nf=c[1],g=gT(c[2]);aN(a,f);return b5(a,g);case\n1:var\nd=c[2],e=c[1];if(0===d[0]){var\ni=d[1];aN(a,e);b5(a,oQ);c=i}else{var\nj=d[1];aN(a,e);b5(a,oR);c=j}break;case\n6:var\nm=c[2];aN(a,c[1]);return h(m,a);case\n7:aN(a,c[1]);return cJ(a);case\n8:var\nn=c[2];aN(a,c[1]);return t(n);case\n2:case\n4:var\nk=c[2];aN(a,c[1]);return b5(a,k);default:var\nl=c[2];aN(a,c[1]);return lD(a,l)}}}function\naO(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;switch(c[0]){case\n0:var\nf=c[1],g=gT(c[2]);aO(a,f);return b9(a,g);case\n1:var\nd=c[2],e=c[1];if(0===d[0]){var\ni=d[1];aO(a,e);b9(a,oS);c=i}else{var\nj=d[1];aO(a,e);b9(a,oT);c=j}break;case\n6:var\nm=c[2];aO(a,c[1]);return b9(a,h(m,0));case\n7:c=c[1];break;case\n8:var\nn=c[2];aO(a,c[1]);return t(n);case\n2:case\n4:var\nk=c[2];aO(a,c[1]);return b9(a,k);default:var\nl=c[2];aO(a,c[1]);return mR(a,l)}}}function\noU(a){var\nc=a[1],b=b8(cv);return o(function(a){aO(b,a);return aK(cQ(b))},0,c)}function\noV(c){if(c==e)return oW;var\nf=n(c);function\nj(a){return h(oU(oX),c)}function\nk(a){var\nb=a;for(;;){if(b===f)return b;var\nd=y(c,b);if(9!==d&&32!==d)return b;b=b+1|0}}var\ni=k(0),o=function(a,b){var\nd=b;for(;;){if(d===f)return d;if(25>>0)return d;d=d+1|0}}(i,i),a=ec(c,i,o-i|0),d=k(o),l=function(a,b){var\nd=b;for(;;){if(d===f)return d;var\ne=y(c,d);a:{if(48<=e){if(58>e)break a}else if(45===e)break a;return d}d=d+1|0}}(d,d);if(d===l)var\nm=0;else\ntry{var\nr=k$(ec(c,d,l-d|0)),m=r}catch(f){var\np=L(f);if(p[1]!==b3)throw g(p,0);var\nq=j(0),m=q}if(k(l)!==f)j(0);a:{if(a!==e&&a!==jt){if(a===\"h\"){var\nb=0;break a}if(a===\"hov\"){var\nb=3;break a}if(a===\"hv\"){var\nb=2;break a}if(a!==\"v\"){var\nb=j(0);break a}var\nb=1;break a}var\nb=4}return[0,m,b]}function\noY(d,b,c){return o(function(a){aN(b,a);return h(d,b)},0,c[1])}function\ncU(a,b){return oY(function(a){return 0},a,b)}function\nep(a){return cU(at,a)}function\neq(c,b){return o(function(a){var\nb=b8(64);aO(b,a);return h(c,cQ(b))},0,b[1])}function\nC(a){return eq(function(a){return a},a)}var\ner=d4(0);function\net(a,b){var\nc=a[1+b];return lE(c)?aw(c)===dC?h(C(oZ),c):aw(c)===ko?ly(c):o0:h(C(o1),c)}function\ngV(a,b){if(a.length-1<=b)return o2;var\nc=gV(a,b+1|0),d=et(a,b);return i(C(o3),d,c)}function\no4(a){var\nb=a.length-1;if(2>=b>>>0)switch(b){case\n0:return o6;case\n1:return o7;default:var\ne=et(a,1);return h(C(o8),e)}var\nc=gV(a,2),d=et(a,1);return i(C(o5),d,c)}function\no9(d){return function(a){var\nb=a;for(;;){if(!b)return 0;var\ne=b[2],f=b[1];a:{try{var\nc=h(f,d)}catch(f){break a}if(c)return[0,c[1]]}b=e}}(cG(er))}function\no_(a){if(a===d6)return o$;if(a===gt)return pa;if(a[1]===gs){var\nb=a[2],e=b[3],i=b[2],j=b[1];return fx(C(es),j,i,e,e+5|0,pb)}if(a[1]===f){var\nc=a[2],g=c[3],k=c[2],l=c[1];return fx(C(es),l,k,g,g+6|0,pc)}if(a[1]===b4){var\nd=a[2],h=d[3],m=d[2],n=d[1];return fx(C(es),n,m,h,h+6|0,pd)}if(0!==aw(a))return a[1];var\no=a[1][1];return ay(o,o4(a))}function\ncV(a){var\nb=o9(a);return b?b[1]:o_(a)}function\npe(a){var\nb=[0,zz(a)];return b}function\npf(c,b){function\na(a){return a?0===c?pg:ph:0===c?pi:pj}if(0===b[0]){var\nd=b[5],e=b[4],f=b[3],g=b[6]?pk:pm,i=b[2],j=b[7],k=a(b[1]);return[0,zm(C(pl),k,j,i,g,f,e,d)]}if(b[1])return 0;var\nl=a(0);return[0,h(C(pn),l)]}function\npo(a,b){if(!b)return cU(a,pq);var\nd=b[1],e=d.length-2|0,g=0;if(e>=0){var\nc=g;for(;;){var\nf=pf(c,j(d,c)[1+c]);if(f){var\ni=f[1];h(cU(a,pp),i)}var\nk=c+1|0;if(e===c)break;c=k}}return 0}function\ncW(a,b){return po(a,pe(b))}var\npt=ps.slice();function\npu(a,b){var\ne=cV(a);h(ep(pv),e);cW(at,b);var\nc=z_(0);if(c<0){var\nd=cI(c);gx(j(pt,d)[1+d])}return cJ(at)}var\npw=[0];function\ngW(a){var\nb=k5(0);return b}function\npx(a,b){try{var\nd=b?pw:gW(0);try{d8(0)}catch(f){}try{var\nf=pu(a,d),e=f}catch(f){var\ni=L(f),j=gW(0),k=cV(a);h(ep(pz),k);cW(at,d);var\nl=cV(i);h(ep(pA),l);cW(at,j);var\ne=cJ(at)}return e}catch(f){var\nc=L(f);if(c===d6)return gx(py);throw g(c,0)}}go(ky,function(a,b){try{var\nc=px(a,b);return c}catch(f){return 0}});function\npr(a){for(;;){var\nb=cG(er),c=1-d5(er,b,[0,a,b]);if(!c)return c}}function\npB(a){return k5(a)}var\npD=[q,pC,ae(0)];pr(function(a){return a[1]===pD?[0,ay(pE,cV(a[2]))]:0});function\npF(a){return z8(a,0,n(a))}function\npG(a){return[0,ap(55,0),0]}function\npH(a,b){function\nl(a,b){return pF(ay(a,gE(b)))}function\nm(a){var\nb=y(a,3)<<24,c=y(a,2)<<16,d=y(a,1)<<8;return((y(a,0)+d|0)+c|0)+b|0}var\ng=0===b.length-1?[0,0]:b,h=g.length-1,c=0;for(;;){j(a[1],c)[1+c]=c;var\ns=c+1|0;if(54===c)break;c=s}var\nf=[0,pI],i=54+gD(55,h)|0,n=0;if(i>=0){var\nd=n;for(;;){var\ne=d%55|0,k=Ad(d,h),o=j(g,k)[1+k];f[1]=l(f[1],o);var\np=m(f[1]),q=(j(a[1],e)[1+e]^p)&jY;j(a[1],e)[1+e]=q;var\nr=d+1|0;if(i===d)break;d=r}}a[2]=0;return}function\npJ(a){var\nb=pG(0);pH(b,a);return b}function\ngX(a){return pJ(Aq(0))}function\ncX(a){a[2]=(a[2]+1|0)%55|0;var\nb=a[2],c=j(a[1],b)[1+b],d=(a[2]+24|0)%55|0,e=(j(a[1],d)[1+d]+(c^(c>>>25|0)&31)|0)&jY,f=a[2];j(a[1],f)[1+f]=e;return e}function\ngY(a){var\nb=gi(dW(cX(a)),9),c=gi(dW(cX(a)),9);return k8(b,k8(k9(c,21),k9(gi(dW(cX(a)),8),42)))}function\npK(a){var\nb=a.length-1<4?1:0,c=b||(a[4]<0?1:0);return c}try{var\nzk=ll(kp),g2=zk}catch(f){var\ngZ=L(f);if(gZ!==ax)throw g(gZ,0);try{var\nzj=ll(\"CAMLRUNPARAM\"),g1=zj}catch(f){var\ng0=L(f);if(g0!==ax)throw g(g0,0);var\ng1=pL}var\ng2=g1}var\ncY=[ba,function(a){return gX(0)}],pM=mi(g2,82);function\npN(a,b){var\nc=a;for(;;){if(b<=c)return c;if(d9<(c*2|0))return c;c=c*2|0}}function\neu(a,b){var\nf=a?a[1]:pM,c=pN(16,b);if(f)var\nd=aw(cY),g=aD===d?cY[1]:ba===d?cK(cY):cY,e=cX(g);else\nvar\ne=0;return[0,0,ap(c,0),e,c]}function\npO(m,b,c,d){var\ng=d.length-1,f=ap(g,0),i=c.length-2|0;function\nn(a){var\nc=a;for(;;){if(!c)return;var\ni=c[1],l=c[2],n=c[3],g=b?c:[0,i,l,0],e=h(m,i),k=j(f,e)[1+e];if(k)k[3]=g;else\nj(d,e)[1+e]=g;j(f,e)[1+e]=g;c=n}}var\no=0;if(i>=0){var\ne=o;for(;;){n(j(c,e)[1+e]);var\nr=e+1|0;if(i===e)break;e=r}}if(b){var\nk=g-1|0,p=0;if(k>=0){var\na=p;for(;;){var\nl=j(f,a)[1+a];if(l)l[3]=0;var\nq=a+1|0;if(k===a)break;a=q}}}return}function\ng3(a,b){var\nc=b[2],d=(c.length-1)*2|0,e=d>>0)return;return g_(a,d)}function\np0(a){var\nb=mK(a[28]);if(!b)return;var\nc=b[1],d=c[1];a[12]=a[12]-c[3]|0;var\ne=al(d);a[9]=a[9]+e|0;return}function\np1(a,b,c){if(typeof\nc===\"number\")switch(c){case\n0:var\nj=bE(a[3]);if(!j)return;var\nk=j[1][1],l=function(a,b){if(!b)return[0,a,0];var\nc=b[1],d=b[2];return z4(a,c)?[0,a,b]:[0,c,l(a,d)]};k[1]=l(a[6]-a[9]|0,k[1]);return;case\n1:bD(a[2]);return;case\n2:bD(a[3]);return;case\n3:var\nm=bE(a[2]);return m?g_(a,m[1][2]):c0(a);case\n4:var\no=a[10]!==(a[6]-a[9]|0)?1:0;return o?p0(a):o;default:var\np=bD(a[5]);if(p)return ev(a,h(a[25],p[1]));return}switch(c[0]){case\n0:return g9(a,b,c[1]);case\n1:var\nd=c[2],f=c[1],q=d[1],z=d[2],r=bE(a[2]);if(!r)return;var\ns=r[1],e=s[2];switch(s[1]){case\n0:return bI(a,f);case\n1:return bi(a,d,e);case\n2:return bi(a,d,e);case\n3:return a[9]<(b+n(q)|0)?bi(a,d,e):bI(a,f);case\n4:return a[11]?bI(a,f):a[9]<(b+n(q)|0)?bi(a,d,e):((a[6]-e|0)+z|0)=a[14]){a[13]=g8;g$(a);if(b)c0(a);return qc(a)}he(a,0)}}function\ney(a,b,c){var\nd=a[14]=c)return x(a[17],hi,0,c);x(a[17],hi,0,80);c=c-80|0}}function\nqp(a){return a[1]===b$?ay(qr,ay(a[2],qq)):qs}function\nqt(a){return a[1]===b$?ay(qv,ay(a[2],qu)):qw}function\nqx(a){return 0}function\nqy(a){return 0}function\nqz(a,b,c,d,e){var\ng=eh(0),h=[0,g6,qA,0];ej(h,g);var\nf=bC(0);ew(f);a5([0,1,h],f);var\ni=78,j=bC(0),k=bC(0),l=bC(0);return[0,f,bC(0),l,k,j,i,10,68,i,0,1,1,1,1,gv,qB,a,b,c,d,e,0,0,qp,qt,qx,qy,g]}function\nhk(a,b){var\nc=qz(a,b,function(a){return 0},function(a){return 0},function(a){return 0});c[19]=function(a){return qn(c,a)};c[20]=function(a){return hj(c,a)};c[21]=function(a){return hj(c,a)};return c}function\nhl(d){return hk(function(a,b,c){return lA(d,a,b,c)},function(a){return cJ(d)})}function\nez(d){return hk(function(a,b,c){return mS(d,a,b,c)},function(a){return 0})}var\nqC=dF,qD=function(a){return b8(qC)}(0),qE=hl(lz),qF=hl(at);ez(qD);function\np9(a,b){if(a[22]){a5(b,a[4]);h(a[26],b)}var\nc=a[23];return c?ca(a,[0,cZ,[5,b],0]):c}function\nqe(a,b){return hh(a,n(b),b)}function\nqf(a,b){hg(a,1);return h(a[18],0)}function\nqg(a,b){var\nc=a[14]=0){var\nc=g;for(;;){qK(e,c,a,j(b,c)[1+c]);var\nh=c+1|0;if(f===c)break;c=h}}return e}function\nho(a,b){if(typeof\nb!==\"number\"&&0===b[0])return hn(a,b[1]);return aK(qL)}function\nqM(a,b,c,d){if(typeof\nc!==\"number\"){if(0===c[0])return hp(c[1],a[1+b],d);return}if(2!==c){a[1+b]=d;return}if(0===aw(d)&&4===d.length-1){var\ne=0,h=a[1+b];for(;;){h[1+e]=d[1+e];var\ni=e+1|0;if(3===e)return;e=i}}throw g([0,f,qN],1)}function\nhp(a,b,c){if(0===aw(c)&&a.length-1<=c.length-1){var\ne=a.length-2|0,h=0;if(e>=0){var\nd=h;for(;;){var\ni=c[1+d];qM(b,d,j(a,d)[1+d],i);var\nk=d+1|0;if(e===d)break;d=k}}return}throw g([0,f,qO],1)}function\nhq(a,b,c){if(typeof\na!==\"number\"&&0===a[0])return hp(a[1],b,c);return aK(qP)}var\neA=[q,qQ,ae(0)];qI(qR,[0,eA,[0]]);(function(a){throw a});function\neB(a){return[0,a]}function\nQ(a){return[0,a]}function\nc2(a){return 0===a[0]?[0,a[1]]:0}var\nbK=[0,function(a){return a}(0)];function\nbL(a){return[1,0,0,0,a]}function\nl(a,b){return 0===a[0]?[0,h(b,a[1])]:bL([0,a,b])}function\ncc(a,b,c){if(0===a[0]){var\nd=a[1];if(0===b[0])return[0,i(c,d,b[1])]}return bL([1,a,b,c])}function\nhr(a){return 0===a[0]?a[1]:bL([4,a,0])}function\nhs(a,b,c){switch(c[0]){case\n0:throw g([0,f,qU],1);case\n1:c[3]=[0,b,a,c[3]];return;default:c[2]=[0,b,a,c[2]];return}}function\neC(a,b){if(!b)throw g([0,f,qV],1);if(b[2]===a)return[0,b[1],b[3]];var\nc=eC(a,b[3]),d=c[1];b[3]=c[2];return[0,d,b]}function\ncd(a,b){switch(b[0]){case\n0:throw g([0,f,qW],1);case\n1:var\nc=eC(a,b[3]),e=c[1];b[3]=c[2];return e;default:var\nd=eC(a,b[2]),h=d[1];b[2]=d[2];return h}}function\nht(a,b,c,d){var\ne=d;for(;;){if(!e)throw g([0,f,qX],1);if(e[1]===b&&e[2]===a){e[1]=c;return}e=e[3]}}function\neD(a,b,c,d){switch(d[0]){case\n0:throw g([0,f,qY],1);case\n1:return ht(a,b,c,d[3]);default:return ht(a,b,c,d[2])}}function\nhu(a,b){var\nc=b;for(;;){if(!c)throw g([0,f,qZ],1);if(c[2]===a)return c[1];c=c[3]}}function\nq0(a,b){switch(b[0]){case\n0:throw g([0,f,q1],1);case\n1:return hu(a,b[3]);default:return hu(a,b[2])}}function\naU(a,b,c,d){switch(d[0]){case\n0:throw g([0,f,q2],1);case\n1:var\nj=d[1];if(typeof\nj===\"number\"&&!j){if(!c)return;if(b[1])return;b[1]=1;return}var\nk=d[4];if(7===k[0]){var\nn=k[2];if(1===n[0]){var\no=n[1];if(typeof\no===\"number\"){if(!o&&c){if(b[1])return;b[1]=1;return}}else if(c)return}}var\nl=d[1];a:{if(typeof\nl===\"number\"&&l){var\ne=1;break a}var\ne=c}d[1]=0;var\nm=d[2];return a<50?jd(a+1|0,b,e,m):r(jd,[0,b,e,m]);default:var\ni=d[1];d[1]=0;if(typeof\ni===\"number\"){if(!i)return;b[1]=2;return}var\np=i[1];if(c)b[1]=2;return h(d[3],p)}}function\na6(a,b,c){return bA(aU(0,a,b,c))}function\njd(a,b,c,d){if(typeof\nd===\"number\")return;switch(d[0]){case\n0:var\nf=d[1];return a<50?aU(a+1|0,b,c,f):r(aU,[0,b,c,f]);case\n1:var\ng=d[2];a6(b,c,d[1]);return a<50?aU(a+1|0,b,c,g):r(aU,[0,b,c,g]);case\n2:var\nh=d[3],l=d[2];a6(b,c,d[1]);a6(b,c,l);return a<50?aU(a+1|0,b,c,h):r(aU,[0,b,c,h]);case\n3:var\ni=d[4],m=d[3],n=d[2];a6(b,c,d[1]);a6(b,c,n);a6(b,c,m);return a<50?aU(a+1|0,b,c,i):r(aU,[0,b,c,i]);default:var\no=d[1];d[1]=0;var\nk=o-1|0,p=0;if(k>=0){var\ne=p;for(;;){a6(b,c,j(d[3],e)[1+e]);var\nq=e+1|0;if(k===e)break;e=q}}return}}function\nq3(a){return i(cU(at,q4),cW,zG(20))}function\nc3(a,b){var\nc=[0,0];a6(c,a,b);var\nd=2<=c[1]?1:0;return d?q3(0):d}function\nam(a){return bL([5,a])}function\naP(a){return a}function\nac(a,b){if(1===a[0]){var\nc=a[4];if(5===c[0]){c[1]=b;return c3(0,a)}}throw g([0,f,q5],1)}function\nbM(a){if(1===a[0]){var\nb=a[4];if(5===b[0])return b[1]}throw g([0,f,q6],1)}function\nbN(a,b,c){var\nk=a,h=b,d=c;for(;;)switch(d[0]){case\n0:return k;case\n1:var\ne=d[2];if(typeof\ne===\"number\")throw g([0,f,q$],1);switch(e[0]){case\n0:if(e[1]!==h)throw g([0,f,ra],1);var\no=0;break;case\n1:var\nB=e[2],C=e[1];if(C===h)var\nD=[0,B];else{if(B!==h)throw g([0,f,rb],1);var\nD=[0,C]}var\no=D;break;case\n2:var\nu=e[3],v=e[2],w=e[1];if(w===h)var\nx=[1,v,u];else if(v===h)var\nx=[1,w,u];else{if(u!==h)throw g([0,f,rc],1);var\nx=[1,w,v]}var\no=x;break;case\n3:var\np=e[4],q=e[3],r=e[2],s=e[1];if(s===h)var\nt=[2,r,q,p];else if(r===h)var\nt=[2,s,q,p];else if(q===h)var\nt=[2,s,r,p];else{if(p!==h)throw g([0,f,rd],1);var\nt=[2,s,r,q]}var\no=t;break;default:var\nn=cd(d,h);if(j(e[3],n)[1+n]!==h)throw g([0,f,re],1);var\nm=e[2]-1|0;e[2]=m;if(n>>2|0))var\nU=mm(e[3],0,K>>>1|0),M=[4,e[1],e[2],U];else\nvar\nM=e;var\nJ=M}var\no=J}d[2]=o;if(typeof\no!==\"number\")return k;var\ny=d[1];d[1]=1;var\nl=d[4];switch(l[0]){case\n0:h=d;d=l[1];break;case\n1:var\nN=l[2];k=bN(k,d,l[1]);h=d;d=N;break;case\n2:var\nO=l[2];k=bN(k,d,l[1]);h=d;d=O;break;case\n3:var\nP=l[2];k=bN(k,d,l[1]);h=d;d=P;break;case\n4:var\nz=l[2],A=bN(k,d,l[1]);if(!z)return A;var\nQ=z[1];l[2]=0;k=A;h=d;d=Q;break;case\n5:return k;case\n6:if(typeof\ny===\"number\")return k;var\nR=y[1];try{i(l[2],d,R);return k}catch(f){var\nS=L(f);return[0,[0,S,pB(0)],k]}default:var\nT=l[1];k=bN(k,d,l[2]);h=d;d=T}break;default:throw g([0,f,rf],1)}}function\na7(a,b){var\ne=a,c=b;for(;;)switch(c[0]){case\n0:return;case\n1:var\nn=typeof\nc[2]===\"number\"?1:0,d=c[2];if(typeof\nd===\"number\")var\nk=[0,e];else\nswitch(d[0]){case\n0:var\nk=[1,e,d[1]];break;case\n1:var\nk=[2,e,d[1],d[2]];break;case\n2:var\nk=[3,e,d[1],d[2],d[3]];break;case\n3:var\no=[0,d[1],d[2],d[3],d[4],e,bK,bK,bK],l=0;for(;;){hs(c,l,j(o,l)[1+l]);var\nw=l+1|0;if(4===l)break;l=w}var\nk=[4,5,5,o];break;default:var\ni=d[2];if(i>>1|0)}function\nhC(a,b,c){if(typeof\na!==\"number\"){if(0!==a[0]){if(a[2]!==b)throw g([0,f,rO],1);a[2]=c;return}if(a[2]===b){a[2]=c;return}if(a[4]===b){a[4]=c;return}}throw g([0,f,rN],1)}function\nfw(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[4];if(typeof\nd!==\"number\"&&1!==d[0]){var\nh=c[5],e=d[2];if(typeof\ne===\"number\")var\ni=0;else{if(0!==e[0])throw g([0,f,rS],1);e[5]=c;var\ni=e}d[2]=c;c[4]=i;c[5]=d;d[5]=h;hC(h,c,d);eK(b,c);return a<50?cp(a+1|0,b,d):r(cp,[0,b,d])}}throw g([0,f,rR],1)}function\nrP(a,b){return bA(fw(0,a,b))}function\nfv(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[2];if(typeof\nd!==\"number\"&&1!==d[0]){var\nh=c[5],e=d[4];if(typeof\ne===\"number\")var\ni=0;else{if(0!==e[0])throw g([0,f,rU],1);e[5]=c;var\ni=e}d[4]=c;c[2]=i;c[5]=d;d[5]=h;hC(h,c,d);eK(b,c);return a<50?cp(a+1|0,b,d):r(cp,[0,b,d])}}throw g([0,f,rT],1)}function\nrQ(a,b){return bA(fv(0,a,b))}function\njf(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[4];a:if(typeof\nd!==\"number\"&&0===d[0]){var\ne=bP(d[2]);if(eJ(bP(d[4]),e)){rQ(b,d);break a}}return a<50?fw(a+1|0,b,c):r(fw,[0,b,c])}throw g([0,f,rV],1)}function\nje(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=c[2];a:if(typeof\nd!==\"number\"&&0===d[0]){var\ne=bP(d[4]);if(eJ(bP(d[2]),e)){rP(b,d);break a}}return a<50?fv(a+1|0,b,c):r(fv,[0,b,c])}throw g([0,f,rW],1)}function\ncp(a,b,c){if(typeof\nc!==\"number\"&&0===c[0]){var\nd=bP(c[2]),e=bP(c[4]);return d>>2|0}function\naz(a,b){if(typeof\na===\"number\")var\nc=b;else{if(typeof\nb!==\"number\"){var\nd=c8(b);return[1,(hH(c8(a),d)+1|0)<<2,a,b]}var\nc=a}return c}function\nhI(a){return typeof\na===\"number\"?0:0===a[0]?[0,a[2]]:[1,a[2],a[3]]}var\neL=1,eM=2,sr=3;function\nhJ(a){return-1===a?1:0}function\neN(a){return-1!==a?1:0}function\nbQ(a){return(a&3)===3?1:0}function\nhK(a){return(a&3)===1?1:0}function\nhL(a){return(a&3)===2?1:0}function\nhM(a){return a|3}function\nss(a){return a>>>2|0}function\nhN(a){return a<<2|2}function\nch(a){return a&ls(sr)}function\nhO(a){return a[2]}function\nhP(a){return a[3]}function\nhQ(a){return[0,0,0,0]}function\nc9(a){a[1]=a[1]+1|0;return}function\nc_(a){a[2]=a[2]+1|0;return}function\nc$(a){a[3]=a[3]+1|0;return}function\neO(a,b,c){var\nd=c;for(;;){if(typeof\nd===\"number\")return;if(0===d[0]){var\ne=d[1],i=(e&3)!==3?1:0,l=i?0!==(e&3)?1:0:i;if(l){if(0!==(e&b))throw g([0,f,su],1);c9(a);c$(a);d[1]=e|3}return}var\nh=d[1],j=(h&3)!==3?1:0,k=j?0!==(h&3)?1:0:j;if(!k)return k;if(0!==(h&b))throw g([0,f,sv],1);c9(a);c$(a);d[1]=h|3;eO(a,b,d[2]);d=d[3]}}function\nda(a,b,c,d){if(typeof\nd===\"number\")return;if(0===d[0]){var\ne=d[1];if(0===(e&c)){c9(a);if(0===(e&3))d[1]=e|c;else{d[1]=-1;c$(a);c_(a)}}var\ng=-1!==e?1:0,h=g?(e&3)===3?1:0:g;return h?(d[1]=-1,c_(a)):h}var\nf=d[1];if(0===(f&c)){c9(a);if(0===(f&3)){d[1]=f|c;ej(d,b)}else{d[1]=-1;c$(a);c_(a);eO(a,c,d[2]);eO(a,c,d[3])}}var\ni=-1!==f?1:0,j=i?(f&3)===3?1:0:i;return j?(d[1]=-1,c_(a)):j}function\neP(a,b,c){var\nd=gP(b);if(typeof\nd!==\"number\"&&1===d[0]){var\ne=(d[1]&3)===c?1:0;return e?(da(a,b,c,d[2]),da(a,b,c,d[3])):e}throw g([0,f,sw],1)}function\nhR(a,b,c){for(;;){if(ek(b))return;eP(a,b,c)}}function\nsx(a,b,c,d){for(;;){if(ek(c))return hR(b,d,eM);if(ek(d))return hR(a,c,eL);eP(a,c,eL);eP(b,d,eM)}}function\neQ(a){var\nb=a[6];a[6]=b+1|0;return b}function\neR(a){var\nb=a;for(;;){if(typeof\nb===\"number\")return;if(0===b[0]){var\nc=b[1];if(typeof\nc!==\"number\"&&0===c[0]){var\ne=c[1],i=eN(e),l=i?bQ(e):i;if(l)c[1]=ch(e);return}throw g([0,f,sC],1)}var\nd=b[1];if(typeof\nd!==\"number\"&&1===d[0]){var\nh=d[1],m=b[4],n=b[3],j=eN(h),k=j?bQ(h):j;if(!k)return k;d[1]=ch(h);eR(n);b=m;continue}throw g([0,f,sD],1)}}function\nhS(a,b){var\nc=b;for(;;){if(typeof\nc===\"number\")return;if(0===c[0]){var\nd=c[1];if(typeof\nd!==\"number\"&&0===d[0]){var\ne=d[1],u=c[2];if(!hK(e)){if(hJ(e)){var\nk=eQ(a);j(a[4],k)[1+k]=d;j(a[5],k)[1+k]=[0,c,0];d[1]=hN(k);return}if(hL(e)){var\nn=ss(e),v=[0,c,j(a[5],n)[1+n]];j(a[5],n)[1+n]=v;return}var\nq=bQ(e);if(q)throw g([0,f,sG],1);return q}var\nm=a[2];if(-1a[3])throw g([0,f,sF],1)}d[1]=ch(e);return}throw g([0,f,sE],1)}var\nh=c[1];if(typeof\nh!==\"number\"&&1===h[0]){var\nr=c[4],s=c[3],i=h[1],w=c[2];if(hJ(i)){var\nl=eQ(a);j(a[4],l)[1+l]=h;j(a[5],l)[1+l]=[0,c,0];h[1]=hN(l);eR(s);return eR(r)}if(!hK(i)){if(hL(i)){var\no=i>>>2|0,x=[0,c,j(a[5],o)[1+o]];j(a[5],o)[1+o]=x;return}var\nt=bQ(i);if(t)throw g([0,f,sJ],1);return t}if(-1a[3])throw g([0,f,sI],1)}h[1]=ch(i);hS(a,s);c=r;continue}throw g([0,f,sH],1)}}function\nci(a,b){if(typeof\nb===\"number\")return 0;if(0!==b[0]){var\ni=b[1];if(-1===i){var\nl=eQ(a);b[1]=0;j(a[4],l)[1+l]=b;var\np=ci(a,b[2]);return[1,b,0,p,ci(a,b[3])]}if(!bQ(i)){b[1]=ch(b[1]);var\nr=ci(a,b[2]);return[1,b,0,r,ci(a,b[3])]}var\nd=i>>>2|0,k=j(a[5],d)[1+d];if(!k)throw g([0,f,sM],1);var\nm=k[2],q=k[1];j(a[5],d)[1+d]=m;if(0===m)b[1]=0;return q}var\ne=b[1];if(eN(e)&&bQ(e)){var\nc=e>>>2|0,h=j(a[5],c)[1+c];if(!h)return[0,b,0];var\nn=h[2],o=h[1];j(a[5],c)[1+c]=n;return o}b[1]=0;return[0,b,0]}var\neS=[0,0,[0],0,0];function\nst(a){return a[1]}function\nsy(a){return a[1]}function\nsz(a){return a[2]}function\nsA(a,b){var\nc=hQ(0),d=hQ(0),e=eh(0),f=eh(0);da(c,e,eL,a);da(d,f,eM,b);sx(c,d,e,f);return[0,c,d]}function\nsB(a){if(typeof\na===\"number\")return;if(0===a[0]){a[1]=0;return}var\nb=c8(a[3]);a[1]=(hH(c8(a[2]),b)+1|0)<<2;return}function\nsK(a){var\ne=a[6]-1|0,h=0;if(e>=0){var\nb=h;for(;;){var\nc=j(a[4],b)[1+b];if(typeof\nc!==\"number\")if(0===c[0])c[1]=hM(c[1]);else\nc[1]=hM(c[1]);var\nd=j(a[5],b)[1+b];if(!d)throw g([0,f,sL],1);if(d[2]){var\ni=a3(d);j(a[5],b)[1+b]=i}var\nk=b+1|0;if(e===b)break;b=k}}return}function\nhT(a,b,c){if(typeof\nb===\"number\"){if(typeof\nc===\"number\")return[0,eS,0]}else if(b[1]===c)return[0,eS,b];var\nt=typeof\nb===\"number\"?cg:b[1],m=sA(t,c),i=sy(m),n=sz(m),u=hP(n),v=hP(i)+u|0,o=st(i)-v|0,w=hO(n),p=hO(i)+w|0,x=0,y=ap(p,0),z=ap(p,0),A=a?o:-1,B=a?0:-1,C=a?ap(o,0):[0],d=[0,C,B,A,z,y,x];hS(d,b);if(d[2]!==d[3])throw g([0,f,sN],1);sK(d);var\nq=ci(d,c),r=d[6]-1|0;if(r>=0){var\nh=r;for(;;){sB(j(d[4],h)[1+h]);var\nF=h-1|0;if(0===h)break;h=F}}if(!a)return[0,eS,q];var\nk=[0,0],l=[0,0],s=d[6]-1|0,D=0;if(s>=0){var\ne=D;for(;;){a4(function(a){if(typeof\na!==\"number\")if(0===a[0]){var\nb=a[2];if(b){k[1]=[0,b[1],k[1]];return 0}}else{var\nc=a[2];if(c){l[1]=[0,c[1],l[1]];return 0}}return 0},j(d[5],e)[1+e]);var\nE=e+1|0;if(s===e)break;e=E}}return[0,[0,d[2],d[1],k[1],l[1]],q]}function\nsO(d,b){if(typeof\nb===\"number\")return 0;function\nc(a){a:if(typeof\na!==\"number\"){b:{if(0===a[0]){var\nb=a[1];if(typeof\nb!==\"number\"&&0===b[0]){var\ne=a[2];if(e){var\nj=e[1];break b}var\nk=h(d[1],b[2]);a[2]=[0,k];return k}break a}var\nl=a[2];if(!l){var\nn=c(a[3]),o=c(a[4]),m=i(d[2],n,o);a[2]=[0,m];return m}var\nj=l[1]}return j}throw g([0,f,sP],1)}return[0,c(b)]}function\ndb(a,b){return[0,[0,a,b],0]}function\ndc(a){return sO(a[1],a[2])}function\nsQ(a,b){var\nc=a[1];return[0,c,hT(0,a[2],b)[2]]}function\neT(a,b){var\nd=a[1],c=hT(1,a[2],b);return[0,c[1],[0,d,c[2]]]}function\ndd(a,b,c,d){var\ne=[0,d];if(v===a)var\nh=c[1],g=0;else if(j7<=a)var\nh=c[2].length-1,g=c[1];else\nvar\nh=c[2].length-1,g=0;var\nk=h-1|0;if(k>=g){var\nf=g;for(;;){var\nl=j(c[2],f)[1+f];if(l)e[1]=i(b,l[1],e[1]);var\nm=f+1|0;if(k===f)break;f=m}}if(j7>a)a4(function(a){e[1]=i(b,a,e[1]);return 0},c[3]);if(v!==a)a4(function(a){e[1]=i(b,a,e[1]);return 0},c[4]);return}function\neU(a,b,c){if(typeof\nc===\"number\")throw g([0,f,sR],1);if(0===c[0])return h(a,c[2]);var\nd=eU(a,b,c[3]);return i(b,eU(a,b,c[2]),d)}function\nbj(a,b,c){var\nd=b[2],e=b[1],f=c2(c);if(f){var\ng=f[1];return typeof\ng===\"number\"?Q(e):Q(eU(a,d,g))}var\nh=[0,db(a,d)];return l(c,function(a){var\nb=sQ(h[1],a);h[1]=b;var\nc=dc(b);return c?c[1]:e})}var\naQ=[0,cg,az];function\nsS(a,b){return c5(b,aQ,a)}function\nde(a){return sS(a,J)}function\nhU(a){function\ne(a,b){var\nc=a,d=b;for(;;){if(typeof\nc===\"number\")return d;if(0===c[0])return[0,c[2],d];var\nf=e(c[3],d);c=c[2];d=f}}return e(a,0)}var\nhV=[0,Q(0),function(a,b){return cc(a,b,az)}];function\neV(c,b){return bj(function(a){return J(h(c,a))},aQ,b)}function\nsT(a,b){return hr(bj(b,hV,a))}function\nbk(a){return sT(a,function(a){return l(a,J)})}var\nbl=e;function\nsU(a){return a[kO]}function\nhW(a,b){var\nc=a?a[1]:bl;return z5(b).join(c)}function\neW(a){return 0===sU(a)?1:0}function\ndf(a,b){return k3(a,b)}p[\"Number\"];var\neX=null,sV=undefined;function\ncj(a){return a===eX?1:0}function\nsW(a){return a===sV?1:0}function\nbR(a){var\nb=cj(a);return b?b:sW(a)}function\nhX(a){return 1-bR(a)}function\ndg(a,b){return bR(b)?0:[0,h(a,b)]}var\nk=p;function\neY(a,b){var\nc=a[b];return bR(c)?0:[0,c]}function\neZ(a){return new\nk[jX](a)}function\nhY(a){return a[kO]}function\nhZ(c,b){return gM(hY(b),function(a){return h(c,b[a])})}function\nh0(a,b){var\nd=b.length-1,e=eZ(d),f=d-1|0,g=0;if(f>=0){var\nc=g;for(;;){e[c]=h(a,j(b,c)[1+c]);var\ni=c+1|0;if(f===c)break;c=i}}return e}function\ne0(f,b){return function(a,b,c){var\ne=a,d=c;for(;;){if(!d)return b;var\ng=d[2];b[e]=h(f,d[1]);e=e+1|0;d=g}}(0,eZ(0),b)}function\ns1(a,b){var\nc=new\nk[\"Error\"](b);return a?(c[cq]=a[1],c):c}var\ns3=Symbol.iterator;function\ns5(a){return a.next()}function\ns6(a){var\nb=dg(function(a){return a|0},a[\"done\"]);return b?b[1]:0}function\ns7(a){return a[dE]}function\nh1(i,g,c,d,e){return function(a,b){var\nd=b;for(;;){var\ne=s5(a);if(s6(e))return d;var\nf=s7(e),j=h(g,f[1]);d=x(c,h(i,f[0]),j,d)}}(d,e)}k[\"Promise\"];function\nsZ(a){return as(a)}function\nbm(a,b,c){return dZ(a,sZ(b),c)}function\naA(a){return as(a)}function\nA(a){return H(a)}function\nbS(a,b){return a\ninstanceof\nb?1:0}var\nsX=true;function\nsY(a,b){a[b];return}function\ns0(c,b){return lY(hY(b),function(a){return h(c,b[a])})}function\ns2(a,b){return h(function(a){throw a},s1(a,b))}function\ns4(a){return a[s3]()}k[\"Event\"];function\ne1(a){return a[fy]}function\nh2(a,b,c,d){var\ne=a?a[1]:{},f=by(1,c);d.addEventListener(b,f,e);return function(a){d.removeEventListener(b,f,e);return 0}}function\nh3(a){return h(a,0)}var\ne2=\"change\",dh=\"click\";k[\"ArrayBuffer\"];k[\"DataView\"];function\ns8(a){a.preventDefault();return 0}var\ns9=\"DOMContentLoaded\",s_=kd,s$=\"scroll\",ta=\"wheel\";k[\"Blob\"];k[\"File\"];var\nh4=k[\"JSON\"];k[\"encodeURI\"];k[\"decodeURI\"];k[\"encodeURIComponent\"];k[\"decodeURIComponent\"];k[\"URL\"];k[\"URLSearchParams\"];function\naR(a,b){return[0,a,b]}var\ndi=[0,bl,bl];function\ne3(a){return[0,a,bl]}function\nh5(a){return a}var\nck=kx,e4=jQ,h6=cq,h7=jC,e5=\"type\",e6=dE,te=\"for\";function\naS(a){return aR(ck,a)}function\nh8(a){return aR(te,a)}var\ntg=e3(jo),ti=e3(\"required\");function\ndj(a){return aR(h7,a)}var\ntj=e3(\"selected\"),bn=k[\"document\"];function\ntb(a){return h4.stringify(a)}function\ntc(a){try{var\nc=h4.parse(a)}catch(f){var\nb=L(f);if(b[1]===eA)return[1,b[2]];throw g(b,0)}return[0,c]}function\ntd(a,b){return a?b:di}var\ntf=\"placeholder\";function\nth(a){return aR(e4,a)}function\ntk(a){return aR(e5,a)}function\ntl(a){return aR(e6,a)}function\ntm(a){return a[\"ownerDocument\"]}if(!bR(bn))bn[jL];function\ntn(a,b){a.appendChild(b);return 0}function\nto(a,b,c,d){var\ng=b,f=c,e=d;for(;;){if(!e){if(0!==g)a.setAttribute(jC,hW([0,\";\"],a3(g)));if(0!==f)a.setAttribute(kx,hW([0,aE],a3(f)));return}var\nh=e[2],k=e[1],i=k[2],j=k[1];if(eW(j))e=h;else if(df(j,h7)){g=[0,i,g];e=h}else if(df(j,ck)){var\nl=eW(i)?f:[0,i,f];f=l;e=h}else{a.setAttribute(j,i);e=h}}}function\nh9(a,b,c,d){var\nf=a?a[1]:bn,g=b?b[1]:0,e=f.createElement(c);to(e,0,0,g);a4(function(a){return tn(e,a)},d);return e}function\nbo(a,b){var\nc=a?a[1]:bn;return c.createTextNode(A(b))}function\nh_(a,b,c){return eW(a)?0:b?(c.setAttribute(a,b[1]),0):(c.removeAttribute(a),0)}function\nh$(a,b,c){return b?(c[jp].add(a),0):(c[jp].remove(a),0)}var\nia=\"div\";function\nty(a,b,c,d){return h9(b,c,a,d)}function\nib(a,b,c){return ty(ia,a,b,c)}function\nic(a){return a[jL]}function\ndk(a,b,c){dZ(a,b,c);return 0}var\ndl=k[kS];function\ndm(a){return z2(function(a,b,c){var\ne=b,d=c;for(;;){if(!d)return a;var\nf=d[2];a[e]=d[1];e=e+1|0;d=f}}(eZ(0),0,a))}function\nah(a){return dk(dl,tB,dm(a))}function\ne7(a){return dk(dl,tG,dm(a))}k[kS];k[\"navigator\"];var\ntJ=k[\"performance\"],dn=k[ks];sY(k,tK);function\ntp(a,b){dZ(a,kI,ee(b));return}function\ntq(a,b,c){var\ne=a?a[1]:k[ks],d=e.getComputedStyle(c)[b];return bR(d)?bl:d}function\ntr(a,b){var\nc=a?a[1]:kk,d=kk<=c?1:0;b.scrollIntoView(!!d);return 0}var\nts=\"button\",tt=\"form\",tu=kd,tv=\"label\",tw=\"option\",tx=\"select\";function\ntz(a){var\nb=a[\"body\"];return hX(b)?b:s2(0,\"Document body is null. Try to defer your script execution.\")}function\ntA(a){return dg(function(a){return a},a[\"activeElement\"])}function\ntC(a){return dk(dl,tD,dm(a))}function\ntE(a){return dk(dl,tF,dm(a))}function\ntH(a){return a}function\ntI(a){return a.now()}function\ntL(a,b){return k.setTimeout(by(1,b),a)}function\ntM(a){k.clearTimeout(a);return}function\ntN(a){k.requestAnimationFrame(by(1,a));return}k[\"ClipboardItem\"];k[\"FormData\"];k[\"Headers\"];k[\"Request\"];k[\"Response\"];k[\"fetch\"];k[\"MediaStream\"];k[\"MediaRecorder\"];k[\"MessageChannel\"];k[\"BroadcastChannel\"];k[\"Notification\"];k[\"WebSocket\"];function\ntO(a){return a[\"localStorage\"]}function\ntP(a,b){function\nc(a){return a}return function(a){return dg(c,a)}(a.getItem(b))}function\ntQ(a,b,c){try{a.setItem(b,c);return}catch(f){var\nd=L(f);if(d[1]===eA)return;throw g(d,0)}}function\naB(a,b,c){return[0,a,b,c]}function\nid(a){var\nb=a[1];return 82===b?gy(c2(a[2])):83<=b?gy(c2(a[2])):1}function\ndp(a){return cL(c2(a))}function\ntR(a){return d$(cM(function(a){var\nb=a[1];return 82===b?[0,dp(a[2]),0]:83<=b?hU(dp(a[2])):[0,a[2],0]},a))}function\nie(a){if(!a)return tS;var\nb=l2(id,a),c=b[2];return[0,tR(b[1]),c]}var\nig=kI,e8=\"before\";function\ntV(a){return[0,a]}function\ntW(a,b){return[1,eX,a,b]}var\ntX=\"remove\",tY=\"contains\";function\nih(a){var\nb=tA(tm(a));return b?bm(a,tY,[0,b[1]])|0:0}function\nii(e,b){var\nc=[0,db(tV,tW)];return l(b,function(a){var\nb=eT(c[1],a),d=b[2],g=b[1];c[1]=d;dd(v,function(a,b){return 0===a[0]?a[1][dD]=sX:0},g,0);var\nh=ih(e),i=dc(d);if(i){var\nf=function(d,b){if(0!==b[0]){if(!cj(b[1]))return b[1];var\nl=f(d,b[3]),k=f(l,b[2]);b[1]=k;return k}var\nc=b[1];delete\nc[dD];if(c.parentNode!==e)if(cj(d))bm(e,ig,[0,c]);else\nbm(d,e8,[0,c]);else{var\na=c.nextSibling!==d?1:0;if(a){if(h)var\ng=ih(c),i=g?function(a){for(;;){var\nb=c.nextSibling;if(b===d)return 1;if(cj(b))return 0;bm(c,e8,[0,b])}}(0):g;else\nvar\ni=h;var\nj=1-i}else\nvar\nj=a;if(j)if(cj(d))bm(e,ig,[0,c]);else\nbm(d,e8,[0,c])}return c};f(eX,i[1])}dd(v,function(a,b){if(0!==a[0])return 0;var\nc=a[1],d=hX(c[dD]),e=d?(delete\nc[dD],bm(c,tX,[0]),0):d;return e},g,0);return e})}var\ndq=Q(0),e9=[0,bl,bl];function\ntT(a){if(!a)return tU;var\nb=a[1],c=b[1];if(82===c){if(!a[2])return[0,0,[0,l(b[2],J)]]}else\nif(83<=c){if(!a[2])return[0,0,[0,b[2]]]}else if(!a[2])return[0,[0,b[2],0],0];return l0(id,a)?[0,d$(cM(function(a){var\nb=a[1];return 82===b?[0,dp(a[2]),0]:83<=b?hU(dp(a[2])):[0,a[2],0]},a)),0]:[0,0,[0,c5(function(a){var\nb=a[1];return 82===b?l(a[2],J):83<=b?a[2]:Q(J(a[2]))},hV,a)]]}function\nij(c,b){function\nd(a){var\nb=a[2],d=a[1];return df(d,ck)?h$(b,1,c):h_(d,[0,b],c)}function\ne(a){var\nb=a[1],d=a[2];return df(b,ck)?h$(d,0,c):h_(b,0,c)}function\nh(a){var\nb=[0,e9];return function(a){if(b[1]!==e9)e(b[1]);var\nc=h5(a);d(c);b[1]=c;return 0}}return c5(function(a){var\nb=a[1];if(82===b){var\ni=a[2];return l(i,h(0))}if(83>b)throw g([0,f,tZ],1);var\nj=a[2],c=[0,db(function(a){var\nb=h5(a);d(b);return b},function(a,b){return e9})];return l(j,function(a){var\nb=eT(c[1],a),d=b[2],f=b[1];c[1]=d;dd(v,function(a,b){return e(a)},f,0);dc(d);return 0})},[0,dq,function(a,b){return dq}],b)}function\ne_(a,b){return h2(b[1],b[2],b[3],a)}function\nt0(c,b){return c5(function(a){var\nb=a[1];if(82===b){var\nd=[0,0];return l(a[2],function(a){var\nb=d[1];if(b)h3(b[1]);d[1]=[0,e_(c,a)];return 0})}if(83>b)throw g([0,f,t1],1);var\nh=a[2],e=[0,db(function(a){return e_(c,a)},function(a,b){return a})];return l(h,function(a){var\nb=eT(e[1],a),c=b[2],d=b[1];e[1]=c;dd(v,function(a,b){return h3(a)},d,0);dc(c);return 0})},[0,dq,function(a,b){return dq}],b)}function\nik(a,b,c,d,e,f){var\nq=b?b[1]:0,r=c?c[1]:0,s=d?d[1]:function(a){return},m=ie(q),k=m[2],t=m[1],n=ie(r),o=n[2],u=n[1],p=tT(f),i=p[2],g=h9(a,[0,t],e,p[1]);h(s,g);if(k)if(i)var\nv=ii(g,i[1]),j=cc(ij(g,k),v,function(a,b){return b});else\nvar\nj=l(ij(g,k),function(a){return g});else\nvar\nj=i?ii(g,i[1]):Q(g);a4(function(a){e_(g,a);return 0},u);var\nw=o?cc(t0(g,o),j,function(a,b){return b}):j;return w}function\nbT(a,b,c,d,e,f){return ik(b,c,d,e,a,f)}function\nt2(a,b,c,d,e,f){return ik(b,c,d,e,a,0)}function\ne$(a,b,c,d,e){return bT(ts,a,b,c,d,e)}function\nR(a,b,c,d,e){return bT(ia,a,b,c,d,e)}function\nil(a,b,c,d,e){return t2(tu,a,b,c,d,e)}function\nim(a,b,c,d,e){return bT(tv,a,b,c,d,e)}function\nt3(a,b,c,d,e){return bT(tt,a,b,c,d,e)}function\nt4(a,b,c,d,e){return bT(tw,a,b,c,d,e)}function\nt5(a,b,c,d,e){return bT(tx,a,b,c,d,e)}function\ndr(a,b){return b=c)return uk;if(b===jl)return uj;if(b===\"cyan\")return ui;if(b===\"green\")return uh;if(b===\"magenta\")return ug;if(b===\"red\")return uf;if(b===\"reset\")return ue;if(b===\"white\")return ud;if(b===\"yellow\")return uc}else{if(b===\"Black\")return ut;if(b===\"Blue\")return us;if(b===\"Cyan\")return ur;if(b===\"Green\")return uq;if(b===\"Magenta\")return up;if(b===\"Red\")return uo;if(b===\"White\")return un;if(b===\"Yellow\")return um;if(b===\"black\")return ul}throw g(fb,1)}function\niq(a,b){a5(b,a);return uv}function\nir(a){try{mE(a);mF(a)}catch(f){var\nb=L(f);if(b!==eg)throw g(b,0)}return uw}var\nis=[q,ux,ae(0)],uu=0;function\nuy(a,b,c){if(c[1]===is)return iq(a,c[2]);if(c[1]!==b$)return h(b,c);var\ne=c[2];try{var\nf=iq(a,ip(e));return f}catch(f){var\nd=L(f);if(d===fb)return h(b,c);throw g(d,0)}}function\nuz(a,b,c){if(c[1]===is)return ir(a);if(c[1]!==b$)return h(b,c);var\ne=c[2];try{ip(e)}catch(f){var\nd=L(f);if(d===fb)return h(b,c);throw g(d,0)}return ir(a)}function\nuA(a){var\nc=bC(0);p$(a,1);var\nb=qa(a,0),d=b[2],e=b[1];return qb(a,[0,function(a){return uy(c,e,a)},function(a){return uz(c,d,a)},b[3],b[4]])}function\nuB(a,b){var\nd=b8(64),c=ez(d),e=a?uu:a;if(e)uA(c);return qH(function(a){bJ(c,0);return cQ(d)},c,b)}function\nuC(a){return uB(1,a)}function\nuD(a,b){return l4(a,b)}function\nuE(a){try{var\nc=[0,k$(a)];return c}catch(f){var\nb=L(f);if(b[1]===b3)return 0;throw g(b,0)}}function\nuF(a){return a|0}function\nuH(a,b,c,d){var\ng=a,f=b,e=d;for(;;){if(!e){g[1+f]=0;return}var\nj=e[2],i=[0,h(c,e[1]),kj];g[1+f]=i;g=i;f=1;e=j}}function\nuG(a,b){if(!b)return 0;var\nd=b[2],c=[0,h(a,b[1]),kj];uH(c,1,a,d);return c}function\nfc(a,b){return b?[0,h(a,b[1])]:0}function\nuI(a,b,c){return c?h(b,c[1]):a}function\nuJ(a,b){if(b)return h(a,b[1]);return}function\nuK(a,b){return b?b[1]:a}function\nuL(a,b){return a?a[1]:b}function\nuM(a){return a?[0,a[1],0]:0}function\nuN(a,b){return 0===b[0]?h(a,b[1]):[1,b[1]]}function\nuO(a,b){return uN(b,a)}function\nuP(a){var\nb=mw(a);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b[37],,,,,,,,,,,b[23]]}function\nuQ(a){var\nb=uP(a);return[0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,b[40],,,,,,,,,,,,,,,,,,,,b[51]]}function\nuR(e,b){var\nd=n(e);if(dr(d,n(b)))return 0;var\nf=n(b)-d|0;return function(a){var\nc=a;for(;;){if(t6(c,d))return 1;if(_(b,f+c|0)!==_(e,c))return 0;c=c+1|0}}(0)}function\nfd(a,b){return uR(a,b)?[0,ec(b,0,n(b)-n(a)|0)]:0}var\nit=[q,uT,ae(0)];function\niu(a){return[0,[0,a]]}function\nbp(a,b,c,d){return[1,a,b,c,d]}function\nuV(a){if(0===a[0]&&typeof\na[1]===\"number\")return 1;return 0}function\niv(a,b){if(0===b[0]){var\nc=b[1];if(typeof\nc===\"number\")return iu(a);switch(c[0]){case\n0:return[0,[1,a,c[1]]];case\n1:return[0,[2,a,c[1],c[2]]];default:return bp(4,[1,a,c[1]],uU,[1,c[2],c[3]])}}var\nd=b[2],f=b[1];if(typeof\nd!==\"number\")switch(d[0]){case\n0:break;case\n1:return bp(f+1|0,[2,a,d[1],d[2]],b[3],b[4]);default:var\ne=b[3],h=d[3],i=d[2],j=d[1],g=aw(e),k=aD===g?e[1]:ba===g?cK(e):e;return bp(f+1|0,[1,a,j],[ba,function(a){return iv([0,i,h],k)}],b[4])}return bp(f+1|0,[1,a,d[1]],b[3],b[4])}function\niw(a){if(0===a[0]){var\nb=a[1];if(typeof\nb===\"number\")throw g(it,1);switch(b[0]){case\n0:return[0,uS,b[1]];case\n1:var\nn=b[2];return[0,iu(b[1]),n];default:return[0,[0,[1,b[1],b[2]]],b[3]]}}var\nd=a[3],e=a[2],f=a[1],i=aw(d),j=aD===i?d[1]:ba===i?cK(d):d,h=a[4];if(typeof\nh!==\"number\"&&0!==h[0]){var\nc=a[4];if(typeof\nc!==\"number\"&&2===c[0]){var\nq=c[3];return[0,bp(f-1|0,e,d,[1,c[1],c[2]]),q]}var\np=c[2];return[0,bp(f-1|0,e,d,[0,c[1]]),p]}var\nk=h[1];if(uV(j))return[0,[0,e],k];var\nl=iw(j),m=l[2],o=[1,m[1],m[2]];return[0,bp(f-1|0,e,lI(l[1]),o),k]}function\nuX(a){if(typeof\na===\"number\")return 0;switch(a[0]){case\n0:return 1;case\n1:return 2;default:return 3}}function\nuW(a){try{var\nc=[0,iw(a)];return c}catch(f){var\nb=L(f);if(b===it)return 0;throw g(b,0)}}function\nuY(a){return 0===a[0]?uX(a[1]):a[1]}function\nuZ(a){return a[\"height\"]}function\nu0(a){return a}function\nu3(a){switch(a){case\n0:return u4;case\n1:return u5;default:return u6}}function\nu1(a){return u0(a[\"contentRect\"])}function\nu2(a){a[fy];return}function\nu7(a,b,c){var\nd=b?[0,c,{box:A(u3(b[1]))}]:[0,c];dZ(a,\"observe\",d);return 0}function\nu8(c){return new\nk[\"ResizeObserver\"](function(a,b){return i(c,s0(function(a){return a},a),b)})}var\nu9=jy,u_=\"pattern\",ix=uQ([0,ed]);function\nu$(a,b){h(a,b);return b}function\nva(a){var\nb=fd(vb,a);if(b){var\nc=b[1],d=uE(c);if(d)return[0,[0,d[1]]];var\ng=function(a){return[0,a]};return function(a){return fc(g,a)}(fa(c))}var\ne=fd(vc,a);if(e){var\nh=function(a){return[1,a]};return function(a){return fc(h,a)}(fa(e[1]))}var\nf=fd(vd,a);if(!f)return 0;function\ni(a){return[1,a]}return function(a){return fc(i,a)}(fa(f[1]))}function\niy(a){switch(a[0]){case\n0:var\nb=a[1];return h(C(ve),b);case\n1:var\nc=a[1];return h(C(vf),c);default:var\nd=a[1];return h(C(vg),d)}}function\niz(a){var\nc=a?a[1]:ic(bn);function\nb(a){var\nb=va(as(tq(0,\"font-size\",a)));if(!b)return 16.;var\nc=b[1];return 0===c[0]?c[1]:aK(vh)}return function(a){switch(a[0]){case\n0:return a[1];case\n1:var\nd=a[1];return d*b(ic(bn));default:var\ne=a[1];return e*b(c)}}}function\nvi(e,b,c,d){function\nf(a,b){return cc(d,a,b)}function\ng(a,b){return x(e,b[1],b[2],a)}return function(a){return f(a,g)}(cc(b,c,function(a,b){return[0,a,b]}))}var\nvl=[q,vk,ae(0)],vn=[q,vm,ae(0)];function\niA(a){return[0,0]}function\niB(a,b){if(a[1])throw g(vn,1);a[1]=[0,b];return 0}function\niC(a){var\nb=a[1];if(b)return b[1];throw g(vl,1)}function\nvj(a,b,c){return vi(function(a,b,c){return[0,a,b,c]},a,b,c)}function\nvo(a){return tb(a)}function\nvp(a){var\nb=tc(a);return 0===b[0]?[0,b[1]]:(tC([0,b[1],0]),vq)}var\niD=eu(0,64),iE=tO(dn);function\nvr(a){return pT(iD,a)?aK(h(C(vs),a)):pQ(iD,a,0)}function\niF(c,b){return function(a){return tQ(iE,c,a)}(vo(b))}function\nvt(a){var\nb=tP(iE,a);function\nc(a){return vp(a)}var\nd=b?[0,b[1]]:vu;return uO(d,c)}function\nvv(a,b){var\nc=vt(a);if(0===c[0])return c[1];var\nd=c[1];return typeof\nd===\"number\"?h(b,0):(tE([0,d[2],0]),h(b,0))}function\nvw(d,b){iF(d,b);var\na=am(b),c=eE(0,aP(a));eF(c,function(a){iF(d,bO(c));return 0});bO(c);return a}function\nvx(a,b){vr(a);var\nc=H(a);return vw(c,vv(c,b))}function\niG(a,b){return vx(a,function(a){return b})}var\nvz=ix[49],vy=ix[29];function\nvA(a){return uG(function(a){return[0,80,aS(H(a))]},vz(a))}var\nvB=0;function\na8(d,b,c){var\na=b[1],e=82===a?[0,82,l(b[2],function(a){return function(a){return aR(d,a)}(H(a))})]:83<=a?aK(vE):[0,80,function(a){return aR(d,a)}(H(b[2]))];return[0,e,c]}function\nfe(d,b,c){return b?[0,[0,80,function(a){return aR(d,a)}(H(b[1]))],c]:c}function\niH(a,b){var\nc=b[1];return 82===c?[0,82,l(b[2],a)]:83<=c?[0,83,eV(a,b[2])]:[0,80,h(a,b[2])]}function\nvG(a){return 0===a[0]?aS(H(a[1])):a[1]}function\nff(a,b){return[0,iH(vG,a),b]}function\nau(a){return ff(a,0)}function\nds(a,b){return ff(a,b)}function\nvC(a,b){var\nd=vA(b[1]),e=b[2],c=function(a){return bB(e,a)}(d);return a?[0,[0,80,th(H(a[1]))],c]:c}function\nvD(a){return[0,vy(a),vB]}function\nvF(a,b,c){return b?[0,[0,80,a],c]:c}function\nvH(a){return ff(iH(function(a){return[0,a]},a),0)}function\nvI(a,b){return 0===b[0]?(a.scroll(0,b[1]),0):tr(0,b[1])}function\nvJ(a,b,c,d,e){var\ng=a?a[1]:0,h=b?b[1]:0,f=am(1),i=ds(vK,ds([0,82,l(aP(f),function(a){return a?[1,aS(\"locked\")]:[1,di]})],g)),j=vH(vL),k=[0,[0,80,aB(0,dh,function(a){return ac(f,1)})],0],m=R(0,[0,j],[0,k],0,[0,[0,82,e$(0,0,0,0,[0,[0,80,bo(0,vM)],0])],0]),n=aB(0,ta,function(a){var\nb=bM(f);return b?ac(f,0):b});return R(0,[0,i],[0,[0,[0,80,n],h]],c,[0,[0,82,l(vj(e,aP(f),d),function(a){var\nb=a[1],c=a[3];if(a[2])uJ(function(a){return vI(b,a)},c);return b})],[0,[0,82,m],0]])}function\ndt(a,b){return typeof\nb===\"number\"?0:0===b[0]?[0,h(a,b[1])]:[1,b[1]]}function\nvN(e,b,c){var\nd=am(c);return[0,aB(0,b,function(a){return ac(d,h(e,e1(a)[dE]))}),d]}function\niI(a,b,c,d,e,f,g,h,i,j){var\nl=d?d[1]:0,m=f?f[1]:0,n=function(a){return fe(u_,h,a)}(function(a){return vF(ti,m,a)}([0,[0,80,tk(H(i))],l])),o=uL(b,function(a){return[0,a]}),k=vN(a,g,j),p=k[2],q=k[1];return[0,il(c,[0,n],[0,[0,[0,80,q],uM(e)]],0,0),p,o]}function\ndu(a,b,c,d,e,f,g,h){var\ni=c?c[1]:0,j=function(a){return fe(e6,h,a)}(function(a){return fe(tf,g,a)}(i));return iI(aA,a,b,[0,j],d,e,s_,f,vP,uK(vO,h))}function\ndv(a,b,c,d){var\ne=b?b[1]:0;return iI(function(a){return 0},0,a,[0,a8(e6,d,e)],c,0,e2,0,vQ,0)}function\naC(a,b){return l(a,function(a){return[0,a,b]})}function\ndw(a,b,c,d){return function(g){var\ni=[0,[0,cg,function(a){return a}],function(a,b){var\nc=b[2],d=a[2];return[0,az(a[1],b[1]),function(a){return h(c,h(d,a))}]}];function\nj(a){var\nb=a[1],c=a[2];function\nd(a){var\nc=bM(b[2]);return h(b[3],c)}return[0,J(b[1]),function(a){var\nb=d(0);return h(h(c,a),b)}]}var\ne=function(a){return bj(j,i,a)}(bk(d[2])),f=[0,82,l(e,function(a){var\nb=a[2];return aB(0,u9,function(a){h(g,h(b,d[1]));return s8(a)})})],k=l(e,function(a){return a[1]}),m=uI([0,f,0],function(a){return lU(f,a)},c);return t3(a,b,[0,m],0,[0,[0,83,bk(k)],0])}}function\niJ(a,b){return a?h(C(vR),b):b}function\nvS(a,b,c,d){var\ne=a?a[1]:1,f=b?b[1]:0,g=c?c[1]:0;return function(a){var\nb=iJ(1,d[1]),h=iJ(0,d[1]),c=e?iG(b,d[2]):am(d[2]),i=d[3];im(0,[0,[0,[0,80,h8(H(b))],0]],0,0,i);var\nj=[0,80,h],k=function(a){return a8(e5,vT,a)}(function(a){return a8(h6,j,a)}(a8(e4,[0,80,b],f))),m=[0,[0,80,aB(0,e2,function(a){return ac(c,aA(e1(a)[dE]))})],g];return[0,t5(0,[0,k],[0,m],0,[0,[0,83,bk(eV(function(a){var\nb=a[1],d=a[2],e=au([0,80,[1,tl(H(b))]]),f=ds([0,82,l(aP(c),function(a){return[1,td(t_(a,b),tj)]})],e);return t4(0,[0,f],0,0,[0,[0,80,bo(0,d)],0])},a))],0]),,c]}}function\niK(a,b,c,d,e,f,g){var\nm=b?b[1]:0,n=c?c[1]:function(a){return},j=h(uC(vU),d);function\nk(a){return a?[0,e]:0}a:{if(a&&a[1]){var\no=iG(j,k(g)),i=o;break a}var\ni=am(k(g))}var\np=im(0,[0,[0,[0,80,h8(H(j))],0]],0,0,f),q=[0,80,d],r=function(a){return a8(e5,vV,a)}(function(a){return a8(h6,q,a)}(a8(e4,[0,80,j],0))),s=[0,[0,82,l(aP(i),function(a){return a?tg:di})],r];return[0,R(0,0,0,0,[0,[0,82,il(0,[0,s],[0,[0,[0,80,aB(0,e2,function(a){var\nb=k(e1(a)[jo]|0);h(n,b);return ac(i,b)})],m]],0,0)],[0,[0,82,p],0]]),i]}function\nvW(a){var\nd=ef(a);return[0,,function(a){return uY(a[1])},function(a){return},,function(a,b,c){var\ne=d[4].call(null,b,c,a[2]);return[0,iv(b,a[1]),e]},function(a){var\nc=uW(a[1]);if(!c)return[0,a,0];var\ne=c[1],b=e[2],f=e[1],g=[0,[0,b,d[28].call(null,b,a[2])]];return[0,[0,f,d[7].call(null,b,a[2])],g]},function(a,b){return d[29].call(null,b,a[2])}]}function\nvX(a){var\nb=vW(a);return[0,function(a){b[3].call(null,0);b[3].call(null,0);return}]}function\nvZ(a){return bj(function(a){return J(R(0,0,0,0,a[3]))},aQ,a)}function\nv0(a){return c4(bj(function(a){return a[2]},[0,v4,function(a,b){return i(C(v3),a,b)}],a),function(a){return i(C(v2),v1,a)})}iz(0)(v8);function\nvY(a,b,c){return[0,a,b,c]}function\nv5(a){return v0(a[1][1])}function\nv6(a){var\nb=iy(a[2]),c=[0,[0,80,aS(jn)],0],d=[0,[0,80,aS(\"lwdui-lazy-table-header\")],c],e=[0,[0,80,dj(H(h(C(v7),b)))],d];return R(0,[0,e],0,0,[0,[0,83,bk(vZ(a[1][1]))],0])}var\nv9=vX([0,uD]),dx=k[\"yjs\"];function\nv_(d,b,c){return function(a){var\nr=a[3],s=a[2],f=iA(0),g=iA(0),k=iy(d[2]),u=h(C(wa),k),v=cf(function(a,b){return J([0,eI(a),a,r])},aQ,s);eu(0,2048);(function(a){return v9[1].call(null,50)}(0));var\ne=am(0),m=Q(function(a){return a}),b=eE(0,qS(m,aP(e)));eF(b,function(a){var\nc=bO(b);return c[2]?h(c[1],0):0});bO(b);function\nt(a){return i(C(v$),k,a)}function\nj(a){var\nb=[0,aS(\"row_spacer\"),0];return ib(0,[0,[0,dj(H(t(a))),b]],0)}var\nw=l(bj(function(a){var\nb=a[1],c=a[3],d=a[2],e=a8(ck,wb,0),f=[0,80,dj(H(u))];return b?[0,0,J(R(0,[0,[0,f,e]],0,0,[0,[0,83,bk(i(c,d,b[1]))],0])),0]:[0,1,cg,0]},[0,[0,0,cg,0],function(a,b){var\nf=b[3],g=b[2],c=b[1],d=a[3],e=a[2],h=a[1],k=hI(e),i=hI(g);if(typeof\nk===\"number\")return typeof\ni===\"number\"?[0,((h+d|0)+c|0)+f|0,e,0]:[0,(h+d|0)+c|0,g,f];if(typeof\ni===\"number\")return[0,h,e,(d+c|0)+f|0];var\nl=dr(d+c|0,0)?function(a){return az(e,a)}(az(J(Q(j(d+c|0))),g)):az(e,g);return[0,h,l,f]}],v),function(a){var\nb=a[3],c=a[2],d=a[1],e=dr(d,0)?az(J(Q(j(d))),c):c;return dr(b,0)?az(e,J(Q(j(b)))):e}),x=v6(d),y=u8(function(a,b){var\nd=lV(a);u2(d);var\nc=uZ(u1(d)),f=bM(e);return f?t7(f[1],c)?ac(e,[0,c]):0:ac(e,[0,c])}),z=au(wc),n=R(0,[0,z],0,[0,function(a){return iB(f,a)}],[0,[0,83,bk(w)],0]),o=au(wd),p=[0,[0,82,l(m,function(c){return aB(0,s$,function(a){var\nd=[0,0.],b=[0,-1];function\ne(e){var\na=800,f=tI(tJ);if(t8(b[1],0))tM(b[1]);b[1]=tL(a,function(a){return h(c,e)});var\ng=t9(f-d[1],a);return g?(d[1]=f,h(c,e)):g}iC(g);(function(a){return e(a)}(0));return 0})})],0];function\nq(a){return iB(g,a)}var\nA=c?vJ([0,o],[0,p],[0,q],l(c[1],function(a){var\nb=iC(f),c=d[2];return[0,[0,cC(a,uF(iz([0,b])(c)))]]}),n):R(0,[0,o],[0,p],[0,q],[0,[0,82,n],0]);function\nB(a){return u7(y,0,a)}function\nD(a){return u$(B,a)}var\nE=function(a){return l(a,D)}(A),F=vC(0,vD(we));return R(0,[0,[0,[0,82,l(v5(d),function(a){return dj(H(a))})],F]],0,0,[0,[0,82,x],[0,[0,82,E],0]])}}var\nfg=ef([0,ed]),fh=dx[\"Text\"],fi=dx[jX],fj=dx[\"Map\"],bU=ho(wj,wi),a9=ho(wl,wk);function\nwf(a,b){return[0,a,b]}function\niL(a){return bS(a,fi)?[0,aW,a]:bS(a,fj)?[0,v,a]:bS(a,fh)?[0,bv,a]:[0,T,a]}function\nwm(a){var\nb=eY(a,wn);if(b)return[0,b[1]];var\nc=eY(a,wo);if(c)return[1,hZ(iL,c[1])];var\nd=eY(a,wp);if(d)return[2,d[1]];throw g([0,f,wq],1)}hq(wr,bU,[0,function(a){return new\nfi},function(a,b,c){a.insert(b,h0(function(a){var\nb=a[1];return bv<=b?aW<=b?a[2]:a[2]:v<=b?a[2]:a[2]},c));return 0},function(a,b,c){a.delete(b,c);return 0},function(a,b){a.push(h0(function(a){var\nb=a[1];return bv<=b?aW<=b?a[2]:a[2]:v<=b?a[2]:a[2]},b));return 0},function(a,d){a.forEach(function(a,b,c){return x(d,b,iL(a),c)});return 0},function(a,b){function\nc(a){return h(b,wf(wm,a))}a.observe(c);return c}]);function\nfk(a){return bS(a,fi)?[0,aW,a]:bS(a,fj)?[0,v,a]:bS(a,fh)?[0,bv,a]:[0,T,a]}function\niM(a,b){return function(a){return dg(fk,a)}(a.get(A(b)))}function\nws(a){return a}function\nwt(a){return ws(a[fy])}function\nwu(a){var\nb=aA(a[\"action\"]);if(b!==\"add\")if(b!==jI){if(b!==\"update\")throw g([0,cH,h(C(wv),b)],1);var\nc=1}else\nvar\nc=2;else\nvar\nc=0;var\nd=a[\"oldValue\"],e=bR(d)?0:[0,fk(d)];return[0,c,0,e]}function\niN(a){return s4(a.entries())}hq(ww,a9,[0,function(a){return new\nfj},[0,function(d){var\na=d[jP][\"keys\"].entries();return h1(aA,wu,function(a,b,c){var\ne=iM(wt(d),a);return fg[4].call(null,a,[0,b[1],e,b[3]],c)},a,fg[1])}],iM,function(a,b,c){var\nd=c[1],e=bv<=d?aW<=d?c[2]:c[2]:v<=d?c[2]:c[2];a.set(A(b),e);return 0},function(a,b){a.delete(A(b));return 0},iN,function(a,d,c){return h1(aA,fk,function(a,b,c){return x(d,a,b,c)},iN(a),c)},function(a,b){function\nc(a){return h(b,a)}a.observe(c);return c}]);var\nwx=dx[\"Doc\"];function\niO(a,b){return a.getArray(A(b))}function\nbq(a,b){a.transact(by(1,b));return 0}function\niP(a){return a}var\nai=a9[4],aT=a9[3],cl=a9[1],dy=bU[5],fl=bU[4],iQ=bU[3],iR=bU[1];function\nwg(a){var\nb=a[1];return[0,function(a){return hZ(b,a)}(a[2][jP][\"delta\"])]}function\nwh(a,b){var\nc=a?[0,A(a[1])]:[0];return z1(fh,c)}function\nwy(a){return new\nwx}var\nwz=a9[8],wA=a9[7],wB=a9[5],wC=a9[2][1],wD=bU[6];function\nwE(a){return a}var\nwF=k[\"IndexeddbPersistence\"];function\nwG(a,b){var\nc=iP(b);new\nwF(A(a),c);return}var\nwH=k[\"WebrtcProvider\"];function\nwI(a,b,c){var\ne=d_(function(a){return[0,wJ,e0(A,a)]},b),d=[0,[0,wM,{config:{iceServers:e0(function(a){return a},cM(function(a){return{urls:A(h(C(wL),a))}},wK))}}]];ah([0,d,0]);var\nf=lc(ee(gC(function(a){return a})([0,e,[0,d,0]]))),g=iP(c);return new\nwH(A(a),g,f)}var\niS=k[\"Quill\"],wN=k[\"QuillCursors\"];function\nwP(a){switch(a){case\n0:var\nb=wQ;break;case\n1:var\nb=wR;break;case\n2:var\nb=wS;break;case\n3:var\nb=wT;break;default:var\nb=wU}return A(b)}function\nwO(a,b){iS.register(A(a),b);return}function\nwV(a,b,c,d){var\ne=a?a[1]:0,f=e?wW:wZ,g=d_(function(a){return[0,wX,!!a]},b),h=[0,g,[0,d_(function(a){return[0,wY,e0(wP,a[1])]},c),0]],i=lc(ee(gC(function(a){return a})(h)));return{theme:A(f),modules:i}}function\nw0(a,b){return new\niS(a,b)}function\nw1(a){return a}var\nw2=k[\"QuillBinding\"];function\nw3(a,b){var\nc=w1(b);new\nw2(wE(a),c);return}function\nw4(a,b,c){return x(eq(t,w5),b,c,a)}function\niT(a,b,c){var\nd=0<=c?1:0;if(d)var\ne=0<=b?1:0,f=e?(b+c|0)<=a?1:0:e;else\nvar\nf=d;var\ng=1-f;return g?w4(a,b,c):g}var\nw6=[0];function\nw7(a,b,c,d){var\ne=ap(a,b);cP(c,0,e,0,d);return e}function\niU(a,b){return b<=a?a:b}function\niV(a){return eq(t,a)}function\nw8(a,b){var\nc=a[1];return i(iV(w9),b,c)}function\nw_(a,b){return i(iV(w$),a,b.length-1)}function\ncm(a,b){var\nc=1-(a<=b.length-1?1:0);return c?w_(a,b):c}function\niW(a){return[0,0,0,w6]}function\ncn(a){return a[1]}function\nxa(a,b){return a[3][1+b]}function\niX(a){var\nb=a[1],c=a[3];cm(b,c);if(0>>4|0)));var\nf=b+1|0;function\ni(a,b,c){a0(a,b,c);return}return function(a){return i(d,f,a)}(h(g,c&15))}for(;;){if(4<=d[1])break;var\nn=y(b,d[1]);f(e,c[1],n);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(6<=d[1])break;var\nm=y(b,d[1]);f(e,c[1],m);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(8<=d[1])break;var\nl=y(b,d[1]);f(e,c[1],l);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(10<=d[1])break;var\nk=y(b,d[1]);f(e,c[1],k);c[1]=c[1]+2|0;d[1]++}c[1]++;for(;;){if(16<=d[1])return $(e);var\nj=y(b,d[1]);f(e,c[1],j);c[1]=c[1]+2|0;d[1]++}}var\nxn=gX(0),an=wy(0);wO(xp,wN);var\ndz=wI(xr,xq,an);wG(xs,an);dn[\"yjsdoc\"]=an;dn[\"yjsprovider\"]=dz;dz.on(A(xu),by(1,function(a){return ah(xt)}));dz.on(A(xw),by(1,function(a){return ah([0,xv,[0,a,0]])}));dz.on(A(xy),by(1,function(a){return ah([0,xx,[0,a,0]])}));function\nxo(a){return xk(xn,0)}function\nxz(a,b){var\nc=a?a[1]:64,d=hz(0);return[0,d,eu(0,c)]}function\ni0(a,b,c){var\ne=g4(a[2],b);if(e)var\nd=e[1];else{var\ng=eH(0,a[1]);g5(a[2],b,g);var\nd=g}var\nf=eI(d);return f?ac(f[1][2],[0,c]):rH(d,[0,b,am([0,c])])}function\nfn(a,b){var\nc=g4(a[2],b);if(c)var\nd=c[1];else{var\nf=a[1],e=eH([0,[0,b,am(0)]],f);g5(a[2],b,e);var\nd=e}return aP(cL(eI(d))[2])}function\nfo(a,b){return l(fn(a,b),function(a){if(!a)return 0;var\nb=a[1];if(typeof\nb!==\"number\"&&T===b[1])return[0,aA(b[2])];throw g([0,f,xA],1)})}function\nxB(a){var\nb=hz(0);return[0,b,iW(0)]}function\nxC(a){try{var\nc=[0,iZ(a[2],0)];return c}catch(f){var\nb=L(f);if(b[1]===cH)return 0;throw g(b,0)}}function\ni1(a,b){var\nc=eH(a,b[1]);return xd(b[2],c)}function\ni2(a,b,c,d){var\ne=[0,b,[0,c,[0,cn(d),0]]];e7([0,xD,[0,cn(a),e]]);var\nf=cn(d),g=iZ(a,0);fm(d,gM(c,function(a){return g}));return xh(a,b,d,f,c)}function\nxE(i,b,c){var\ne=[0,0],j=i[2],d=iW(0);gN(function(a){switch(a[0]){case\n0:var\nm=a[1];i2(j,e[1],m,d);e[1]=e[1]+m|0;return 0;case\n1:var\nc=a[1];if(0!==cn(d)){var\no=[0,iX(d)];return fm(d,gO(function(a){var\nd=h(b,a),c=rD([0,d],o[1]);o[1]=c;return c},c))}var\nn=xC(i);if(!n)return gN(function(a){var\nc=h(b,a);return i1([0,c],[0,i[1],d])},c);var\ns=n[1];return fm(d,gO(function(a){return rB([0,h(b,a)],s)},c));default:var\nk=a[1],t=0===e[1]?sk(i[1]):hG(iX(d)),p=[0,t],u=1;if(k>=1){var\nl=u;for(;;){var\nq=p[1];if(!q)throw g([0,f,xF],1);var\nr=q[1];p[1]=hG(r);rK(r);var\nv=l+1|0;if(k===l)break;l=v}}e[1]=e[1]+k|0;return 0}},c);var\nk=e[1],a=cn(j)-k|0;if(0