@univerjs/core 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var Pa=Object.defineProperty;var ka=(e,n,t)=>n in e?Pa(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var _=(e,n,t)=>ka(e,typeof n!="symbol"?n+"":n,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("rxjs"),Cn=require("rxjs/operators"),Pe=require("react");function Fa(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:()=>e[t]})}}return n.default=e,Object.freeze(n)}function Ha(e,n){for(var t=0;t<n.length;t++){const r=n[t];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const o=Object.getOwnPropertyDescriptor(r,s);o&&Object.defineProperty(e,s,o.get?o:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}const st=Fa(Pe);function ja(){$a()}const gn=typeof global<"u"?global:typeof self<"u"?self:window;function $a(){typeof gn.requestIdleCallback!="function"&&(gn.requestIdleCallback=function(t){const r=Date.now();return setTimeout(function(){const o=Math.max(0,50-(Date.now()-r));t({didTimeout:o===0,timeRemaining(){return o}})},1)}),typeof gn.cancelIdleCallback!="function"&&(gn.cancelIdleCallback=function(t){clearTimeout(t)})}const Wa="__default_document_sub_component_id20231101__",Qt=2,xs=1;function Ba(e,n){if(n==null||e==null)return!0;const{left:t=0,top:r=0,height:s=0,width:o=0,angle:i=0}=n,{left:a=0,top:l=0,height:h=0,width:c=0,angle:u=0}=e,d=c,f=h,p=o,m=s;return Math.abs(a-t)>Qt||Math.abs(l-r)>Qt||Math.abs(d-p)>Qt||Math.abs(f-m)>Qt||Math.abs(u-i)>xs}function Ps(e,n){let t=0,r=e.length-1;for(;t<=r;){const s=Math.floor((r+t)/2);if(n<e[s]&&(s===0||n>=e[s-1]))return s;if(n>=e[s])t=s+1;else if(n<e[s])r=s-1;else return-1}return-1}function ks(e,n){let t=0,r=0,s=0,o=-1,i=e.length-1;for(;t<e.length&&i>=0&&i>=t;){if(r=e[i],i===0?s=0:s=e[i-1],n>=s&&n<=r){o=i;break}if(r=e[t],t===0?s=0:s=e[t-1],n>=s&&n<r){o=t;break}t++,i--}return o}function Ga(e,n){let t=e.length-1;return n<0?-1:n<e[0]?0:n>e[e.length-1]?Number.POSITIVE_INFINITY:(e.length<40||n<=e[20]||n>=e[t-20]?t=ks(e,n):t=Ps(e,n),t)}function Va(e){const n=new Blob([e],{type:"text/javascript"});return window.URL.createObjectURL(n)}var Fs=(e=>(e[e.DEFAULT_SERIES=0]="DEFAULT_SERIES",e[e.ALTERNATE_SERIES=1]="ALTERNATE_SERIES",e))(Fs||{}),he=(e=>(e[e.NONE=0]="NONE",e[e.THIN=1]="THIN",e[e.HAIR=2]="HAIR",e[e.DOTTED=3]="DOTTED",e[e.DASHED=4]="DASHED",e[e.DASH_DOT=5]="DASH_DOT",e[e.DASH_DOT_DOT=6]="DASH_DOT_DOT",e[e.DOUBLE=7]="DOUBLE",e[e.MEDIUM=8]="MEDIUM",e[e.MEDIUM_DASHED=9]="MEDIUM_DASHED",e[e.MEDIUM_DASH_DOT=10]="MEDIUM_DASH_DOT",e[e.MEDIUM_DASH_DOT_DOT=11]="MEDIUM_DASH_DOT_DOT",e[e.SLANT_DASH_DOT=12]="SLANT_DASH_DOT",e[e.THICK=13]="THICK",e))(he||{}),Hs=(e=>(e.TOP="top",e.BOTTOM="bottom",e.LEFT="left",e.RIGHT="right",e.NONE="none",e.ALL="all",e.OUTSIDE="outside",e.INSIDE="inside",e.HORIZONTAL="horizontal",e.VERTICAL="vertical",e.TLBR="tlbr",e.TLBC_TLMR="tlbc_tlmr",e.TLBR_TLBC_TLMR="tlbr_tlbc_tlmr",e.BLTR="bl_tr",e.MLTR_BCTR="mltr_bctr",e))(Hs||{}),qe=(e=>(e[e.UNSUPPORTED=0]="UNSUPPORTED",e[e.RGB=1]="RGB",e[e.HEX=2]="HEX",e[e.THEME=3]="THEME",e))(qe||{}),js=(e=>(e[e.ON=0]="ON",e[e.OFF=1]="OFF",e))(js||{}),$s=(e=>(e[e.PASTE_NORMAL=0]="PASTE_NORMAL",e[e.PASTE_NO_BORDERS=1]="PASTE_NO_BORDERS",e[e.PASTE_FORMAT=2]="PASTE_FORMAT",e[e.PASTE_FORMULA=3]="PASTE_FORMULA",e[e.PASTE_DATA_VALIDATION=4]="PASTE_DATA_VALIDATION",e[e.PASTE_VALUES=5]="PASTE_VALUES",e[e.PASTE_CONDITIONAL_FORMATTING=6]="PASTE_CONDITIONAL_FORMATTING",e[e.PASTE_COLUMN_WIDTHS=7]="PASTE_COLUMN_WIDTHS",e))($s||{}),Ws=(e=>(e[e.DOCUMENT=0]="DOCUMENT",e[e.PROJECT=1]="PROJECT",e))(Ws||{}),Bs=(e=>(e[e.COLUMNS=0]="COLUMNS",e[e.ROWS=1]="ROWS",e))(Bs||{}),Gs=(e=>(e[e.UP=0]="UP",e[e.RIGHT=1]="RIGHT",e[e.DOWN=2]="DOWN",e[e.LEFT=3]="LEFT",e))(Gs||{});function Ka(e){switch(e){case 3:return 1;case 1:return 3;case 0:return 2;case 2:return 0}}var Vs=(e=>(e[e.NUMBER_FORMAT_TYPE_UNSPECIFIED=0]="NUMBER_FORMAT_TYPE_UNSPECIFIED",e[e.TEXT=1]="TEXT",e[e.NUMBER=2]="NUMBER",e[e.PERCENT=3]="PERCENT",e[e.CURRENCY=4]="CURRENCY",e[e.DATE=5]="DATE",e[e.TIME=6]="TIME",e[e.DATE_TIME=7]="DATE_TIME",e[e.SCIENTIFIC=8]="SCIENTIFIC",e))(Vs||{}),Ks=(e=>(e[e.INTERPOLATION_POINT_TYPE_UNSPECIFIED=0]="INTERPOLATION_POINT_TYPE_UNSPECIFIED",e[e.MIN=1]="MIN",e[e.MAX=2]="MAX",e[e.NUMBER=3]="NUMBER",e[e.PERCENT=4]="PERCENT",e[e.PERCENTILE=5]="PERCENTILE",e))(Ks||{}),Pt=(e=>(e.EN_US="enUS",e.ZH_CN="zhCN",e.RU_RU="ruRU",e.ZH_TW="zhTW",e.VI_VN="viVN",e))(Pt||{}),zs=(e=>(e[e.RANGE=0]="RANGE",e[e.SHEET=1]="SHEET",e))(zs||{}),Ys=(e=>(e[e.RELATIVE_DATE_UNSPECIFIED=0]="RELATIVE_DATE_UNSPECIFIED",e[e.PAST_YEAR=1]="PAST_YEAR",e[e.PAST_MONTH=2]="PAST_MONTH",e[e.PAST_WEEK=3]="PAST_WEEK",e[e.YESTERDAY=4]="YESTERDAY",e[e.TODAY=5]="TODAY",e[e.TOMORROW=6]="TOMORROW",e))(Ys||{}),Hn=(e=>(e[e.GRID=0]="GRID",e[e.KANBAN=1]="KANBAN",e[e.GANTT=2]="GANTT",e))(Hn||{}),on=(e=>(e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LEFT_TO_RIGHT=1]="LEFT_TO_RIGHT",e[e.RIGHT_TO_LEFT=2]="RIGHT_TO_LEFT",e))(on||{}),Xs=(e=>(e[e.DASH=0]="DASH",e[e.DASH_DOT_DOT_HEAVY=1]="DASH_DOT_DOT_HEAVY",e[e.DASH_DOT_HEAVY=2]="DASH_DOT_HEAVY",e[e.DASHED_HEAVY=3]="DASHED_HEAVY",e[e.DASH_LONG=4]="DASH_LONG",e[e.DASH_LONG_HEAVY=5]="DASH_LONG_HEAVY",e[e.DOT_DASH=6]="DOT_DASH",e[e.DOT_DOT_DASH=7]="DOT_DOT_DASH",e[e.DOTTED=8]="DOTTED",e[e.DOTTED_HEAVY=9]="DOTTED_HEAVY",e[e.DOUBLE=10]="DOUBLE",e[e.NONE=11]="NONE",e[e.SINGLE=12]="SINGLE",e[e.THICK=13]="THICK",e[e.WAVE=14]="WAVE",e[e.WAVY_DOUBLE=15]="WAVY_DOUBLE",e[e.WAVY_HEAVY=16]="WAVY_HEAVY",e[e.WORDS=17]="WORDS",e))(Xs||{}),Dt=(e=>(e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LEFT=1]="LEFT",e[e.CENTER=2]="CENTER",e[e.RIGHT=3]="RIGHT",e[e.JUSTIFIED=4]="JUSTIFIED",e))(Dt||{}),Wt=(e=>(e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.TOP=1]="TOP",e[e.MIDDLE=2]="MIDDLE",e[e.BOTTOM=3]="BOTTOM",e))(Wt||{}),Bt=(e=>(e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.OVERFLOW=1]="OVERFLOW",e[e.CLIP=2]="CLIP",e[e.WRAP=3]="WRAP",e))(Bt||{}),Tn=(e=>(e[e.NORMAL=0]="NORMAL",e[e.ITALIC=1]="ITALIC",e))(Tn||{}),yn=(e=>(e[e.NORMAL=0]="NORMAL",e[e.BOLD=1]="BOLD",e))(yn||{}),Gt=(e=>(e[e.NORMAL=1]="NORMAL",e[e.SUBSCRIPT=2]="SUBSCRIPT",e[e.SUPERSCRIPT=3]="SUPERSCRIPT",e))(Gt||{}),K=(e=>(e[e.FALSE=0]="FALSE",e[e.TRUE=1]="TRUE",e))(K||{}),Mt=(e=>(e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER",e[e.BOOLEAN=3]="BOOLEAN",e[e.FORCE_STRING=4]="FORCE_STRING",e))(Mt||{}),He=(e=>(e[e.DARK1=0]="DARK1",e[e.LIGHT1=1]="LIGHT1",e[e.DARK2=2]="DARK2",e[e.LIGHT2=3]="LIGHT2",e[e.ACCENT1=4]="ACCENT1",e[e.ACCENT2=5]="ACCENT2",e[e.ACCENT3=6]="ACCENT3",e[e.ACCENT4=7]="ACCENT4",e[e.ACCENT5=8]="ACCENT5",e[e.ACCENT6=9]="ACCENT6",e[e.HYPERLINK=10]="HYPERLINK",e[e.FOLLOWED_HYPERLINK=11]="FOLLOWED_HYPERLINK",e))(He||{}),jn=(e=>(e.OFFICE="Office",e.OFFICE_2007_2010="Office 2007-2010",e.GRAYSCALE="Grayscale",e.BLUE_WARM="Blue Warm",e.BLUE="Blue",e.BLUE_II="Blue II",e.BLUE_GREEN="Blue Green",e.GREEN="Green",e.GREEN_YELLOW="Green Yellow",e.YELLOW="Yellow",e.YELLOW_ORANGE="Yellow Orange",e.ORANGE="Orange",e.ORANGE_RED="Orange Red",e.RED_ORANGE="Red Orange",e.RED="Red",e.RED_VIOLET="Red Violet",e.VIOLET="Violet",e.VIOLET_II="Violet II",e.MEDIAN="Median",e.PAPER="Paper",e.MARQUEE="Marquee",e.SLIPSTREAM="Slipstream",e.Aspect="Aspect",e))(jn||{}),Qs=(e=>(e.Line="line",e.LineInv="lineInv",e.Triangle="triangle",e.RtTriangle="rtTriangle",e.Rect="rect",e.Diamond="diamond",e.Parallelogram="parallelogram",e.Trapezoid="trapezoid",e.NonIsocelesTrapezoid="nonIsocelesTrapezoid",e.Pentagon="pentagon",e.Hexagon="hexagon",e.Heptagon="heptagon",e.Octagon="octagon",e.Decagon="decagon",e.Dodecagon="dodecagon",e.Star4="star4",e.Star5="star5",e.Star6="star6",e.Star7="star7",e.Star8="star8",e.Star10="star10",e.Star12="star12",e.Star16="star16",e.Star24="star24",e.Star32="star32",e.RoundRect="roundRect",e.Round1Rect="round1Rect",e.Round2SameRect="round2SameRect",e.Round2DiagRect="round2DiagRect",e.Ellipse="ellipse",e))(Qs||{}),qs=(e=>(e.RightArrow="rightArrow",e.LeftArrow="leftArrow",e.UpArrow="upArrow",e.DownArrow="downArrow",e.LeftRightArrow="leftRightArrow",e.UpDownArrow="upDownArrow",e.QuadArrow="quadArrow",e.LeftRightUpArrow="leftRightUpArrow",e.BentArrow="bentArrow",e.UturnArrow="uturnArrow",e.CircularArrow="circularArrow",e.NotchedRightArrow="notchedRightArrow",e.HomePlate="homePlate",e.Chevron="chevron",e.LeftCircularArrow="leftCircularArrow",e.LeftRightCircularArrow="leftRightCircularArrow",e))(qs||{}),Zs=(e=>(e.Plaque="plaque",e.Can="can",e.Cube="cube",e.Bevel="bevel",e.Donut="donut",e.NoSmoking="noSmoking",e.BlockArc="blockArc",e.FoldedCorner="foldedCorner",e))(Zs||{}),Js=(e=>(e.SmileyFace="smileyFace",e.Heart="heart",e.LightningBolt="lightningBolt",e.Sun="sun",e.Moon="moon",e.Cloud="cloud",e.Arc="arc",e.Backpack="backpack",e.Frame="frame",e.HalfFrame="halfFrame",e.Corner="corner",e.Chord="chord",e.Pie="pie",e.Teardrop="teardrop",e.WedgeRectCallout="wedgeRectCallout",e.WedgeRRectCallout="wedgeRRectCallout",e.WedgeEllipseCallout="wedgeEllipseCallout",e.CloudCallout="cloudCallout",e.BorderCallout1="borderCallout1",e.BorderCallout2="borderCallout2",e.BorderCallout3="borderCallout3",e.AccentCallout1="accentCallout1",e.AccentCallout2="accentCallout2",e.AccentCallout3="accentCallout3",e.Callout1="callout1",e.Callout2="callout2",e.Callout3="callout3",e.ActionButtonBackPrevious="actionButtonBackPrevious",e.ActionButtonEnd="actionButtonEnd",e.ActionButtonForwardNext="actionButtonForwardNext",e.ActionButtonHelp="actionButtonHelp",e.ActionButtonHome="actionButtonHome",e.ActionButtonInformation="actionButtonInformation",e.ActionButtonMovie="actionButtonMovie",e.ActionButtonReturn="actionButtonReturn",e.ActionButtonSound="actionButtonSound",e))(Js||{});const eo={[jn.OFFICE]:{[He.ACCENT1]:"#4472C4",[He.ACCENT2]:"#ED7D31",[He.ACCENT3]:"#A5A5A5",[He.ACCENT4]:"#70AD47",[He.ACCENT5]:"#5B9BD5",[He.ACCENT6]:"#70AD47",[He.DARK1]:"#000000",[He.DARK2]:"#44546A",[He.LIGHT1]:"#FFFFFF",[He.LIGHT2]:"#E7E6E6",[He.HYPERLINK]:"#0563C1",[He.FOLLOWED_HYPERLINK]:"#954F72"}};class $n{constructor(){_(this,"_themeValue",He.LIGHT1);_(this,"_themeColors");_(this,"_themeTint");_(this,"_rgbValue","");_(this,"_colorType");this._colorType=qe.UNSUPPORTED,this._themeColors=jn.OFFICE,this._themeTint=0}asRgbColor(){return new Dn(this._rgbValue,this)}asThemeColor(){return new Mn(this._themeValue,this._themeTint,this._themeColors,this)}build(){switch(this._colorType){case qe.THEME:return this.asThemeColor();case qe.RGB:return this.asRgbColor();case qe.UNSUPPORTED:throw new Error("unsupported color type")}}setRgbColor(n){return this._colorType=qe.RGB,this._rgbValue=n,this}setThemeColors(n){this._colorType=qe.THEME,this._themeColors=n}setThemeTint(n){this._colorType=qe.THEME,this._themeTint=n}setThemeColor(n){return this._colorType=qe.THEME,this._themeValue=n,this}getColorType(){return this._colorType}}class Ut{constructor(n){_(this,"_builder");this._builder=n}static rgbColorToHexValue(n){return`#${((1<<24)+(n.getRed()<<16)+(n.getGreen()<<8)+n.getBlue()).toString(16).slice(1)}`}static hexValueToRgbColor(n){n?n.indexOf("#")>-1&&(n=n.substring(1)):n="#000000";const t=+`0x${n[0]}${n[1]}`,r=+`0x${n[2]}${n[3]}`,s=+`0x${n[4]}${n[5]}`;return new $n().setRgbColor(`rgb(${t},${r},${s})`).asRgbColor()}static hexToRgbString(n){const t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;n=n.replace(t,(o,i,a,l)=>i+i+a+a+l+l);const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(n);let s=null;if(r){const o=Number.parseInt(r[1],16),i=Number.parseInt(r[2],16),a=Number.parseInt(r[3],16);s=`rgba(${o},${i},${a})`}return s}asRgbColor(){return this._builder.asRgbColor()}asThemeColor(){return this._builder.asThemeColor()}getColorType(){return this._builder.getColorType()}clone(){return new Ut(this._builder)}equals(n){return!1}}class to{constructor(n){_(this,"_saturation",0);_(this,"_hue",0);_(this,"_lightness",0);_(this,"_alpha",0);const t=n.getRed()/255,r=n.getGreen()/255,s=n.getBlue()/255,o=n.getAlpha()/255,i=Math.min(t,Math.min(r,s)),a=Math.max(t,Math.max(r,s)),l=a-i;if(a===i){this._hue=0,this._saturation=0,this._lightness=a;return}this._lightness=(i+a)/2,this._lightness<.5?this._saturation=l/(a+i):this._saturation=l/(2-a-i),t===a&&(this._hue=(r-s)/l),r===a&&(this._hue=2+(s-t)/l),s===a&&(this._hue=4+(t-r)/l),this._hue*=60,this._hue<0&&(this._hue+=360),this._alpha=o}asRgbColor(){const n=new $n;if(this._saturation===0)return n.setRgbColor(`rgba(${this._lightness*255},${this._lightness*255},${this._lightness*255},${this._alpha*255})`),n.asRgbColor();let t;this._lightness<.5?t=this._lightness*(1+this._saturation):t=this._lightness+this._saturation-this._lightness*this._saturation;const r=2*this._lightness-t,s=this._hue/360,o=s+1/3,i=this.setColor(t,r,o),a=this.setColor(t,r,s),l=s-1/3,h=this.setColor(t,r,l);return n.setRgbColor(`rgba(${Math.round(i*255)},${Math.round(a*255)},${Math.round(h*255)},${this._alpha*255})`),n.asRgbColor()}getLightness(){return this._lightness}getHue(){return this._hue}getSaturation(){return this._saturation}getAlpha(){return this._alpha}setColor(n,t,r){r<0&&(r+=1),r>1&&(r-=1);let s;return 6*r<1?s=t+(n-t)*6*r:2*r<1?s=n:3*r<2?s=t+(n-t)*(2/3-r)*6:s=t,s}setLightness(n){this._lightness=n}}const Qe=class Qe extends Ut{constructor(t,r){super(r);_(this,"_cssString");_(this,"_red");_(this,"_green");_(this,"_blue");_(this,"_alpha");let s=t.match(Qe.RGBA_EXTRACT);if(s){const o=+s[1],i=+s[2],a=+s[3],l=+s[4];this._cssString=t,this._red=o,this._green=i,this._blue=a,this._alpha=l;return}if(s=t.match(Qe.RGB_EXTRACT),s){const o=+s[1],i=+s[2],a=+s[3];this._cssString=t,this._red=o,this._green=i,this._blue=a,this._alpha=1;return}throw new Error("Invalid rgba or rgb color")}asHexString(){return Ut.rgbColorToHexValue(this)}getRed(){let t=this._red+Qe.RGB_COLOR_AMT;return t>255?t=255:t<0&&(t=0),t}getGreen(){let t=this._green+Qe.RGB_COLOR_AMT;return t>255?t=255:t<0&&(t=0),t}getBlue(){let t=this._blue+Qe.RGB_COLOR_AMT;return t>255?t=255:t<0&&(t=0),t}getAlpha(){return this._alpha}getColorType(){return qe.RGB}clone(){return new Qe(this._cssString,this._builder)}asThemeColor(){throw new Error("rgb color not support to themeColor")}equals(t){return t instanceof Qe?t._red===this._red&&t._blue===this._blue&&t._green===this._green&&t._alpha===this._alpha:!1}getCssString(){return this._cssString}};_(Qe,"RGB_COLOR_AMT",0),_(Qe,"RGBA_EXTRACT",new RegExp("\\s*rgba\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d.\\d|\\d\\s*)\\)\\s*")),_(Qe,"RGB_EXTRACT",new RegExp("\\s*rgb\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*)\\)\\s*"));let Dn=Qe;const Ct=class Ct extends Ut{constructor(t,r,s,o){super(o);_(this,"_themeColorType");_(this,"_themeTint");_(this,"_themeColors");this._themeColorType=t,this._themeTint=r,this._themeColors=s}lumValue(t,r){if(t==null)return r;let s;return t<0?s=r*(1+t):s=r*(1-t)+(255-255*(1-t)),s}asRgbColor(){const t=eo[this._themeColors];if(t==null)throw new Error("not find themeColors type");const r=t[this._themeColorType];if(r==null)throw new Error("not find themeColors value");let s;if(Ct._cacheThemeColor.has(this._themeColors)){if(s=Ct._cacheThemeColor.get(this._themeColors),s.has(this._themeColorType))return s.get(this._themeColorType)}else s=new Map,Ct._cacheThemeColor.set(this._themeColors,s);const o=new to(Ut.hexValueToRgbColor(r));o.setLightness(this.lumValue(this._themeTint,o.getLightness()*255)/255);const i=o.asRgbColor();return s.set(this._themeColorType,i),i}clone(){return new Ct(this._themeColorType,this._themeTint,this._themeColors,this._builder)}equals(t){return t instanceof Ct?t._themeColorType===this._themeColorType:!1}getColorType(){return qe.THEME}getThemeColorType(){return this._themeColorType}};_(Ct,"_cacheThemeColor",new Map);let Mn=Ct;const za="rgb(",Ya="rgba(",lr={aliceBlue:[240,248,255],antiqueWhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blancheAlmond:[255,235,205],blue:[0,0,255],blueViolet:[138,43,226],brown:[165,42,42],burlyWood:[222,184,135],cadetBlue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornFlowerBlue:[100,149,237],cornSilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkCyan:[0,139,139],darkGoldenrod:[184,132,11],darkGray:[169,169,169],darkGreen:[0,100,0],darkGrey:[169,169,169],darkKhaki:[189,183,107],darkMagenta:[139,0,139],darkOliveGreen:[85,107,47],darkOrange:[255,140,0],darkOrchid:[153,50,204],darkRed:[139,0,0],darkSalmon:[233,150,122],darkSeaGreen:[143,188,143],darkSlateBlue:[72,61,139],darkSlateGray:[47,79,79],darkSlateGrey:[47,79,79],darkTurquoise:[0,206,209],darkViolet:[148,0,211],deepPink:[255,20,147],deepSkyBlue:[0,191,255],dimGray:[105,105,105],dimGrey:[105,105,105],dodgerBlue:[30,144,255],firebrick:[178,34,34],floralWhite:[255,255,240],forestGreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostWhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenYellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotPink:[255,105,180],indianRed:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderBlush:[255,240,245],lawnGreen:[124,252,0],lemonChiffon:[255,250,205],lightblue:[173,216,230],lightCoral:[240,128,128],lightCyan:[224,255,255],lightGoldenrodYellow:[250,250,210],lightGray:[211,211,211],lightGreen:[144,238,144],lightGrey:[211,211,211],lightPink:[255,182,193],lightSalmon:[255,160,122],lightSeaGreen:[32,178,170],lightSkyBlue:[135,206,250],lightSlateGray:[119,136,153],lightSlateGrey:[119,136,153],lightSteelBlue:[176,196,222],lightYellow:[255,255,224],lime:[0,255,0],limeGreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumAquamarine:[102,205,170],mediumBlue:[0,0,205],mediumOrchid:[186,85,211],mediumPurple:[147,112,219],mediumSeaGreen:[60,179,113],mediumSlateBlue:[123,104,238],mediumSpringGreen:[0,250,154],mediumTurquoise:[72,209,204],mediumVioletRed:[199,21,133],midBightBlue:[25,25,112],mintCream:[245,255,250],mistyRose:[255,228,225],moccasin:[255,228,181],navajoWhite:[255,222,173],navy:[0,0,128],oldLace:[253,245,230],olive:[128,128,0],oliveDrab:[107,142,35],orange:[255,165,0],orangeRed:[255,69,0],orchid:[218,112,214],paleGoldenrod:[238,232,170],paleGreen:[152,251,152],paleTurquoise:[175,238,238],paleVioletRed:[219,112,147],papayaWhip:[255,239,213],peachPuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderBlue:[176,224,230],purple:[128,0,128],rebeccaPurple:[102,51,153],red:[255,0,0],rosyBrown:[188,143,143],royalBlue:[65,105,225],saddleBrown:[139,69,19],salmon:[250,128,114],sandyBrown:[244,164,96],seaGreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyBlue:[135,206,235],slateBlue:[106,90,205],slateGray:[119,128,144],slateGrey:[119,128,144],snow:[255,255,250],springGreen:[0,255,127],steelBlue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whiteSmoke:[245,245,245],yellow:[255,255,0],yellowGreen:[154,205,5]};class rt{constructor(n){_(this,"_color");_(this,"_rgbColor");_(this,"_isValid",!1);if(n==null){this._setNullColor();return}if(n instanceof rt){this._color={...n._color},this._rgbColor={...n._rgbColor};return}const t=no(n);if(t==null){this._setNullColor();return}this._color=t;const r=Ja(this._color);if(r==null){this._setNullColor();return}this._rgbColor=r,this._isValid=!0}static mix(n,t,r){var h,c;r=Math.min(1,Math.max(0,r));const s=new rt(n).toRgb(),o=new rt(t).toRgb(),i=(h=s.a)!=null?h:1,a=(c=o.a)!=null?c:1,l={r:(o.r-s.r)*r+s.r,g:(o.g-s.g)*r+s.g,b:(o.b-s.b)*r+s.b,a:(a-i)*r+i};return new rt(l)}static getContrastRatio(n,t){const r=new rt(n).getLuminance(),s=new rt(t).getLuminance();return(Math.max(r,s)+.05)/(Math.min(r,s)+.05)}get isValid(){return this._isValid}toRgb(){return this._rgbColor}toRgbString(){const{r:n,g:t,b:r,a:s=1}=this.toRgb(),o=s<1;return`rgb${o?"a":""}(${n},${t},${r}${o?`,${s}`:""})`}toString(){return this.toRgbString()}toHexString(n){const{r:t,g:r,b:s,a:o=1}=this.toRgb(),i=o<1,a=[pn(Math.round(t).toString(16)),pn(Math.round(r).toString(16)),pn(Math.round(s).toString(16)),pn(Math.round(o*255).toString(16))];return n&&a[0][0]===a[0][1]&&a[1][0]===a[1][1]&&a[2][0]===a[2][1]&&a[3][0]===a[3][1]?i?`#${a[0][0]}${a[1][0]}${a[2][0]}${a[3][0]}`:`#${a[0][0]}${a[1][0]}${a[2][0]}`:i?`#${a[0]}${a[1]}${a[2]}${a[3]}`:`#${a[0]}${a[1]}${a[2]}`}toHsv(){return rl(this.toRgb())}toHsl(){return nl(this.toRgb())}lighten(n=10){const t=this.toHsl();return t.l+=n,t.l=Math.min(Math.max(t.l,0),100),new rt(t)}darken(n=10){const t=this.toHsl();return t.l-=n,t.l=Math.min(Math.max(t.l,0),100),new rt(t)}setAlpha(n){return new rt({...this._rgbColor,a:n})}getLuminance(){let{r:n,g:t,b:r}=this.toRgb();return n=er(n),t=er(t),r=er(r),Number((.2126*n+.7152*t+.0722*r).toFixed(3))}getBrightness(){const{r:n,g:t,b:r}=this.toRgb();return(n*299+t*587+r*114)/1e3}getAlpha(){var n;return(n=this._color.a)!=null?n:1}isDark(){return this.getBrightness()<128}isLight(){return!this.isDark()}_setNullColor(){this._isValid=!1,this._color={r:0,g:0,b:0,a:0},this._rgbColor={r:0,g:0,b:0,a:0}}}const pn=e=>e.length===1?`0${e}`:e,er=e=>(e/=255,e<=.03928?e/12.92:((e+.055)/1.055)**2.4),no=e=>{if(ol(e)){if("r"in e){const r={r:Math.round(e.r),g:Math.round(e.g),b:Math.round(e.b)};return e.a!==void 0&&(r.a=e.a),r}if("l"in e){const r={h:Math.round(e.h),s:e.s,l:e.l};return e.a!==void 0&&(r.a=e.a),r}const t={h:Math.round(e.h),s:e.s,v:e.v};return e.a!==void 0&&(t.a=e.a),t}const n=e.trim();if(lr[n]){const t=lr[n],r={r:Math.round(t[0]),g:Math.round(t[1]),b:Math.round(t[2])};return r.a=t[3]||1,r}if(n.startsWith("#"))return Xa(n);if(n.startsWith("rgb"))return Qa(n);if(n.startsWith("hsl"))return qa(n);if(n.startsWith("hsv"))return Za(n)},Xa=e=>{const n=e.substring(1),t=new RegExp(`.{1,${n.length>=6?2:1}}`,"g");let r=n.match(t);if(!r||r.length<3)throw new Error(`The color '${e}' is illegal hex color`);r[0].length===1&&(r=r.map(o=>o+o));const s={r:Number.parseInt(r[0],16),g:Number.parseInt(r[1],16),b:Number.parseInt(r[2],16)};return r.length>3&&(s.a=Number.parseInt(r[3],16)/255),s},Qa=e=>{const n=e.indexOf("(");if(n===-1)throw new Error(`The color '${e}' is illegal rgb color`);const t=e.substring(n+1,e.length-1).split(",");if(t.length<3)throw new Error(`The color '${e}' is illegal rgb color`);const r={r:Number.parseInt(t[0],10),g:Number.parseInt(t[1],10),b:Number.parseInt(t[2],10)};return t.length>3&&(r.a=Number.parseFloat(t[3])),r},qa=e=>{const n=e.indexOf("(");if(n===-1)throw new Error(`The color '${e}' is illegal hsl color`);const t=e.substring(n+1,e.length-1).split(",");if(t.length<3)throw new Error(`The color '${e}' is illegal hsl color`);const r={h:Number.parseInt(t[0],10),s:Number.parseFloat(t[1]),l:Number.parseFloat(t[2])};return t.length>3&&(r.a=Number.parseFloat(t[3])),r},Za=e=>{const n=e.indexOf("(");if(n===-1)throw new Error(`The color '${e}' is illegal hsv color`);const t=e.substring(n+1,e.length-1).split(",");if(t.length<3)throw new Error(`The color '${e}' is illegal hsv color`);const r={h:Number.parseInt(t[0],10),s:Number.parseFloat(t[1]),v:Number.parseFloat(t[2])};return t.length>3&&(r.a=Number.parseFloat(t[3])),r},Ja=e=>{const n=no(e);if(n!=null)return"r"in n?n:"l"in n?el(n):tl(n)},tr=(e,n,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?e+(n-e)*6*t:t<1/2?n:t<2/3?e+(n-e)*(2/3-t)*6:e),el=e=>{let{h:n,s:t,l:r}=e;n/=360,t/=100,r/=100;let s=0,o=0,i=0;if(t===0)s=o=i=r;else{const l=r<.5?r*(1+t):r+t-r*t,h=2*r-l;s=tr(h,l,n+1/3),o=tr(h,l,n),i=tr(h,l,n-1/3)}const a={r:Math.round(s*255),g:Math.round(o*255),b:Math.round(i*255)};return e.a!==void 0&&(a.a=e.a),a},tl=e=>{let{h:n,s:t,v:r}=e;n=n/360*6,t/=100,r/=100;const s=Math.floor(n),o=n-s,i=r*(1-t),a=r*(1-o*t),l=r*(1-(1-o)*t),h=s%6,c=[r,a,i,i,l,r][h],u=[l,r,r,a,i,i][h],d=[i,i,l,r,r,a][h],f={r:c*255,g:u*255,b:d*255};return e.a!==void 0&&(f.a=e.a),f},nl=e=>{let{r:n,g:t,b:r}=e;n/=255,t/=255,r/=255;const s=Math.max(n,t,r),o=Math.min(n,t,r),i=(s+o)/2;let a,l;if(s===o)a=l=0;else{const c=s-o;switch(l=i>.5?c/(2-s-o):c/(s+o),s){case n:a=(t-r)/c+(t<r?6:0);break;case t:a=(r-n)/c+2;break;default:a=(n-t)/c+4;break}a/=6}const h={h:Math.round(a*360),s:Math.round(l*100),l:Math.round(i*100)};return e.a!==void 0&&(h.a=e.a),h},rl=e=>{let{r:n,g:t,b:r}=e;n/=255,t/=255,r/=255;const s=Math.max(n,t,r),o=Math.min(n,t,r);let i;const a=s,l=s-o,h=s===0?0:l/s;if(s===o)i=0;else{switch(s){case n:i=(t-r)/l+(t<r?6:0);break;case t:i=(r-n)/l+2;break;default:i=(n-t)/l+4;break}i/=6}const c={h:Math.round(i*360),s:Math.round(h*100),v:Math.round(a*100)};return e.a!==void 0&&(c.a=e.a),c},sl=e=>e==null,ol=e=>!sl(e)&&typeof e=="object";function il(e){const n=/^#(?:[0]{3}|[0]{6})\b/,t=/^rgb\s*\(\s*0+\s*,\s*0+\s*,\s*0+\s*\)$/,r=/^rgba\s*\(\s*0+\s*,\s*0+\s*,\s*0+\s*,\s*(1|1\.0*|0?\.\d+)\)$/,s=/^hsl\s*\(\s*0*\s*,\s*0%*\s*,\s*0%*\s*\)$/,o=/^hsla\s*\(\s*0*\s*,\s*0%*\s*,\s*0%*\s*,\s*(1|1\.0*|0?\.\d+)\)$/;return!!(n.test(e)||t.test(e)||r.test(e)||s.test(e)||o.test(e))}function al(e){const n=/^#(?:[Ff]{3}|[Ff]{6})\b/,t=/^rgb\s*\(\s*255\s*,\s*255\s*,\s*255\s*\)$/,r=/^rgba\s*\(\s*255\s*,\s*255\s*,\s*255\s*,\s*(1|1\.0*|0?\.\d+)\)$/,s=/^hsl\s*\(\s*0*\s*,\s*0%*\s*,\s*100%*\s*\)$/,o=/^hsla\s*\(\s*0*\s*,\s*0%*\s*,\s*100%*\s*,\s*(1|1\.0*|0?\.\d+)\)$/;return!!(n.test(e)||t.test(e)||r.test(e)||s.test(e)||o.test(e))}var ke=(e=>(e[e.COVER=0]="COVER",e[e.REPLACE=1]="REPLACE",e[e.INTERSECTION=2]="INTERSECTION",e))(ke||{});function ll(e){return e&&(e.s!==void 0||e.p!==void 0||e.v!==void 0||e.t!==void 0||e.f!==void 0||e.si!==void 0)}function ul(e){if(e.t!==void 0)return e.t;if(typeof e.v=="string")return Mt.STRING;if(typeof e.v=="number")return Mt.NUMBER;if(typeof e.v=="boolean")return Mt.BOOLEAN}function cl(e){if(e==null)return!0;const{v:n,f:t,si:r,p:s,s:o,custom:i}=e;return!(!(n==null||typeof n=="string"&&n.length===0)||t!=null&&t.length>0||r!=null&&r.length>0||s!=null||i!=null)}function hl(e){return e!=null&&(typeof e=="string"||typeof e=="number"||typeof e=="boolean")}var ro=(e=>(e[e.character=0]="character",e[e.paragraph=1]="paragraph",e[e.table=2]="table",e[e.numbering=3]="numbering",e))(ro||{}),so=(e=>(e[e.TAB=0]="TAB",e[e.SPACE=1]="SPACE",e[e.NOTHING=2]="NOTHING",e))(so||{}),Jt=(e=>(e[e.GLYPH_TYPE_UNSPECIFIED=0]="GLYPH_TYPE_UNSPECIFIED",e[e.NONE=1]="NONE",e[e.DECIMAL=2]="DECIMAL",e[e.ZERO_DECIMAL=3]="ZERO_DECIMAL",e[e.UPPER_ALPHA=4]="UPPER_ALPHA",e[e.ALPHA=5]="ALPHA",e[e.UPPER_ROMAN=6]="UPPER_ROMAN",e[e.ROMAN=7]="ROMAN",e))(Jt||{}),Rt=(e=>(e[e.BULLET_ALIGNMENT_UNSPECIFIED=0]="BULLET_ALIGNMENT_UNSPECIFIED",e[e.START=1]="START",e[e.CENTER=2]="CENTER",e[e.END=3]="END",e))(Rt||{}),oo=(e=>(e[e.HYPERLINK=0]="HYPERLINK",e[e.FIELD=1]="FIELD",e[e.SDT=2]="SDT",e[e.BOOKMARK=3]="BOOKMARK",e[e.COMMENT=4]="COMMENT",e[e.CUSTOM=5]="CUSTOM",e[e.MENTION=6]="MENTION",e[e.UNI_FORMULA=7]="UNI_FORMULA",e))(oo||{}),io=(e=>(e[e.COMMENT=0]="COMMENT",e))(io||{}),ao=(e=>(e[e.DRAWING=0]="DRAWING",e[e.CUSTOM=1]="CUSTOM",e))(ao||{}),lo=(e=>(e[e.TRADITIONAL=0]="TRADITIONAL",e[e.MODERN=1]="MODERN",e))(lo||{}),uo=(e=>(e[e.DEFAULT=0]="DEFAULT",e[e.LINES=1]="LINES",e[e.LINES_AND_CHARS=2]="LINES_AND_CHARS",e[e.SNAP_TO_CHARS=3]="SNAP_TO_CHARS",e))(uo||{}),co=(e=>(e[e.SECTION_TYPE_UNSPECIFIED=0]="SECTION_TYPE_UNSPECIFIED",e[e.CONTINUOUS=1]="CONTINUOUS",e[e.NEXT_PAGE=2]="NEXT_PAGE",e[e.EVEN_PAGE=3]="EVEN_PAGE",e[e.ODD_PAGE=4]="ODD_PAGE",e))(co||{}),ho=(e=>(e[e.COLUMN_SEPARATOR_STYLE_UNSPECIFIED=0]="COLUMN_SEPARATOR_STYLE_UNSPECIFIED",e[e.NONE=1]="NONE",e[e.BETWEEN_EACH_COLUMN=2]="BETWEEN_EACH_COLUMN",e))(ho||{}),fo=(e=>(e[e.NORMAL=0]="NORMAL",e[e.TBRL=1]="TBRL",e[e.LRTBV=2]="LRTBV",e))(fo||{}),_o=(e=>(e[e.TEXT_RUN=0]="TEXT_RUN",e[e.AUTO_TEXT=1]="AUTO_TEXT",e[e.PAGE_BREAK=2]="PAGE_BREAK",e[e.COLUMN_BREAK=3]="COLUMN_BREAK",e[e.FOOT_NOTE_REFERENCE=4]="FOOT_NOTE_REFERENCE",e[e.HORIZONTAL_RULE=5]="HORIZONTAL_RULE",e[e.EQUATION=6]="EQUATION",e[e.DRAWING=7]="DRAWING",e[e.PERSON=8]="PERSON",e[e.RICH_LINK=9]="RICH_LINK",e))(_o||{}),go=(e=>(e[e.BOTH_SIDES=0]="BOTH_SIDES",e[e.LEFT=1]="LEFT",e[e.RIGHT=2]="RIGHT",e[e.LARGEST=3]="LARGEST",e))(go||{}),po=(e=>(e[e.INLINE=0]="INLINE",e[e.WRAP_NONE=1]="WRAP_NONE",e[e.WRAP_POLYGON=2]="WRAP_POLYGON",e[e.WRAP_SQUARE=3]="WRAP_SQUARE",e[e.WRAP_THROUGH=4]="WRAP_THROUGH",e[e.WRAP_TIGHT=5]="WRAP_TIGHT",e[e.WRAP_TOP_AND_BOTTOM=6]="WRAP_TOP_AND_BOTTOM",e))(po||{}),mo=(e=>(e[e.NAMED_STYLE_TYPE_UNSPECIFIED=0]="NAMED_STYLE_TYPE_UNSPECIFIED",e[e.NORMAL_TEXT=1]="NORMAL_TEXT",e[e.TITLE=2]="TITLE",e[e.SUBTITLE=3]="SUBTITLE",e[e.HEADING_1=4]="HEADING_1",e[e.HEADING_2=5]="HEADING_2",e[e.HEADING_3=6]="HEADING_3",e[e.HEADING_4=7]="HEADING_4",e[e.HEADING_5=8]="HEADING_5",e[e.HEADING_6=9]="HEADING_6",e))(mo||{}),Eo=(e=>(e[e.AUTO=0]="AUTO",e[e.AT_LEAST=1]="AT_LEAST",e[e.EXACT=2]="EXACT",e))(Eo||{}),Ro=(e=>(e[e.DASH_STYLE_UNSPECIFIED=0]="DASH_STYLE_UNSPECIFIED",e[e.SOLID=1]="SOLID",e[e.DOT=2]="DOT",e[e.DASH=3]="DASH",e))(Ro||{}),Co=(e=>(e[e.TAB_STOP_ALIGNMENT_UNSPECIFIED=0]="TAB_STOP_ALIGNMENT_UNSPECIFIED",e[e.START=1]="START",e[e.CENTER=2]="CENTER",e[e.END=3]="END",e))(Co||{}),Io=(e=>(e.EVENLY_DISTRIBUTED="0",e.FIXED_WIDTH="1",e))(Io||{}),vo=(e=>(e[e.CONTENT_ALIGNMENT_UNSPECIFIED=0]="CONTENT_ALIGNMENT_UNSPECIFIED",e[e.CONTENT_ALIGNMENT_UNSUPPORTED=1]="CONTENT_ALIGNMENT_UNSUPPORTED",e[e.TOP=2]="TOP",e[e.MIDDLE=3]="MIDDLE",e[e.BOTTOM=4]="BOTTOM",e))(vo||{}),Oo=(e=>(e.NORMAL="normal",e.BOLD="bold",e.ITALIC="italic",e))(Oo||{}),So=(e=>(e[e.PAGE=0]="PAGE",e[e.COLUMN=1]="COLUMN",e[e.CHARACTER=2]="CHARACTER",e[e.MARGIN=3]="MARGIN",e[e.INSIDE_MARGIN=4]="INSIDE_MARGIN",e[e.OUTSIDE_MARGIN=5]="OUTSIDE_MARGIN",e[e.LEFT_MARGIN=6]="LEFT_MARGIN",e[e.RIGHT_MARGIN=7]="RIGHT_MARGIN",e))(So||{}),No=(e=>(e[e.PAGE=0]="PAGE",e[e.PARAGRAPH=1]="PARAGRAPH",e[e.LINE=2]="LINE",e[e.MARGIN=3]="MARGIN",e[e.TOP_MARGIN=4]="TOP_MARGIN",e[e.BOTTOM_MARGIN=5]="BOTTOM_MARGIN",e[e.INSIDE_MARGIN=6]="INSIDE_MARGIN",e[e.OUTSIDE_MARGIN=7]="OUTSIDE_MARGIN",e))(No||{}),wo=(e=>(e[e.POINT=0]="POINT",e[e.LINE=1]="LINE",e[e.CHARACTER=2]="CHARACTER",e[e.PIXEL=3]="PIXEL",e))(wo||{}),bo=(e=>(e[e.CENTER=0]="CENTER",e[e.INSIDE=1]="INSIDE",e[e.LEFT=2]="LEFT",e[e.OUTSIDE=3]="OUTSIDE",e[e.RIGHT=4]="RIGHT",e[e.BOTH=5]="BOTH",e[e.DISTRIBUTE=6]="DISTRIBUTE",e))(bo||{}),Ao=(e=>(e[e.BOTTOM=0]="BOTTOM",e[e.CENTER=1]="CENTER",e[e.INSIDE=2]="INSIDE",e[e.OUTSIDE=3]="OUTSIDE",e[e.TOP=4]="TOP",e))(Ao||{}),To=(e=>(e[e.compressPunctuation=0]="compressPunctuation",e[e.compressPunctuationAndJapaneseKana=1]="compressPunctuationAndJapaneseKana",e[e.doNotCompress=2]="doNotCompress",e))(To||{}),yo=(e=>(e[e.PORTRAIT=0]="PORTRAIT",e[e.LANDSCAPE=1]="LANDSCAPE",e))(yo||{}),Do=(e=>(e[e.forward=0]="forward",e[e.backward=1]="backward",e[e.front=2]="front",e[e.back=3]="back",e))(Do||{}),Mo=(e=>(e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e[e.DRAWING_IMAGE=0]="DRAWING_IMAGE",e[e.DRAWING_SHAPE=1]="DRAWING_SHAPE",e[e.DRAWING_CHART=2]="DRAWING_CHART",e[e.DRAWING_TABLE=3]="DRAWING_TABLE",e[e.DRAWING_SMART_ART=4]="DRAWING_SMART_ART",e[e.DRAWING_VIDEO=5]="DRAWING_VIDEO",e[e.DRAWING_GROUP=6]="DRAWING_GROUP",e[e.DRAWING_UNIT=7]="DRAWING_UNIT",e[e.DRAWING_DOM=8]="DRAWING_DOM",e))(Mo||{}),oe=(e=>(e[e.NORMAL=0]="NORMAL",e[e.ROW=1]="ROW",e[e.COLUMN=2]="COLUMN",e[e.ALL=3]="ALL",e))(oe||{}),Se=(e=>(e[e.NONE=0]="NONE",e[e.ROW=1]="ROW",e[e.COLUMN=2]="COLUMN",e[e.ALL=3]="ALL",e))(Se||{});function dl(e){return[e.startRow,e.startColumn,e.endRow,e.endColumn]}function fl(e,n,t){let r=!1,s=!1,o=e,i=n,a=e,l=n;if(t==null)return{actualRow:e,actualColumn:n,isMergedMainCell:s,isMerged:r,endRow:o,endColumn:i,startRow:a,startColumn:l};for(let h=0;h<t.length;h++){const{startRow:c,endRow:u,startColumn:d,endColumn:f}=t[h];if(e===c&&n===d){o=u,i=f,a=c,l=d,s=!0;break}if(e>=c&&e<=u&&n>=d&&n<=f){o=u,i=f,a=c,l=d,r=!0;break}}return{actualRow:e,actualColumn:n,isMergedMainCell:s,isMerged:r,endRow:o,endColumn:i,startRow:a,startColumn:l}}var yr=(e=>(e[e.SLIDE=0]="SLIDE",e[e.MASTER=1]="MASTER",e[e.LAYOUT=2]="LAYOUT",e[e.HANDOUT_MASTER=3]="HANDOUT_MASTER",e[e.NOTES_MASTER=4]="NOTES_MASTER",e))(yr||{}),Uo=(e=>(e[e.SHAPE=0]="SHAPE",e[e.IMAGE=1]="IMAGE",e[e.TEXT=2]="TEXT",e[e.SPREADSHEET=3]="SPREADSHEET",e[e.DOCUMENT=4]="DOCUMENT",e[e.SLIDE=5]="SLIDE",e))(Uo||{}),Lo=(e=>(e[e.RELATIVE_SLIDE_LINK_UNSPECIFIED=0]="RELATIVE_SLIDE_LINK_UNSPECIFIED",e[e.NEXT_SLIDE=1]="NEXT_SLIDE",e[e.PREVIOUS_SLIDE=2]="PREVIOUS_SLIDE",e[e.FIRST_SLIDE=3]="FIRST_SLIDE",e[e.LAST_SLIDE=4]="LAST_SLIDE",e))(Lo||{});const _l="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let gl=e=>crypto.getRandomValues(new Uint8Array(e)),pl=(e,n,t)=>{let r=(2<<Math.log(e.length-1)/Math.LN2)-1,s=-~(1.6*r*n/e.length);return(o=n)=>{let i="";for(;;){let a=t(s),l=s;for(;l--;)if(i+=e[a[l]&r]||"",i.length===o)return i}}},ml=(e,n=21)=>pl(e,n,gl),El=(e=21)=>{let n="",t=crypto.getRandomValues(new Uint8Array(e));for(;e--;)n+=_l[t[e]&63];return n};const Rl=new Set(["ac","ad","ae","aero","af","ag","ai","al","am","ao","aq","ar","arpa","as","asia","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","biz","bj","bm","bn","bo","br","bs","bt","bv","bw","by","bz","ca","cat","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","com","coop","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","edu","ee","eg","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gov","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","info","int","io","iq","ir","is","it","je","jm","jo","jobs","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mg","mh","mil","mk","ml","mm","mn","mo","mobi","mp","mq","mr","ms","mt","mu","museum","mv","mw","mx","my","mz","na","name","nc","ne","net","nf","ng","ni","nl","no","np","nr","nu","nz","om","onion","org","pa","pe","pf","pg","ph","pk","pl","pm","pn","post","pr","pro","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","su","sv","sx","sy","sz","tc","td","tel","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","uk","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","yt","za","zm","zw"]),Cl=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");function Il(e){if(!Number.isNaN(+e))return!1;if(e.startsWith("http://localhost:3002")||e.startsWith("localhost:3002"))return!0;if(Cl.test(e)){if(xo(e))return!0;try{const r=new URL(Po(e)).hostname.split(".").pop();if(r&&Rl.has(r))return!0}catch{return!1}}return!1}function xo(e){return/^[a-zA-Z]+:\/\//.test(e)}function vl(e){return/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(e)}function Po(e){return xo(e)?e:vl(e)?`mailto://${e}`:`https://${e}`}const Ol=/^-ms-/,Sl=/-([a-z])/g,Et=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];class x{static stringAt(n){let t="",r=n;for(;r>=Et.length;)r/=Et.length,r-=1,t+=Et[r%Et.length];const s=n%Et.length;return t+=Et[s],t}static indexAt(n){let t=0;for(let r=0;r<n.length-1;r+=1){const s=n.charCodeAt(r)-65,o=n.length-1-r;t+=Et.length**o+Et.length*s}return t+=n.charCodeAt(n.length-1)-65,t}static deleteBlank(n){return x.isString(n)?n.replace(/\s/g,""):n}static getSystemType(){const n=navigator.userAgent,t=navigator.platform==="Win32"||navigator.platform==="Windows",r=navigator.platform==="Mac68K"||navigator.platform==="MacPPC"||navigator.platform==="Macintosh"||navigator.platform==="MacIntel";if(r)return"Mac";if(navigator.platform==="X11"&&!t&&!r)return"Unix";if(String(navigator.platform).indexOf("Linux")>-1)return"Linux";if(t){if(n.indexOf("Windows NT 5.0")>-1||n.indexOf("Windows 2000")>-1)return"Windows 2000";if(n.indexOf("Windows NT 5.1")>-1||n.indexOf("Windows XP")>-1)return"Windows XP";if(n.indexOf("Windows NT 5.2")>-1||n.indexOf("Windows 2003")>-1)return"Windows 2003";if(n.indexOf("Windows NT 6.0")>-1||n.indexOf("Windows Vista")>-1)return"Windows Vista";if(n.indexOf("Windows NT 6.1")>-1||n.indexOf("Windows 7")>-1)return"Windows 7";if(n.indexOf("Windows NT 10")>-1||n.indexOf("Windows 10")>-1)return"Windows 10";if(n.indexOf("Windows NT 11")>-1||n.indexOf("Windows 11")>-1)return"Windows 11"}return"Unknown system"}static getBrowserType(){const n=navigator.userAgent,t=n.indexOf("Opera")>-1,r=n.indexOf("compatible")>-1&&n.indexOf("MSIE")>-1&&!t,s=n.indexOf("Trident")>-1&&n.indexOf("rv:11.0")>-1,o=n.indexOf("Edge")>-1,i=n.indexOf("Firefox")>-1,a=n.indexOf("Safari")>-1&&n.indexOf("Chrome")===-1,l=n.indexOf("Chrome")>-1&&n.indexOf("Safari")>-1;if(r){new RegExp("MSIE (\\d+\\.\\d+);").test(n);const c=Number.parseFloat(RegExp.$1);return c===7?"IE7":c===8?"IE8":c===9?"IE9":c===10?"IE10":"0"}return i?"FF":t?"Opera":a?"Safari":l?"Chrome":o?"Edge":s?"IE11":"Unknown browser"}static generateRandomId(n=21,t){return ko(n,t)}static getClassName(n){return n.constructor.name}static deepMerge(n,...t){t.forEach(i=>i&&o(i));function r(i,a){i.forEach((l,h)=>{var c,u;if(x.isArray(l)){const d=(c=a[h])!=null?c:[];a[h]=d,r(l,d);return}if(x.isObject(l)){const d=(u=a[h])!=null?u:{};a[h]=d,s(l,d);return}a[h]=l})}function s(i,a){Object.keys(i).forEach(l=>{var c,u;const h=i[l];if(x.isObject(h)){const d=(c=a[l])!=null?c:{};a[l]=d,s(h,d);return}if(x.isArray(h)){const d=(u=a[l])!=null?u:[];a[l]=d,r(h,d);return}a[l]=h})}function o(i){Object.keys(i).forEach(a=>{var h,c;const l=i[a];if(x.isArray(l)){const u=(h=n[a])!=null?h:[];n[a]=u,r(l,u);return}if(x.isObject(l)){const u=(c=n[a])!=null?c:{};n[a]=u,s(l,u);return}n[a]=l})}return n}static numberFixed(n,t){return Number(Number(n).toFixed(t))}static diffValue(n,t){function r(i,a){const l=x.getValueType(i),h=x.getValueType(a);return l!==h?!1:x.isArray(i)?s(i,a):x.isObject(i)?o(i,a):x.isDate(i)?i.getTime()===a.getTime():x.isRegExp(i)?i.toString()===a.toString():i===a}function s(i,a){if(n.length!==t.length)return!1;for(let l=0,h=i.length;l<h;l++){const c=i[l],u=a[l];if(!r(c,u))return!1}return!0}function o(i,a){const l=Object.keys(i),h=Object.keys(a);if(l.length!==h.length)return!1;for(const c of l){if(!h.includes(c))return!1;const u=i[c],d=a[c];if(!r(u,d))return!1}return!0}return r(n,t)}static deepClone(n){if(!this.isDefine(n))return n;if(this.isRegExp(n))return new RegExp(n);if(this.isDate(n))return new Date(n);if(this.isArray(n)){const t=[];return n.forEach((r,s)=>{t[s]=x.deepClone(r)}),t}if(this.isObject(n)){const t={};return Object.keys(n).forEach(r=>{const s=n[r];t[r]=x.deepClone(s)}),Object.setPrototypeOf(t,Object.getPrototypeOf(n)),t}return n}static getLanguage(){const n="en-US";return globalThis.navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||n}static getValueType(n){return Object.prototype.toString.apply(n)}static isDefine(n){return n!=null}static isBlank(n){return this.isDefine(n)?this.isString(n)?n.trim()==="":!1:!0}static isAssignableFrom(n,t){return n instanceof t}static isBoolean(n){return this.getValueType(n)==="[object Boolean]"}static isPlainObject(n){return this.isDefine(n)?Object.getPrototypeOf(n)===Object.getPrototypeOf({}):!1}static isFunction(n){return this.getValueType(n)==="[object Function]"}static isDate(n){return this.getValueType(n)==="[object Date]"}static isRegExp(n){return this.getValueType(n)==="[object RegExp]"}static isArray(n){return this.getValueType(n)==="[object Array]"}static isString(n){return this.getValueType(n)==="[object String]"}static isNumber(n){return this.getValueType(n)==="[object Number]"}static isStringNumber(n){return!isNaN(Number.parseFloat(n))&&isFinite(n)}static isObject(n){return this.getValueType(n)==="[object Object]"}static isEmptyObject(n){for(const t in n)return!1;return!0}static isMobile(){let n=0,t=0;return document.body.clientWidth&&(n=document.body.clientWidth),document.body.clientHeight&&(t=document.body.clientHeight),this.isAndroid()||this.isIPhone()||this.isTablet()||n<350&&t<500}static isTablet(){return/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase())}static isWeChat(){const n=navigator.userAgent.toLowerCase();return String(n.match(/MicroMessenger/i))==="micromessenger"}static isAndroid(){const n=navigator.userAgent;return n.indexOf("Android")>-1||n.indexOf("Linux")>-1}static isIPhone(){return/iPhone/i.test(navigator.userAgent)}static isLegalUrl(n){return Il(n)}static normalizeUrl(n){return Po(n)}static itCount(n){return t=>{for(let r=0;r<n;r++)t&&t()}}static hasLength(n,t){return x.isDefine(n)?x.isDefine(t)?n.length===t:n.length>0:!1}static capitalize(n){return n.charAt(0).toUpperCase()+n.slice(1)}static fCamelCase(n,t){return t.toUpperCase()}static camelCase(n){return n.replace(Ol,"ms-").replace(Sl,this.fCamelCase)}static removeNull(n){return this.isObject(n)&&Object.keys(n).forEach(t=>{const r=n[t];r==null?delete n[t]:x.removeNull(r)}),n}static fillTwoDimensionalArray(n,t,r){return new Array(n).fill(r).map(s=>new Array(t).fill(r))}static numToWord(n){let t="";for(;n>0;){let r=n%26;r=r===0?r=26:r,t=String.fromCharCode(96+r)+t,n=(n-r)/26}return t.toLocaleUpperCase()}static ABCatNum(n){if(n==null||n.length===0)return Number.NaN;const t=n.toLowerCase().split(""),r=t.length;let s=0,o=0;for(let i=0;i<r;i++)o=t[i].charCodeAt(0)-96,s+=o*26**(r-i-1);return s===0?Number.NaN:s-1}static chatAtABC(n){let o="";for(;n>=0;)o=String.fromCharCode(n%26+97)+o,n=Math.floor(n/26)-1;return o.toUpperCase()}static randSort(n){for(let t=0,r=n.length;t<r;t++){const s=Number.parseInt((Math.random()*r).toString()),o=n[s];n[s]=n[t],n[t]=o}return n}static commonExtend(n,t){const r={};for(const s in n)r[s]=n[s];for(const s in t)t[s]!=null&&(r[s]=t[s]);return r}static commonExtend1(n,t){for(const r in n)t[r]==null&&(t[r]=n[r]);return t}static arrayToObject(n){const t={};return n.forEach((r,s)=>{t[s]={},r.forEach((o,i)=>{t[s][i]=o})}),t}static hasIntersectionBetweenTwoRanges(n,t,r,s){return t>=r&&s>=n}static isStartValidPosition(n){return/^[A-Za-z_]/.test(n)}static isValidParameter(n){const t=/[~!@#$%^&*()+=\-{}\[\]\|:;"'<>,?\/ ]+/.test(n),r=n.length<=255;return!t&&r}static set(n,t,r){const s=t.split("."),o=s.pop();s.forEach(i=>{n[i]||(n[i]={}),n=n[i]}),o&&(n[o]=r)}static clamp(n,t,r){return Math.max(t,Math.min(r,n))}}function ko(e=21,n){return n?ml(n,e)():El(e)}function Nl(e){const{actualRow:n,actualColumn:t,isMerged:r,isMergedMainCell:s,mergeInfo:o}=e;let{startY:i,endY:a,startX:l,endX:h}=e,c=n,u=t,d=n,f=t;if(r&&o){const{startRow:p,startColumn:m,endRow:S,endColumn:y,startY:ee,endY:ge,startX:ce,endX:E}=o;c=p,u=m,d=S,f=y,i=ee,a=ge,l=ce,h=E}return s&&(i=o.startY,a=o.endY,l=o.startX,h=o.endX,d=o.endRow,f=o.endColumn),{startRow:c,startColumn:u,endRow:d,endColumn:f,startY:i,endY:a,startX:l,endX:h}}function wl(e){if(!e)return;const{actualRow:n,actualColumn:t,isMerged:r,isMergedMainCell:s,startRow:o,startColumn:i,endRow:a,endColumn:l}=e;let h=n,c=t,u=n,d=t;return(r||s)&&(h=o,c=i,u=a,d=l),{startRow:h,startColumn:c,endRow:u,endColumn:d}}function Fo(e){var t;return!e||(((t=e==null?void 0:e.v)==null?void 0:t.toString())||"").length===0&&!e.p}function bl(e){return Fo(e)&&(e==null?void 0:e.coverable)!==!1}function ut(e){if(e){if(e.rgb)return e.rgb;if(e.th)return new $n().setThemeColor(e.th).asThemeColor().asRgbColor().getCssString()}return null}function Al(e){return x.isString(e)&&e.substring(0,1)==="="&&e.length>1}function Tl(e){return x.isString(e)&&e.length>0}function yl(e,n=!1){var o;let t="";const r=new Map([["ff",()=>{e.ff&&(t+=`font-family: ${e.ff}; `)}],["fs",()=>{if(e.fs){let i=e.fs;e.va&&(i/=2),t+=`font-size: ${i}pt; `}}],["it",()=>{e.it&&(t+="font-style: italic; ")}],["bl",()=>{e.bl&&(t+="font-weight: bold; ")}],["ul",()=>{var i;(i=e.ul)!=null&&i.s&&(t.indexOf("text-decoration-line")>-1?t=t.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(a,l)=>`${l} underline`):t+="text-decoration: underline; ",e.ul.cl&&t.indexOf("text-decoration-color")===-1&&(t+=`text-decoration-color: ${ut(e.ul.cl)}; `),e.ul.t&&t.indexOf("text-decoration-style")===-1&&(t+=`text-decoration-style: ${e.ul.t} `))}],["st",()=>{var i;(i=e.st)!=null&&i.s&&(t.indexOf("text-decoration-line")>-1?t=t.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(a,l)=>`${l} line-through`):t+="text-decoration-line: line-through; ",e.st.cl&&t.indexOf("text-decoration-color")===-1&&(t+=`text-decoration-color: ${ut(e.st.cl)}; `),e.st.t&&t.indexOf("text-decoration-style")===-1&&(t+=`text-decoration-style: ${e.st.t} `))}],["ol",()=>{var i;(i=e.ol)!=null&&i.s&&(t.indexOf("text-decoration-line")>-1?t=t.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(a,l)=>`${l} overline`):t+="text-decoration-line: overline; ",e.ol.cl&&t.indexOf("text-decoration-color")===-1&&(t+=`text-decoration-color: ${ut(e.ol.cl)}; `),e.ol.t&&t.indexOf("text-decoration-style")===-1&&(t+=`text-decoration-style: ${e.ol.t} `))}],["bg",()=>{e.bg&&(t+=`background: ${ut(e.bg)}; `)}],["bd",()=>{var i,a,l,h,c,u,d,f,p,m,S,y;(i=e.bd)!=null&&i.b&&(t+=`border-bottom: ${mn((a=e.bd)==null?void 0:a.b.s)} ${(l=ut(e.bd.b.cl))!=null?l:""}; `),(h=e.bd)!=null&&h.t&&(t+=`border-top: ${mn((c=e.bd)==null?void 0:c.t.s)} ${(u=ut(e.bd.t.cl))!=null?u:""}; `),(d=e.bd)!=null&&d.r&&(t+=`border-right: ${mn((f=e.bd)==null?void 0:f.r.s)} ${(p=ut(e.bd.r.cl))!=null?p:""}; `),(m=e.bd)!=null&&m.l&&(t+=`border-left: ${mn((S=e.bd)==null?void 0:S.l.s)} ${(y=ut(e.bd.l.cl))!=null?y:""}; `)}],["cl",()=>{e.cl&&(t+=`color: ${ut(e.cl)}; `)}],["va",()=>{e.va===Gt.SUBSCRIPT?t+="vertical-align: sub; ":e.va===Gt.SUPERSCRIPT&&(t+="vertical-align: super; ")}],["td",()=>{e.td===on.LEFT_TO_RIGHT?t+="direction: ltr; ":e.td===on.RIGHT_TO_LEFT&&(t+="direction: rtl; ")}],["tr",()=>{var i,a,l;e.tr&&(t+=`--data-rotate: (${(i=e.tr)==null?void 0:i.a}deg${(a=e.tr)!=null&&a.v?` ,${(l=e.tr)==null?void 0:l.v}`:""});`)}],["ht",()=>{e.ht===Dt.LEFT?t+="text-align: left; ":e.ht===Dt.RIGHT?t+="text-align: right; ":e.ht===Dt.CENTER?t+="text-align: center; ":e.ht===Dt.JUSTIFIED&&(t+="text-align: justify; ")}],["vt",()=>{e.vt===Wt.BOTTOM?t+="vertical-align: bottom; ":e.vt===Wt.TOP?t+="vertical-align: top; ":e.vt===Wt.MIDDLE&&(t+="vertical-align: middle; ")}],["tb",()=>{e.tb===Bt.CLIP?t+="white-space: nowrap; overflow-x: hidden; ":e.tb===Bt.WRAP&&(t+="white-space: normal;")}],["pd",()=>{var c,u,d,f,p,m,S,y;const i=`${(c=e.pd)==null?void 0:c.b}pt`,a=`${(u=e.pd)==null?void 0:u.t}pt`,l=`${(d=e.pd)==null?void 0:d.l}pt`,h=`${(f=e.pd)==null?void 0:f.r}pt`;(p=e.pd)!=null&&p.b&&(t+=`padding-bottom: ${i}; `),(m=e.pd)!=null&&m.t&&(t+=`padding-top: ${a}; `),(S=e.pd)!=null&&S.l&&(t+=`padding-left: ${l}; `),(y=e.pd)!=null&&y.r&&(t+=`padding-right: ${h}; `)}]]),s=["bd","tr","tb"];for(const i in e)n&&s.includes(i)||(o=r.get(i))==null||o();return t}function mn(e){let n="";return e===he.NONE?n="none":e===he.THIN?n="0.5pt solid":e===he.HAIR?n="0.5pt double":e===he.DOTTED?n="0.5pt dotted":e===he.DASHED||e===he.DASH_DOT?n="0.5pt dashed":e===he.DASH_DOT_DOT?n="0.5pt dotted":e===he.DOUBLE?n="0.5pt double":e===he.MEDIUM?n="1pt solid":e===he.MEDIUM_DASHED||e===he.MEDIUM_DASH_DOT?n="1pt dashed":e===he.MEDIUM_DASH_DOT_DOT?n="1pt dotted":e===he.SLANT_DASH_DOT?n="0.5pt dashed":e===he.THICK&&(n="1.5pt solid"),n}function Dl(e){let n=0;if(e=e.trim(),e==="none")n=he.NONE;else if(e==="0.5pt solid")n=he.THIN;else if(e==="0.5pt double")n=he.HAIR;else if(e==="0.5pt dotted")n=he.DOTTED;else if(e==="0.5pt dashed")n=he.DASHED;else if(e==="1pt solid")n=he.MEDIUM;else if(e==="1pt dashed")n=he.MEDIUM_DASHED;else if(e==="1pt dotted")n=he.MEDIUM_DASH_DOT_DOT;else if(e==="1.5pt solid")n=he.THICK;else if(!e.includes("none"))n=he.THIN;else return he.NONE;return n}function Ml(e,n){let t=e.body;if(n){const{headers:r,footers:s}=e;r!=null&&r[n]?t=r[n].body:s!=null&&s[n]&&(t=s[n].body)}return t}function Ul(e){const{startRow:n,endRow:t,startColumn:r,endColumn:s,rangeType:o}=e;return!(n<0||r<0||t<0||s<0||!(Number.isNaN(n)&&Number.isNaN(t))&&o===oe.COLUMN||!(Number.isNaN(r)&&Number.isNaN(s))&&o===oe.ROW||o!==oe.ROW&&o!==oe.COLUMN&&(Number.isNaN(r)||Number.isNaN(n)||Number.isNaN(s)||Number.isNaN(t)))}function Ll(e,n){return{startRow:e,endRow:e,startColumn:n,endColumn:n}}function Dr(e,n){return Object.prototype.toString.call(e)===Object.prototype.toString.call(n)?Object.prototype.toString.call(e)==="[object Object]"||Object.prototype.toString.call(e)==="[object Array]"?Object.keys(e).length!==Object.keys(n).length?!1:Object.keys(e).every(t=>Dr(e[t],n[t])):e===n:!1}function Ho(e,n){const t=e.ts||{},r=n.ts||{};return e.sId!==n.sId?!1:Dr(t,r)}function xl(e,n){return n.some(t=>e.indexOf(t)>-1)}function Wn(e,n,t,r){if(e>n&&([e,n]=[n,e]),t>r&&([t,r]=[r,t]),n<t||r<e)return[e,n];t<e&&(t=e),r>n&&(r=n);const s=r-t+1;let o=[];return e===t?o=[r+1-s,n-s]:n===r?o=[e,t-1]:o=[e,n-s],o}function Pl(e){if(e==null)return!1;const n=e.bullet;return(n==null?void 0:n.listId)!=null}function kl(e){if(e==null)return!1;const n=e.paragraphStyle;return jo(n)}function jo(e){var n;return!(e==null||(e.indentStart==null||e.indentStart.v===0)&&e.hanging==null||((n=e.hanging)==null?void 0:n.v)===0)}function $o(e,n,t){return e.slice(0,n)+t+e.slice(n)}function Wo(e,n,t){return n>t?e:e.slice(0,n)+e.slice(t)}function Fl(e){return e===null||e.toString().replace(/\s/g,"")===""||typeof e=="boolean"?!1:!isNaN(e)}function Hl(e){let n=0;for(let t=0;t<e.length;t++)n=e.charCodeAt(t)+(n<<6)+(n<<16)-n;return n>>>0}function as(e){var n=typeof Symbol=="function"&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function ls(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var r=t.call(e),s,o=[],i;try{for(;(n===void 0||n-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o}function us(e,n,t){if(t||arguments.length===2)for(var r=0,s=n.length,o;r<s;r++)(o||!(r in n))&&(o||(o=Array.prototype.slice.call(n,0,r)),o[r]=n[r]);return e.concat(o||Array.prototype.slice.call(n))}function en(e){return typeof e=="function"}function jl(e){var n=function(r){Error.call(r),r.stack=new Error().stack},t=e(n);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var nr=jl(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
2
- `+t.map(function(r,s){return s+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function cs(e,n){if(e){var t=e.indexOf(n);0<=t&&e.splice(t,1)}}var Bo=function(){function e(n){this.initialTeardown=n,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var n,t,r,s,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=as(i),l=a.next();!l.done;l=a.next()){var h=l.value;h.remove(this)}}catch(m){n={error:m}}finally{try{l&&!l.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}else i.remove(this);var c=this.initialTeardown;if(en(c))try{c()}catch(m){o=m instanceof nr?m.errors:[m]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=as(u),f=d.next();!f.done;f=d.next()){var p=f.value;try{hs(p)}catch(m){o=o!=null?o:[],m instanceof nr?o=us(us([],ls(o)),ls(m.errors)):o.push(m)}}}catch(m){r={error:m}}finally{try{f&&!f.done&&(s=d.return)&&s.call(d)}finally{if(r)throw r.error}}}if(o)throw new nr(o)}},e.prototype.add=function(n){var t;if(n&&n!==this)if(this.closed)hs(n);else{if(n instanceof e){if(n.closed||n._hasParent(this))return;n._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(n)}},e.prototype._hasParent=function(n){var t=this._parentage;return t===n||Array.isArray(t)&&t.includes(n)},e.prototype._addParent=function(n){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(n),t):t?[t,n]:n},e.prototype._removeParent=function(n){var t=this._parentage;t===n?this._parentage=null:Array.isArray(t)&&cs(t,n)},e.prototype.remove=function(n){var t=this._finalizers;t&&cs(t,n),n instanceof e&&n._removeParent(this)},e.EMPTY=function(){var n=new e;return n.closed=!0,n}(),e}();Bo.EMPTY;function $l(e){return e instanceof Bo||e&&"closed"in e&&en(e.remove)&&en(e.add)&&en(e.unsubscribe)}function hs(e){en(e)?e():e.unsubscribe()}function Ne(e){let n=!1;return e?$l(e)?{dispose:()=>e.unsubscribe()}:typeof e=="function"?{dispose:()=>{n||(n=!0,e())}}:e:Ne(()=>{})}function Wl(e){return Ne(()=>{e.unsubscribe()})}class Mr{constructor(){_(this,"_disposables",new Set)}add(n){const t=Ne(n);return this._disposables.add(t),{dispose:()=>{t.dispose(),this._disposables.delete(t)}}}dispose(){this._disposables.forEach(n=>{n.dispose()}),this._disposables.clear()}}class Ae{constructor(){_(this,"_disposed",!1);_(this,"_collection",new Mr)}disposeWithMe(n){return this._collection.add(n)}ensureNotDisposed(){if(this._disposed)throw new Error("[Disposable]: object is disposed!")}dispose(){this._disposed||(this._disposed=!0,this._collection.dispose())}}class Bl extends Ae{constructor(){super(...arguments);_(this,"dispose$",new Y.Subject)}dispose(){super.dispose(),this.dispose$.next(),this.dispose$.complete()}}class Gl extends Ae{constructor(t){super();_(this,"_ref",0);this._rootDisposable=t}inc(){if(this._disposed)throw new Error("[RCDisposable]: should not ref to a disposed.");this._ref+=1}dec(){this._ref-=1,this._ref===0&&(this._rootDisposable.dispose(),this.dispose())}}class qt{static hasLength(n,t){return n.length===t}static getValueType(n){return Object.prototype.toString.apply(n)}static isObject(n){return this.getValueType(n)==="[object Object]"}static isIterable(n){return n[Symbol.iterator]!=null}static isNumber(n){return this.getValueType(n)==="[object Number]"}}function Bn(e,n){const t=e.indexOf(n);return t>-1?(e.splice(t,1),!0):!1}function Vl(e){const n=new Set,t=[];for(const r of e)n.has(r)||(n.add(r),t.push(r));return t}function Kl(e,n){for(let t=e.length-1;t>-1;t--){const r=e[t];if(n(r,t))return r}return null}function zl(e,n){if(e.length===0)return e;const t=n%e.length;return e.slice(t).concat(e.slice(0,t))}function Yl(e,n){const t=new Map;return e.forEach(r=>{const s=n(r);let o=t.get(s);t.has(s)||(o=[],t.set(s,o)),o.push(r)}),t}function Xl(e){return Array.isArray(e)?e:[e]}const ue=Symbol("newer"),Me=Symbol("older");class Go{constructor(n){_(this,"entry");this.entry=n}[Symbol.iterator](){return this}next(){const n=this.entry;return n?(this.entry=n[ue],{done:!1,value:n.key}):{done:!0,value:void 0}}}class Vo{constructor(n){_(this,"entry");this.entry=n}[Symbol.iterator](){return this}next(){const n=this.entry;return n?(this.entry=n[ue],{done:!1,value:n.value}):{done:!0,value:void 0}}}class Ko{constructor(n){_(this,"entry");this.entry=n}[Symbol.iterator](){return this}next(){const n=this.entry;return n?(this.entry=n[ue],{done:!1,value:[n.key,n.value]}):{done:!0,value:void 0}}}var Us,Ls;Ls=ue,Us=Me;class ur{constructor(n,t){_(this,"key");_(this,"value");_(this,Ls);_(this,Us);this.key=n,this.value=t,this[ue]=void 0,this[Me]=void 0}toJSON(){return{key:this.key,value:this.value}}}class zo{constructor(...n){_(this,"_keymap");_(this,"size",0);_(this,"limit");_(this,"oldest");_(this,"newest");_(this,"_onShiftListeners",[]);if(qt.hasLength(n,1)){if(qt.isNumber(n[0])){const t=n[0];this._initialize(t,void 0);return}if(qt.isIterable(n[0])){const t=n[0];this._initialize(0,t);return}return}if(qt.hasLength(n,2)){const t=n[0],r=n[1];this._initialize(t,r)}}onShift(n){if(this._onShiftListeners.indexOf(n)===-1)return this._onShiftListeners.push(n),Ne(()=>Bn(this._onShiftListeners,n));throw new Error("[LRUMap]: the listener has been registered!")}_initialize(n,t){this.oldest=void 0,this.newest=void 0,this.size=0,this.limit=n,this._keymap=new Map,t&&(this.assign(t),n<1&&(this.limit=this.size))}_markEntryAsUsed(n){n!==this.newest&&(n[ue]&&(n===this.oldest&&(this.oldest=n[ue]),n[ue][Me]=n[Me]),n[Me]&&(n[Me][ue]=n[ue]),n[ue]=void 0,n[Me]=this.newest,this.newest&&(this.newest[ue]=n),this.newest=n)}assign(n){let t,r=this.limit||Number.MAX_VALUE;this._keymap.clear();const s=n[Symbol.iterator]();for(let o=s.next();!o.done;o=s.next()){const i=new ur(o.value[0],o.value[1]);if(this._keymap.set(i.key,i),t?(t[ue]=i,i[Me]=t):this.oldest=i,t=i,r--===0)throw new Error("overflow")}this.newest=t,this.size=this._keymap.size}set(n,t){let r=this._keymap.get(n);return r?(r.value=t,this._markEntryAsUsed(r),this):(this._keymap.set(n,r=new ur(n,t)),this.newest?(this.newest[ue]=r,r[Me]=this.newest):this.oldest=r,this.newest=r,++this.size,this.size>this.limit&&this.shift(),this)}shift(){const n=this.oldest;if(n)return this.oldest&&this.oldest[ue]?(this.oldest=this.oldest[ue],this.oldest[Me]=void 0):(this.oldest=void 0,this.newest=void 0),n[ue]=n[Me]=void 0,this._keymap.delete(n.key),--this.size,this._onShiftListeners.forEach(t=>t(n)),[n.key,n.value]}get(n){const t=this._keymap.get(n);if(t)return this._markEntryAsUsed(t),t.value}has(n){return this._keymap.has(n)}find(n){const t=this._keymap.get(n);return t?t.value:void 0}delete(n){const t=this._keymap.get(n);if(t)return this._keymap.delete(t.key),t[ue]&&t[Me]?(t[Me][ue]=t[ue],t[ue][Me]=t[Me]):t[ue]?(t[ue][Me]=void 0,this.oldest=t[ue]):t[Me]?(t[Me][ue]=void 0,this.newest=t[Me]):this.oldest=this.newest=void 0,this.size--,t.value}clear(){this.oldest=void 0,this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new Go(this.oldest)}values(){return new Vo(this.oldest)}entries(){return this[Symbol.iterator]()}[Symbol.iterator](){return new Ko(this.oldest)}forEach(n,t){typeof t!="object"&&(t=this);let r=this.oldest;for(;r;)n.call(t,r.value,r.key,this),r=r[ue]}toJSON(){const n=new Array(this.size);let t=0,r=this.oldest;for(;r;)n[t++]={key:r.key,value:r.value},r=r[ue];return n}toString(){let n="",t=this.oldest;for(;t;)n+=`${String(t.key)}:${t.value}`,t=t[ue],t&&(n+=" < ");return n}}function It(e){let n=0;const t=Object.keys(e);for(const r of t){const s=Number(r);n=Math.max(n,s)}return n+1}function cr(e,n,t){const r=It(t),s=t;for(let o=r-1;o>=e;o--)s[o+1]=s[o];s[e]=n}function hr(e,n,t){const r=Object.keys(t).reduce((s,o)=>Math.max(s,Number.parseInt(o)),0)+1;for(let s=e;s<r;s++)s<e+n?delete t[s]:t[s]!==void 0&&(t[s-n]=t[s],delete t[s])}function Ql(e,n){const t=e,r=Object.keys(t),s=r.length,o=n,i=Object.keys(o),a=i.length,l={};let h=0;for(let c=0;c<s;c++,h++){const u=r[c];l[h]=t[u]}for(let c=0;c<a;c++,h++){const u=i[c];l[h]=o[u]}return l}function ql(e,n,t){const r=t;if(It(t)>0){const o={};let i=0;for(let a=e;a<=n;a++)r[a]&&(o[i]=r[a],i++);return o}return{}}function dr(e,n,t,r){const s=e>t;if(!s&&e+n>t)throw new Error("Invalid move operation");s?Zl(e,n,t,r):Jl(e,n,t,r)}function Zl(e,n,t,r){const s=r,o=[];for(let i=e;i<e+n;i++)o.push(s[i]);for(let i=e-1;i>=t;i--){const a=s[i];s[i+n]=a,a===void 0&&delete s[i+n]}o.forEach((i,a)=>{s[t+a]=i,i===void 0&&delete s[t+a]})}function Jl(e,n,t,r){const s=r,o=[];for(let i=e;i<e+n;i++)o.push(s[i]);for(let i=e+n;i<t;i++){const a=s[i];s[i-n]=a,a===void 0&&delete s[i-n]}o.forEach((i,a)=>{s[t+a-n]=i,i===void 0&&delete s[t+a-n]})}class ot{constructor(n={}){_(this,"_matrix");this._setOriginValue(n)}static MakeObjectMatrixSize(n){return new ot({[n-1]:{}})}getMatrix(){return this._matrix}forEach(n){const t=this._matrix,r=Object.keys(t);for(const s of r){const o=Number(s),i=t[o];if(n(o,i)===!1)return this}return this}forRow(n){const t=this._matrix,r=Object.keys(t);for(const s of r){const o=Number(s),i=t[o];if(n(o,Object.keys(i).map(l=>Number(l)))===!1)return this}return this}forValue(n){const t=this._matrix,r=Object.keys(t);for(const s of r){const o=Number(s),i=t[o];if(!i)continue;const a=Object.keys(i);for(const l of a){const h=Number(l),c=i[Number(l)];if(n(o,h,c)===!1)return this}}return this}swapRow(n,t){const r=this._matrix[n],s=this._matrix[t];this._matrix[n]=s,this._matrix[t]=r}getRow(n){return this._matrix[n]}getRowOrCreate(n){let t=this.getRow(n);return t==null&&(t={},this._matrix[n]=t),t}reset(){this._setOriginValue({})}hasValue(){const n=this._matrix,t=Object.keys(n);if(t.length===0)return!1;for(const r of t){const s=Number(r),o=n[s];if(Object.keys(o).length>0)return!0}return!1}getValue(n,t){var r,s;return(s=(r=this._matrix)==null?void 0:r[n])==null?void 0:s[t]}setValue(n,t,r){const s=this.getRowOrCreate(n);s[t]=r}deleteValue(n,t){var r,s;(s=(r=this._matrix)==null?void 0:r[n])==null||delete s[t]}realDeleteValue(n,t){var r,s,o;if((s=(r=this._matrix)==null?void 0:r[n])==null||delete s[t],this.getRow(n)){const i=this.getRow(n);if(i==null)return;Object.keys(i).length===0&&((o=this._matrix)==null||delete o[n])}}setRow(n,t){this._matrix[n]=t}moveRows(n,t,r){dr(n,t,r,this._matrix)}moveColumns(n,t,r){this.forEach((s,o)=>{dr(n,t,r,o)})}insertRows(n,t){for(let r=n;r<n+t;r++)cr(r,{},this._matrix)}insertColumns(n,t){for(let r=n;r<n+t;r++)this.forEach((s,o)=>{o&&cr(r,void 0,o)})}removeRows(n,t){hr(n,t,this._matrix)}removeColumns(n,t){this.forEach((r,s)=>{s&&hr(n,t,s)})}getFragment(n,t,r,s){const o=new ot;let i=0;for(let a=n;a<=t;a++){const l={};let h=0;for(let c=r;c<=s;c++){const u=this.getValue(a,c);l[h]=u,h++}o.setRow(i,l),i++}return o}getSlice(n,t,r,s){const o=new ot;for(let i=n;i<=t;i++)for(let a=r;a<=s;a++){const l=this.getValue(i,a);l&&o.setValue(i,a,x.deepClone(l))}return o}getSizeOf(){return Object.keys(this._matrix).length}getLength(){return It(this._matrix)}getRange(){const r=this.getLength()-1;let s=0;const o=this.getLength();for(let i=0;i<o;i++){const a=this.getRow(i);if(a){const l=It(a)-1;s=l>s?l:s}}return{startRow:0,startColumn:0,endRow:r,endColumn:s}}toNativeArray(){const n=new Array;return this.forValue((t,r,s)=>{n.push(s)}),n}toArray(){const n=[];return this.forRow((t,r)=>{n[t]==null&&(n[t]=[]),r.forEach(s=>{n[t][s]=this.getValue(t,s)})}),n}toFullArray(){const n=this.getRange(),{endColumn:t,endRow:r}=n,s=[];for(let o=0;o<=r;o++){const i=Array(t+1).fill(void 0);s.push(i)}return this.forValue((o,i,a)=>{s[o][i]=a}),s}toJSON(){return this._matrix}clone(){const n=JSON.stringify(this._matrix);return JSON.parse(n)}getData(){const n=JSON.stringify(this._matrix);return JSON.parse(n)}getArrayData(){let n=0,t=0,r=!1,s=!1;const o=new ot;return this.forEach((i,a)=>{r||(r=!0,n=i),Object.keys(a).forEach(l=>{const h=Number(l);s?h<t&&(t=h):(s=!0,t=h);const c=this.getValue(i,h);o.setValue(i-n,h-t,c)})}),o.getData()}getDataRange(){let n=0,t=0,r=0,s=-1,o=!1,i=!1;return this.forEach((a,l)=>{if(o||(o=!0,n=a),l==null)return;const h=It(l)-1;h>r&&(r=h),Object.keys(l).forEach(c=>{const u=Number(c);i?u<t&&(t=u):(i=!0,t=u)}),a>s&&(s=a)}),{startRow:n,startColumn:t,endRow:s,endColumn:r}}getDiscreteRanges(){const n=[];return this.forEach((t,r)=>{Object.keys(r).forEach(s=>{const o=Number(s);let i=!1;for(const a of n)if(t>=a.startRow&&t<=a.endRow+1&&o>=a.startColumn&&o<=a.endColumn+1){a.endRow=Math.max(t,a.endRow),a.endColumn=Math.max(o,a.endColumn),i=!0;break}i||n.push({startRow:t,endRow:t,startColumn:o,endColumn:o})})}),n}merge(n){this.forValue((t,r)=>{const s=n.getValue(t,r);s!=null&&this.setValue(t,r,s)})}_setOriginValue(n={}){this._matrix=n}}const _t=class _t{static clone(n){return n.rangeType!==void 0?{startRow:n.startRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.endColumn,rangeType:n.rangeType}:{startRow:n.startRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.endColumn}}static equals(n,t){return n==null||t==null?!1:n.endRow===t.endRow&&n.endColumn===t.endColumn&&n.startRow===t.startRow&&n.startColumn===t.startColumn&&(n.rangeType===t.rangeType||n.rangeType===void 0&&t.rangeType===oe.NORMAL||t.rangeType===void 0&&n.rangeType===oe.NORMAL)}static intersects(n,t){if(n.rangeType===oe.ROW&&t.rangeType===oe.COLUMN||n.rangeType===oe.COLUMN&&t.rangeType===oe.ROW)return!0;if(n.rangeType===oe.ROW&&t.rangeType===oe.ROW)return n.startRow<=t.endRow&&n.endRow>=t.startRow;if(n.rangeType===oe.COLUMN&&t.rangeType===oe.COLUMN)return n.startColumn<=t.endColumn&&n.endColumn>=t.startColumn;const r=Math.floor(Number.MAX_SAFE_INTEGER/10),s=Number.isNaN(n.startRow)?0:n.startRow,o=Number.isNaN(n.endRow)?r:n.endRow,i=Number.isNaN(n.startColumn)?0:n.startColumn,a=Number.isNaN(n.endColumn)?r:n.endColumn,l=Number.isNaN(t.startRow)?0:t.startRow,h=Number.isNaN(t.endRow)?r:t.endRow,c=Number.isNaN(t.startColumn)?0:t.startColumn,u=Number.isNaN(t.endColumn)?r:t.endColumn,d=Math.abs(i+a-c-u),f=Math.abs(i-a)+Math.abs(c-u),p=Math.abs(s+o-l-h),m=Math.abs(s-o)+Math.abs(l-h);return d<=f&&p<=m}static getIntersects(n,t){const r=n.startRow,s=n.endRow,o=n.startColumn,i=n.endColumn,a=t.startRow,l=t.endRow,h=t.startColumn,c=t.endColumn;let u,d,f,p;if(a<=s)a>=r?d=a:d=r;else return null;if(l>=r)l>=s?p=s:p=l;else return null;if(h<=i)h>o?u=h:u=o;else return null;if(c>=o)c>=i?f=i:f=c;else return null;return{startRow:d,endRow:p,startColumn:u,endColumn:f,rangeType:oe.NORMAL}}static contains(n,t){return n.startRow<=t.startRow&&n.endRow>=t.endRow&&n.startColumn<=t.startColumn&&n.endColumn>=t.endColumn}static realContain(n,t){return _t.contains(n,t)&&(n.startRow<t.startRow||n.endRow>t.endRow||n.startColumn<t.startColumn||n.endColumn>t.endColumn)}static union(...n){return n.reduce((t,r)=>({startRow:Math.min(t.startRow,r.startRow),startColumn:Math.min(t.startColumn,r.startColumn),endRow:Math.max(t.endRow,r.endRow),endColumn:Math.max(t.endColumn,r.endColumn),rangeType:oe.NORMAL}),n[0])}static realUnion(...n){const t=n.some(o=>o.rangeType===oe.COLUMN),r=n.some(o=>o.rangeType===oe.ROW),s=_t.union(...n);return{startColumn:r?Number.NaN:s.startColumn,endColumn:r?Number.NaN:s.endColumn,startRow:t?Number.NaN:s.startRow,endRow:t?Number.NaN:s.endRow,rangeType:r?oe.ROW:t?oe.COLUMN:oe.NORMAL}}static subtract(n,t){if(t.startRow>n.endRow||t.endRow<n.startRow||t.startColumn>n.endColumn||t.endColumn<n.startColumn)return[n];const r=[];t.startRow>=n.startRow&&r.push({startRow:n.startRow,startColumn:n.startColumn,endRow:t.startRow-1,endColumn:n.endColumn}),t.endRow<=n.endRow&&r.push({startRow:t.endRow+1,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.endColumn});const s=Math.max(n.startRow,t.startRow),o=Math.min(n.endRow,t.endRow);return t.startColumn>=n.startColumn&&r.push({startRow:s,startColumn:n.startColumn,endRow:o,endColumn:t.startColumn-1}),t.endColumn<=n.endColumn&&r.push({startRow:s,startColumn:t.endColumn+1,endRow:o,endColumn:n.endColumn}),r.filter(a=>a.startRow<=a.endRow&&a.startColumn<=a.endColumn)}static hasIntersectionBetweenTwoRect(n,t){return!(n.left>t.right||n.right<t.left||n.top>t.bottom||n.bottom<t.top)}static getIntersectionBetweenTwoRect(n,t){const r=Math.max(n.left,t.left),s=Math.min(n.right,t.right),o=Math.max(n.top,t.top),i=Math.min(n.bottom,t.bottom);return s<=r||i<=o?null:{left:r,right:s,top:o,bottom:i,width:s-r,height:i-o}}};_(_t,"getRelativeRange",(n,t)=>({startRow:n.startRow-t.startRow,endRow:n.endRow-n.startRow,startColumn:n.startColumn-t.startColumn,endColumn:n.endColumn-n.startColumn})),_(_t,"getPositionRange",(n,t,r)=>({...r||{},startRow:r&&[Se.ROW,Se.ALL].includes(r.startAbsoluteRefType||0)?r.startRow:n.startRow+t.startRow,endRow:r&&[Se.ROW,Se.ALL].includes(r.endAbsoluteRefType||0)?r.endRow:n.endRow+n.startRow+t.startRow,startColumn:r&&[Se.COLUMN,Se.ALL].includes(r.startAbsoluteRefType||0)?r.startColumn:n.startColumn+t.startColumn,endColumn:r&&[Se.COLUMN,Se.ALL].includes(r.endAbsoluteRefType||0)?r.endColumn:n.endColumn+n.startColumn+t.startColumn})),_(_t,"moveHorizontal",(n,t=0,r=0)=>({...n,startColumn:n.startColumn+t,endColumn:n.endColumn+t+r})),_(_t,"moveVertical",(n,t=0,r=0)=>({...n,startRow:n.startRow+t,endRow:n.endRow+t+r})),_(_t,"moveOffset",(n,t,r)=>({...n,startRow:n.startRow+r,endRow:n.endRow+r,startColumn:n.startColumn+t,endColumn:n.endColumn+t}));let vt=_t;class eu{constructor(n,t){_(this,"_values",[]);_(this,"_keys",[]);_(this,"_keyMaps",new Map);this._values=n,this._keys=t,n.forEach(r=>{this._initKeyMap(r)})}_initKeyMap(n){this._keys.forEach(t=>{const r=n[t],s=this._keyMaps.get(t)||new Map;s.set(r,n),this._keyMaps.set(t,s)})}getValue(n,t){const r=t||this._keys;for(let s=0;s<r.length;s++){const o=this._keyMaps.get(r[s]);if(o!=null&&o.has(n))return o.get(n)}return null}hasValue(n){for(let t=0;t<this._keys.length;t++){const r=this._keyMaps.get(this._keys[t]);if(r!=null&&r.has(n))return!0}return!1}addValue(n){this._values.push(n),this._initKeyMap(n)}setValue(n,t,r){const s=this.getValue(n);s&&Object.keys(s).includes(t)&&(s[t]=r)}deleteValue(n){const t=this.getValue(n);if(t){this._keys.forEach(s=>{const o=this._keyMaps.get(s),i=t[s];o==null||o.delete(i)});const r=this._values.findIndex(s=>s===t);this._values.splice(r,1)}}getValues(){return this._values}getKeyMap(n){var t;return[...((t=this._keyMaps.get(n))==null?void 0:t.keys())||[]]}clear(){this._values=[],this._keys=[],this._keyMaps.clear()}}function fr(e,n,t,r){return{forEach(s){for(let o=e;o<=n;o++)for(let i=t;i<=r;i++)s(o,i)}}}function tu(e){if(e==null||e.length===0)return Number.NaN;const n=e.toLowerCase().split(""),t=n.length,r=i=>i.charCodeAt(0)-96;let s=0,o=0;for(let i=0;i<t;i++)o=r(n[i]),s+=o*26**(t-i-1);return s===0?Number.NaN:s-1}const Un=65,Yo=90,nu=97;function ru(e){const n=Yo-Un+1;let t="";for(;e>=0;)t=String.fromCharCode(e%n+Un)+t,e=Math.floor(e/n)-1;return t}function Xo(e,n){let t="";for(;n>0;)t+=e,n--;return t}function su(e,n=!1){const t=Yo-Un+1;let r=nu;n&&(r=Un);const s=String.fromCharCode(e%t+r),o=Math.floor(e/t)+1;return Xo(s,o)}function ou(e,n){return e.zIndex>n.zIndex?1:e.zIndex===n.zIndex?0:-1}function iu(e,n){return e.zIndex>n.zIndex?-1:e.zIndex===n.zIndex?0:1}function kt(e="index",n=1){return(t,r)=>t[e]>r[e]?n:t[e]===r[e]?0:-n}function au(e,n){let t;function r(...s){const o=this,i=function(){t=null,e.apply(o,s)};clearTimeout(t),t=setTimeout(i,n)}return Object.defineProperty(r,"cancel",{value:()=>{clearTimeout(t)},enumerable:!1,writable:!1}),r}function In(e,n,t){const{dataStream:r,textRuns:s=[]}=e;let o=n;const i=[];for(const a of s){const{st:l,ed:h}=a;x.hasIntersectionBetweenTwoRanges(n,t,l,h)&&(l>o?(i.push(r.slice(o,l)),i.push(_r(r,{...a,ed:Math.min(h,t)}))):i.push(_r(r,{...a,st:o,ed:Math.min(h,t)}))),o=Math.max(n,Math.min(h,t))}return o!==t&&i.push(r.slice(o,t)),i.join("")}function lu(e,n=!0){var t;if(n&&((t=e.paragraphs)!=null&&t.length)){const{dataStream:r,paragraphs:s=[]}=e;let o="",i=-1;for(const a of s){const{startIndex:l,paragraphStyle:h={}}=a,{spaceAbove:c,spaceBelow:u,lineSpacing:d}=h,f=[];c!=null&&(typeof c=="number"?f.push(`margin-top: ${c}px`):f.push(`margin-top: ${c.v}px`)),u!=null&&(typeof u=="number"?f.push(`margin-bottom: ${u}px`):f.push(`margin-bottom: ${u.v}px`)),d!=null&&f.push(`line-height: ${d}`),l>i+1?o+=`<p class="UniverNormal" ${f.length?`style="${f.join("; ")};"`:""}>${In(e,i+1,l)}</p>`:o+=`<p class="UniverNormal" ${f.length?`style="${f.join("; ")};"`:""}></p>`,i=l}return i!==r.length&&(o+=In(e,i,r.length)),o}else return In(e,0,e.dataStream.length)}function _r(e,n){const{st:t,ed:r,ts:s={}}=n,{ff:o,fs:i,it:a,bl:l,ul:h,st:c,ol:u,bg:d,cl:f,va:p}=s;let m=e.slice(t,r);const S=[];return a===K.TRUE&&(m=`<i>${m}</i>`),p===Gt.SUPERSCRIPT?m=`<sup>${m}</sup>`:p===Gt.SUBSCRIPT&&(m=`<sub>${m}</sub>`),(h==null?void 0:h.s)===K.TRUE&&(m=`<u>${m}</u>`),(c==null?void 0:c.s)===K.TRUE&&(m=`<s>${m}</s>`),l===K.TRUE&&(m=`<strong>${m}</strong>`),o&&S.push(`font-family: ${o}`),f&&S.push(`color: ${f.rgb}`),i&&S.push(`font-size: ${i}pt`),u&&S.push("text-decoration: overline"),d&&S.push(`background: ${d.rgb}`),S.length?`<span style="${S.join("; ")};">${m}</span>`:m}const uu={sheetId:"",range:{startRow:-1,endRow:-1,startColumn:-1,endColumn:-1}},cu={startRow:-1,startColumn:-1,endRow:-1,endColumn:-1},hu={startRow:0,startColumn:0,endRow:0,endColumn:0},du={row:0,column:0},vn={ff:"Arial",fs:11,it:K.FALSE,bl:K.FALSE,ul:{s:K.FALSE},st:{s:K.FALSE},ol:{s:K.FALSE},tr:{a:0,v:K.FALSE},td:on.UNSPECIFIED,cl:{rgb:"#000"},bg:{rgb:"#fff"},ht:Dt.UNSPECIFIED,vt:Wt.UNSPECIFIED,tb:Bt.UNSPECIFIED,pd:{t:0,r:0,b:0,l:0}},Qo={id:"default_slide",title:"defaultSlide",pageSize:{width:300,height:300}};var qo=(e=>(e.ARRAY_CONVERTOR="ARRAY_CONVERTOR",e.MATRIX_CONVERTOR="MATRIX_CONVERTOR",e))(qo||{});function En(e,n){const{textRuns:t=[]}=n;let r=0;for(const o of t){const{ts:i={},st:a,ed:l}=o;if(i[e]==null)return K.FALSE;switch(e){case"bl":case"it":{if(i[e]===K.FALSE)return K.FALSE;break}case"ul":case"st":{if(i[e].s===K.FALSE)return K.FALSE;break}default:throw new Error(`unknown style key: ${e} in IStyleBase`)}r+=l-a}return n.dataStream.indexOf(`\r
4
- `)===r?K.TRUE:K.FALSE}const rn=class rn{constructor(n,t,r){_(this,"_range");_(this,"_worksheet");this._deps=r,this._range=t,this._worksheet=n}static foreach(n,t){const{startRow:r,startColumn:s,endRow:o,endColumn:i}=n;for(let a=r;a<=o;a++)for(let l=s;l<=i;l++)t(a,l)}getRangeData(){return this._range}getValue(){return this.getValues()[0][0]}getValues(){const{startRow:n,endRow:t,startColumn:r,endColumn:s}=this._range,o=[];for(let i=n;i<=t;i++){const a=[];for(let l=r;l<=s;l++)a.push(this.getMatrix().getValue(i,l)||null);o.push(a)}return o}getMatrix(){const{startRow:n,endRow:t,startColumn:r,endColumn:s}=this._range,o=this._worksheet.getCellMatrix(),i=new ot;for(let a=n;a<=t;a++)for(let l=r;l<=s;l++)i.setValue(a,l,o.getValue(a,l)||null);return i}getMatrixObject(){const{startRow:n,endRow:t,startColumn:r,endColumn:s}=this._range,o=this._worksheet.getCellMatrix(),i=new ot;for(let a=n;a<=t;a++)for(let l=r;l<=s;l++)i.setValue(a-n,l-r,o.getValue(a,l)||{});return i}getA1Notation(){const{startRow:n,endRow:t,startColumn:r,endColumn:s}=this._range;let o,i;return r<s?(o=x.numToWord(r+1)+(n+1),i=x.numToWord(s+1)+(t+1)):(o=x.numToWord(s+1)+(t+1),i=x.numToWord(r+1)+(n+1)),o===i?`${o}`:`${o}:${i}`}getBackground(){return this.getBackgrounds()[0][0]}getBackgrounds(){const n=this._deps.getStyles();return this.getValues().map(t=>t.map(r=>{var o;const s=n.getStyleByCell(r);return((o=s==null?void 0:s.bg)==null?void 0:o.rgb)||vn.bg.rgb}))}getCell(n,t){const{startRow:r,endRow:s,startColumn:o,endColumn:i}=this._range,a={startRow:r+n,endRow:r+n,startColumn:o+t,endColumn:o+t};return new rn(this._worksheet,a,this._deps)}getColumn(){return this._range.startColumn}getObjectValue(n={}){return this.getObjectValues(n)[0][0]}getObjectValues(n={}){var a;const{startRow:t,endRow:r,startColumn:s,endColumn:o}=this._range,i=this._worksheet.getCellMatrix().getFragment(t,r,s,o).getData();if(n.isIncludeStyle){const l=this._deps.getStyles();for(let h=0;h<=r-t;h++)for(let c=0;c<=o-s;c++){if(i==null||((a=i==null?void 0:i[h])==null?void 0:a[c])==null)continue;const u=i[h][c].s;u&&(i[h][c].s=l.get(u))}}return i}getFontColor(){return this.getFontColors()[0][0]}getFontColors(){const n=this._deps.getStyles();return this.getValues().map(t=>t.map(r=>{var o;const s=n.getStyleByCell(r);return((o=s==null?void 0:s.cl)==null?void 0:o.rgb)||vn.cl.rgb}))}getFontFamilies(){return this._getStyles("ff")}getFontFamily(){return this.getFontFamilies()[0][0]}getUnderlines(){return this._getStyles("ul")}getUnderline(){var t,r;const{p:n}=(t=this.getValue())!=null?t:{};return n&&Array.isArray((r=n.body)==null?void 0:r.textRuns)&&n.body.textRuns.length>0?En("ul",n.body)===K.TRUE?{s:K.TRUE}:{s:K.FALSE}:this.getUnderlines()[0][0]}getOverlines(){return this._getStyles("ol")}getOverline(){return this.getOverlines()[0][0]}getStrikeThrough(){var t,r;const{p:n}=(t=this.getValue())!=null?t:{};return n&&Array.isArray((r=n.body)==null?void 0:r.textRuns)&&n.body.textRuns.length>0?En("st",n.body)===K.TRUE?{s:K.TRUE}:{s:K.FALSE}:this.getStrikeThroughs()[0][0]}getStrikeThroughs(){return this._getStyles("st")}getFontSize(){var t,r;const n=((t=this.getValue())==null?void 0:t.p)||{};return n&&Array.isArray((r=n.body)==null?void 0:r.textRuns)&&n.body.textRuns.length>0?n.body.textRuns.some(s=>{var o;return((o=s==null?void 0:s.ts)==null?void 0:o.fs)!=null})?Math.max(...n.body.textRuns.map(s=>{var o;return((o=s==null?void 0:s.ts)==null?void 0:o.fs)||0})):this.getFontSizes()[0][0]:this.getFontSizes()[0][0]}getFontSizes(){return this._getStyles("fs")}getBorder(){return this.getBorders()[0][0]}getBorders(){return this._getStyles("bd")}getFontStyle(){var t,r;const{p:n}=(t=this.getValue())!=null?t:{};return n&&Array.isArray((r=n.body)==null?void 0:r.textRuns)&&n.body.textRuns.length>0?En("it",n.body)===K.TRUE?Tn.ITALIC:Tn.NORMAL:this._getFontStyles()[0][0]}_getFontStyles(){return this._getStyles("it")}getFontWeight(){var t,r;const{p:n}=(t=this.getValue())!=null?t:{};return n&&Array.isArray((r=n.body)==null?void 0:r.textRuns)&&n.body.textRuns.length>0?En("bl",n.body)===K.TRUE?yn.BOLD:yn.NORMAL:this._getFontWeights()[0][0]}_getFontWeights(){return this._getStyles("bl")}getGridId(){return this._worksheet.getSheetId()}getHeight(){const{_range:n,_worksheet:t}=this,{startRow:r,endRow:s}=n;let o=0;for(let i=0;i<=s-r;i++){const a=t.getRowHeight(i);o+=a}return o}getHorizontalAlignment(){return this.getHorizontalAlignments()[0][0]}getHorizontalAlignments(){return this._getStyles("ht")}getLastColumn(){return this._range.endColumn}getLastRow(){return this._range.endRow}getNumColumns(){const{startColumn:n,endColumn:t}=this._range;return t-n+1}getNumRows(){const{startRow:n,endRow:t}=this._range;return t-n+1}getRichTextValue(){return this.getRichTextValues()[0][0]}getRichTextValues(){return this.getValues().map(n=>n.map(t=>(t==null?void 0:t.p)||""))}getRowIndex(){return this._range.startRow}getSheet(){return this._worksheet}getTextDirection(){return this.getTextDirections()[0][0]}getTextDirections(){return this._getStyles("td")}getTextRotation(){return this.getTextRotations()[0][0]}getTextRotations(){return this._getStyles("tr")}getTextStyle(){return this.getTextStyles()[0][0]}getTextStyles(){const n=this._deps.getStyles();return this.getValues().map(t=>t.map(r=>n.getStyleByCell(r)))}getVerticalAlignment(){return this.getVerticalAlignments()[0][0]}getVerticalAlignments(){return this._getStyles("vt")}getWidth(){const{_range:n,_worksheet:t}=this,{startColumn:r,endColumn:s}=n;let o=0;for(let i=0;i<=s-r;i++)o+=t.getColumnWidth(i);return o}getWrap(){return this.getWrapStrategy()===Bt.WRAP?K.TRUE:K.FALSE}getWrapStrategies(){return this._getStyles("tb")}getWrapStrategy(){return this.getWrapStrategies()[0][0]}forEach(n){rn.foreach(this._range,n)}_getStyles(n){const t=this._deps.getStyles();return this.getValues().map(r=>r.map(s=>{const o=t&&t.getStyleByCell(s);return o&&o[n]||vn[n]}))}};_(rn,"transformRange",(n,t)=>n.rangeType===oe.ALL?{startColumn:0,startRow:0,endColumn:t.getMaxColumns()-1,endRow:t.getMaxRows()-1}:n.rangeType===oe.COLUMN?{startRow:0,endRow:t.getMaxRows()-1,startColumn:n.startColumn,endColumn:n.endColumn}:n.rangeType===oe.ROW?{startColumn:0,endColumn:t.getMaxColumns()-1,startRow:n.startRow,endRow:n.endRow}:n);let Vt=rn;function fu(e,n){if(e.length===0||e[0].length===0)return null;const t=new Array(e[0].length).fill(0);let r=0,s=null;for(let o=0;o<e.length;o++){for(let a=0;a<e[0].length;a++)t[a]=n(e[o][a])?t[a]+1:0;const i=_u(t);i.area>r&&(r=i.area,s={startColumn:i.start,startRow:o-i.height+1,endColumn:i.end,endRow:o})}return s}function _u(e){const n=[];let t=0,r={area:0,height:0,start:0,end:0},s=0;for(;s<e.length;)if(n.length===0||e[s]>=e[n[n.length-1]])n.push(s++);else{const o=e[n.pop()],i=n.length===0?s:s-n[n.length-1]-1;o*i>t&&(t=o*i,r={area:t,height:o,start:n.length===0?0:n[n.length-1]+1,end:s-1})}for(;n.length>0;){const o=e[n.pop()],i=n.length===0?s:s-n[n.length-1]-1;o*i>t&&(t=o*i,r={area:t,height:o,start:n.length===0?0:n[n.length-1]+1,end:s-1})}return r}function gu(e,n){Vt.foreach(n,(t,r)=>{e[t][r]=void 0})}function pu(e,n){const t=e.toFullArray(),r=[];for(;;){const s=fu(t,n);if(!s)break;r.push(s),gu(t,s)}return r}function mu(e,n,t,r=!1){let s={...e};const o=s.startAbsoluteRefType||Se.NONE,i=s.endAbsoluteRefType||Se.NONE;return!r&&o===Se.ALL&&i===Se.ALL?s:r||o===Se.NONE&&i===Se.NONE?vt.moveOffset(s,n,t):(o===Se.NONE?s={...s,startRow:s.startRow+t,startColumn:s.startColumn+n}:o===Se.COLUMN?s={...s,startRow:s.startRow+t}:o===Se.ROW&&(s={...s,startColumn:s.startColumn+n}),i===Se.NONE?s={...s,endRow:s.endRow+t,endColumn:s.endColumn+n}:i===Se.COLUMN?s={...s,endRow:s.endRow+t}:i===Se.ROW&&(s={...s,endColumn:s.endColumn+n}),s)}var Ur=Symbol("$$IDENTIFIER_DECORATOR");function Eu(e){return e&&e[Ur]===!0}function Lr(e){return typeof e=="function"}function gr(e){return!!(e&&typeof e.useClass<"u")}function pr(e){return!!(e&&typeof e.useFactory<"u")}function mr(e){return!!(e&&typeof e.useValue<"u")}function Ru(e){return!!(e&&typeof e.useExisting<"u")}function Er(e){return!!(e&&typeof e.useAsync<"u")}var Zo=Symbol("AsyncHook");function On(e){return!!(e&&e.__symbol===Zo)}function Ge(e){return typeof e>"u"?"undefined":Lr(e)&&!e[Ur]?e.name:e.toString()}exports.Quantity=void 0;(function(e){e.MANY="many",e.OPTIONAL="optional",e.REQUIRED="required"})(exports.Quantity||(exports.Quantity={}));exports.LookUp=void 0;(function(e){e.SELF="self",e.SKIP_SELF="skipSelf"})(exports.LookUp||(exports.LookUp={}));var Cu=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Le=function(e){Cu(n,e);function n(t){return e.call(this,"[redi]: ".concat(t))||this}return n}(Error),Jo=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),ds=Symbol("$$TARGET"),Rr=Symbol("$$DEPENDENCIES"),Iu=function(e){Jo(n,e);function n(t,r){var s="Could not find dependency registered on the ".concat(t,' (indexed) parameter of the constructor of "').concat(Ge(r),'".');return e.call(this,s)||this}return n}(Le),ei=function(e){Jo(n,e);function n(t,r){var s='It seems that you register "undefined" as dependency on the '.concat(r+1,' parameter of "').concat(Ge(t),'". Please make sure that there is not cyclic dependency among your TypeScript files, or consider using "forwardRef". For more info please visit our website https://redi.wendell.fun/docs/debug#could-not-find-dependency-registered-on');return e.call(this,s)||this}return n}(Le);function ti(e){var n=e;return n[Rr]||[]}function xr(e,n){var t=ti(e),r=t.find(function(s){return s.paramIndex===n});if(!r)throw new Iu(n,e);return r}function Pr(e,n,t,r,s){r===void 0&&(r=exports.Quantity.REQUIRED);var o={paramIndex:t,identifier:n,quantity:r,lookUp:s,withNew:!1};if(typeof n>"u")throw new ei(e,t);var i=e;i[ds]===i?i[Rr].push(o):(i[Rr]=[o],i[ds]=i)}var fs=new Set;function Ve(e){if(fs.has(e))throw new Le('Identifier "'.concat(e,'" already exists.'));fs.add(e);var n=function(t,r,s){Pr(t,n,s)};return n.toString=function(){return e},n[Ur]=!0,n}var vu=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ou=function(e){vu(n,e);function n(t,r,s){var o='Expect "'.concat(r,'" dependency items for id "').concat(Ge(t),'" but get ').concat(s,".");return e.call(this,o)||this}return n}(Le);function ni(e,n,t){if(n===exports.Quantity.OPTIONAL&&t>1||n===exports.Quantity.REQUIRED&&t!==1)throw new Ou(e,n,t)}function Su(e,n){return e===exports.Quantity.MANY?n:n[0]}function Nu(e,n,t){var r=xr(e,n);r.quantity=t}function kr(e){return function n(t){return this instanceof n?this:function(r,s,o){if(t)Pr(r,t,o,e);else{if(e===exports.Quantity.REQUIRED)throw new ei(r,o);Nu(r,o,e)}}}}var ri=kr(exports.Quantity.MANY),si=kr(exports.Quantity.OPTIONAL),it=kr(exports.Quantity.REQUIRED);function wu(e){return{unwrap:e}}function bu(e){return!!e&&typeof e.unwrap=="function"}function Au(e){return bu(e)?e.unwrap():e}function Cr(e){return!!e&&typeof e.dispose=="function"}var oi=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}();function Tu(e){return e.length===1}var Gn=[];function _s(e){Gn.push(e)}function gs(){Gn.pop()}function yu(){Gn.length=0}var ps=function(e){oi(n,e);function n(t,r,s){var o='Cannot find "'.concat(Ge(r),'" registered by any injector. It is the ').concat(s,'th param of "').concat(Eu(t)?Ge(t):t.name,'".');return e.call(this,o)||this}return n}(Le),Sn=function(e){oi(n,e);function n(t){var r=this,s='Cannot find "'.concat(Ge(t),'" registered by any injector. The stack of dependencies is: "').concat(Gn.map(function(o){return Ge(o)}).join(" -> "),'".');return r=e.call(this,s)||this,yu(),r}return n}(Le),Du=function(){function e(n){var t=this;this.dependencyMap=new Map,this.normalizeDependencies(n).map(function(r){return t.add(r[0],r[1])})}return e.prototype.add=function(n,t){typeof t>"u"&&(t={useClass:n,lazy:!1});var r=this.dependencyMap.get(n);typeof r>"u"&&(r=[],this.dependencyMap.set(n,r)),r.push(t)},e.prototype.delete=function(n){this.dependencyMap.delete(n)},e.prototype.get=function(n,t){t===void 0&&(t=exports.Quantity.REQUIRED);var r=this.dependencyMap.get(n);return ni(n,t,r.length),Su(t,r)},e.prototype.has=function(n){return this.dependencyMap.has(n)},e.prototype.append=function(n){var t=this;this.normalizeDependencies(n).forEach(function(r){return t.add(r[0],r[1])})},e.prototype.dispose=function(){this.dependencyMap.clear()},e.prototype.normalizeDependencies=function(n){return n.map(function(t){var r=t[0],s;return Tu(t)?s={useClass:t[0],lazy:!1}:s=t[1],[r,s]})},e}(),Mu=function(){function e(){this.resolvedDependencies=new Map}return e.prototype.add=function(n,t){var r=this.resolvedDependencies.get(n);typeof r>"u"&&(r=[],this.resolvedDependencies.set(n,r)),r.push(t)},e.prototype.has=function(n){return this.resolvedDependencies.has(n)},e.prototype.delete=function(n){if(this.resolvedDependencies.has(n)){var t=this.resolvedDependencies.get(n);t.forEach(function(r){return Cr(r)?r.dispose():void 0}),this.resolvedDependencies.delete(n)}},e.prototype.get=function(n,t){t===void 0&&(t=exports.Quantity.REQUIRED);var r=this.resolvedDependencies.get(n);if(!r)throw new Sn(n);return ni(n,t,r.length),t===exports.Quantity.MANY?r:r[0]},e.prototype.dispose=function(){Array.from(this.resolvedDependencies.values()).forEach(function(n){n.forEach(function(t){return Cr(t)?t.dispose():void 0})}),this.resolvedDependencies.clear()},e}();function Uu(e,n,t){var r=xr(e,n);r.lookUp=t}function ii(e){return function n(){return this instanceof n?this:function(t,r,s){Uu(t,s,e)}}}var ai=ii(exports.LookUp.SKIP_SELF),li=ii(exports.LookUp.SELF);function Lu(e,n,t){var r=xr(e,n);r.withNew=t}function xu(e){return function n(){return this instanceof n?this:function(t,r,s){Lu(t,s,e)}}}var ui=xu(!0);function ci(e,n){return n===void 0&&(n=0),e?e.map(function(t,r){if(r+=n,!Array.isArray(t))return{paramIndex:r,identifier:t,quantity:exports.Quantity.REQUIRED,withNew:!1};var s=t.slice(0,t.length-1),o=t[t.length-1],i=void 0,a=exports.Quantity.REQUIRED,l=!1;return s.forEach(function(h){if(h instanceof li)i=exports.LookUp.SELF;else if(h instanceof ai)i=exports.LookUp.SKIP_SELF;else if(h instanceof si)a=exports.Quantity.OPTIONAL;else if(h instanceof ri)a=exports.Quantity.MANY;else if(h instanceof ui)l=!0;else throw new Le("unknown dep modifier ".concat(h,"."))}),{paramIndex:r,identifier:o,quantity:a,lookUp:i,withNew:l}}):[]}var Ir;(function(){if(typeof requestIdleCallback<"u"&&typeof cancelIdleCallback<"u")Ir=function(n,t){var r=requestIdleCallback(n,typeof t=="number"?{timeout:t}:void 0),s=!1;return function(){s||(s=!0,cancelIdleCallback(r))}};else{var e=Object.freeze({didTimeout:!0,timeRemaining:function(){return 15}});Ir=function(n){var t=setTimeout(function(){return n(e)}),r=!1;return function(){r||(r=!0,clearTimeout(t))}}}})();var Pu=function(){function e(n){var t=this;this.didRun=!1,this.selfExecutor=function(){try{t.value=n()}catch(r){t.error=r}finally{t.didRun=!0}},this.disposeCallback=Ir(function(){return t.selfExecutor()})}return e.prototype.hasRun=function(){return this.didRun},e.prototype.dispose=function(){this.disposeCallback()},e.prototype.getValue=function(){if(this.didRun||(this.dispose(),this.selfExecutor()),this.error)throw this.error;return this.value},e}(),zt=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ln=function(){return Ln=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++){n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Ln.apply(this,arguments)},Tt=function(e,n,t){if(t||arguments.length===2)for(var r=0,s=n.length,o;r<s;r++)(o||!(r in n))&&(o||(o=Array.prototype.slice.call(n,0,r)),o[r]=n[r]);return e.concat(o||Array.prototype.slice.call(n))},ku=300,Xt=Symbol("$$NOT_INSTANTIATED_SYMBOL"),Fu=function(e){zt(n,e);function n(t){return e.call(this,'Detecting cyclic dependency. The last identifier is "'.concat(Ge(t),'".'))||this}return n}(Le),Hu=function(e){zt(n,e);function n(){return e.call(this,"Injector cannot be accessed after it was disposed.")||this}return n}(Le),ju=function(e){zt(n,e);function n(t){return e.call(this,'Async item "'.concat(Ge(t),'" returns another async item.'))||this}return n}(Le),$u=function(e){zt(n,e);function n(t){return e.call(this,'Cannot get async item "'.concat(Ge(t),'" from sync api.'))||this}return n}(Le),ms=function(e){zt(n,e);function n(t){return e.call(this,'Cannot add dependency "'.concat(Ge(t),'" after it is already resolved.'))||this}return n}(Le),Wu=function(e){zt(n,e);function n(t){return e.call(this,'Cannot dependency dependency "'.concat(Ge(t),'" after it is already resolved.'))||this}return n}(Le),pt=function(){function e(n,t){t===void 0&&(t=null),this.parent=t,this.children=[],this.resolutionOngoing=0,this.disposed=!1,this.dependencyCollection=new Du(n||[]),this.resolvedDependencyCollection=new Mu,t&&t.children.push(this)}return e.prototype.createChild=function(n){return this._ensureInjectorNotDisposed(),new e(n,this)},e.prototype.dispose=function(){this.children.forEach(function(n){return n.dispose()}),this.children.length=0,this.dependencyCollection.dispose(),this.resolvedDependencyCollection.dispose(),this.deleteSelfFromParent(),this.disposed=!0},e.prototype.deleteSelfFromParent=function(){if(this.parent){var n=this.parent.children.indexOf(this);n>-1&&this.parent.children.splice(n,1)}},e.prototype.add=function(n){this._ensureInjectorNotDisposed();var t=n[0],r=n[1];if(this.resolvedDependencyCollection.has(t))throw new ms(t);typeof r>"u"?this.dependencyCollection.add(t):Er(r)||gr(r)||mr(r)||pr(r)?this.dependencyCollection.add(t,r):this.resolvedDependencyCollection.add(t,r)},e.prototype.replace=function(n){this._ensureInjectorNotDisposed();var t=n[0];if(this.resolvedDependencyCollection.has(t))throw new ms(t);this.dependencyCollection.delete(t),n.length===1?this.dependencyCollection.add(t):this.dependencyCollection.add(t,n[1])},e.prototype.delete=function(n){if(this._ensureInjectorNotDisposed(),this.resolvedDependencyCollection.has(n))throw new Wu(n);this.dependencyCollection.delete(n)},e.prototype.invoke=function(n){for(var t=this,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];this._ensureInjectorNotDisposed();var o={get:function(i,a,l){return t._get(i,a,l)}};return n.apply(void 0,Tt([o],r,!1))},e.prototype.has=function(n){var t;return this.dependencyCollection.has(n)||((t=this.parent)===null||t===void 0?void 0:t.has(n))||!1},e.prototype.get=function(n,t,r){this._ensureInjectorNotDisposed();var s=this._get(n,t,r);if(Array.isArray(s)&&s.some(function(o){return On(o)})||On(s))throw new $u(n);return s},e.prototype._get=function(n,t,r,s){var o=exports.Quantity.REQUIRED;if(t===exports.Quantity.REQUIRED||t===exports.Quantity.OPTIONAL||t===exports.Quantity.MANY?o=t:r=t,!s){var i=this.getValue(n,o,r);if(i!==Xt)return i}return this.createDependency(n,o,r,!s)},e.prototype.getAsync=function(n){this._ensureInjectorNotDisposed();var t=this.getValue(n,exports.Quantity.REQUIRED);if(t!==Xt)return Promise.resolve(t);var r=this.createDependency(n,exports.Quantity.REQUIRED);return On(r)?r.whenReady():Promise.resolve(r)},e.prototype.createInstance=function(n){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return this._ensureInjectorNotDisposed(),this._resolveClassImpl.apply(this,Tt([{useClass:n}],t,!1))},e.prototype._resolveDependency=function(n,t,r){r===void 0&&(r=!0);var s;_s(n);try{mr(t)?s=this._resolveValueDependency(n,t):pr(t)?s=this._resolveFactory(n,t,r):gr(t)?s=this._resolveClass(n,t,r):Ru(t)?s=this._resolveExisting(n,t):s=this._resolveAsync(n,t),gs()}catch(o){throw gs(),o}return s},e.prototype._resolveExisting=function(n,t){var r=this.get(t.useExisting);return this.resolvedDependencyCollection.add(n,r),r},e.prototype._resolveValueDependency=function(n,t){var r=t.useValue;return this.resolvedDependencyCollection.add(n,r),r},e.prototype._resolveClass=function(n,t,r){var s=this;r===void 0&&(r=!0),t.useClass;var o;if(t.lazy){var i=new Pu(function(){return s._ensureInjectorNotDisposed(),s._resolveClassImpl(t)});o=new Proxy(Object.create(null),{get:function(a,l){if(l in a)return a[l];if(l!=="whenReady"){var h=i.getValue(),c=h[l];return typeof c!="function"||(c=c.bind(h),a[l]=c),c}},set:function(a,l,h){return i.getValue()[l]=h,!0}})}else o=this._resolveClassImpl(t);return n&&r&&this.resolvedDependencyCollection.add(n,o),o},e.prototype._resolveClassImpl=function(n){for(var t,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];var o=n.useClass;this.markNewResolution(o);for(var i=ti(o).sort(function(S,y){return S.paramIndex-y.paramIndex}).map(function(S){return Ln(Ln({},S),{identifier:Au(S.identifier)})}),a=[],l=0,h=i;l<h.length;l++){var c=h[l];try{var u=this._get(c.identifier,c.quantity,c.lookUp,c.withNew);a.push(u)}catch(S){throw S instanceof Sn?new ps(o,c.identifier,c.paramIndex):S}}var d=Tt([],r,!0),f=i.length>0?i[0].paramIndex:d.length;if(d.length!==f){console.warn("[redi]: Expect ".concat(f," custom parameter(s) of ").concat(Ge(o)," but get ").concat(d.length,"."));var p=f-d.length;p>0?d=Tt(Tt([],d,!0),new Array(p).fill(void 0),!0):d=d.slice(0,f)}var m=new(o.bind.apply(o,Tt(Tt([void 0],d,!1),a,!1)));return(t=n==null?void 0:n.onInstantiation)===null||t===void 0||t.call(n,m),this.markResolutionCompleted(),m},e.prototype._resolveFactory=function(n,t,r){var s;this.markNewResolution(n);for(var o=ci(t.deps),i=[],a=0,l=o;a<l.length;a++){var h=l[a];try{var c=this._get(h.identifier,h.quantity,h.lookUp,h.withNew);i.push(c)}catch(d){throw d instanceof Sn?new ps(n,h.identifier,h.paramIndex):d}}var u=t.useFactory.apply(null,i);return r&&this.resolvedDependencyCollection.add(n,u),this.markResolutionCompleted(),(s=t==null?void 0:t.onInstantiation)===null||s===void 0||s.call(t,u),u},e.prototype._resolveAsync=function(n,t){var r=this,s={__symbol:Zo,whenReady:function(){return r._resolveAsyncImpl(n,t)}};return s},e.prototype._resolveAsyncImpl=function(n,t){var r=this;return t.useAsync().then(function(s){var o=r.getValue(n);if(o!==Xt)return o;var i;if(Array.isArray(s)){var a=s[1];if(Er(a))throw new ju(n);i=r._resolveDependency(n,a)}else Lr(s)?i=r._resolveClassImpl({useClass:s,onInstantiation:t.onInstantiation}):i=s;return r.resolvedDependencyCollection.add(n,i),i})},e.prototype.getValue=function(n,t,r){var s=this;t===void 0&&(t=exports.Quantity.REQUIRED);var o=function(){return s.dependencyCollection.has(n)&&!s.resolvedDependencyCollection.has(n)?Xt:s.resolvedDependencyCollection.get(n,t)},i=function(){return s.parent?s.parent.getValue(n,t):Xt};return r===exports.LookUp.SKIP_SELF?i():r===exports.LookUp.SELF||this.resolvedDependencyCollection.has(n)||this.dependencyCollection.has(n)?o():i()},e.prototype.createDependency=function(n,t,r,s){var o=this;t===void 0&&(t=exports.Quantity.REQUIRED),s===void 0&&(s=!0);var i=function(){var l=o.dependencyCollection.get(n,t),h=null;return Array.isArray(l)?h=l.map(function(c){return o._resolveDependency(n,c,s)}):l&&(h=o._resolveDependency(n,l,s)),h},a=function(){if(o.parent)return o.parent.createDependency(n,t,void 0,s);if(t===exports.Quantity.OPTIONAL)return null;throw _s(n),new Sn(n)};return r===exports.LookUp.SKIP_SELF?a():n===e?this:this.dependencyCollection.has(n)?i():a()},e.prototype.markNewResolution=function(n){if(this.resolutionOngoing+=1,this.resolutionOngoing>=ku)throw new Fu(n)},e.prototype.markResolutionCompleted=function(){this.resolutionOngoing-=1},e.prototype._ensureInjectorNotDisposed=function(){if(this.disposed)throw new Hu},e}();function Bu(e,n,t){t===void 0&&(t=0);var r=ci(n,t);r.forEach(function(s){Pr(e,s.identifier,s.paramIndex,s.quantity,s.lookUp)})}var Es=typeof globalThis<"u"&&globalThis||typeof window<"u"&&window||typeof global<"u"&&global,Rs="REDI_GLOBAL_LOCK",Gu=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;Es[Rs]?Gu||console.error(`[redi]: You are loading scripts of redi more than once! This may cause undesired behavior in your application.
1
+ "use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const rxjs=require("rxjs"),operators=require("rxjs/operators"),React=require("react");function _interopNamespaceDefault(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const k in e)if(k!=="default"){const d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:!0,get:__name(()=>e[k],"get")})}}return n.default=e,Object.freeze(n)}__name(_interopNamespaceDefault,"_interopNamespaceDefault");function _mergeNamespaces(n,m){for(var i=0;i<m.length;i++){const e=m[i];if(typeof e!="string"&&!Array.isArray(e)){for(const k in e)if(k!=="default"&&!(k in n)){const d=Object.getOwnPropertyDescriptor(e,k);d&&Object.defineProperty(n,k,d.get?d:{enumerable:!0,get:__name(()=>e[k],"get")})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}__name(_mergeNamespaces,"_mergeNamespaces");const React__namespace=_interopNamespaceDefault(React);function installShims(){installRequestIdleCallback()}__name(installShims,"installShims");const glob=typeof global<"u"?global:typeof self<"u"?self:window;function installRequestIdleCallback(){typeof glob.requestIdleCallback!="function"&&(glob.requestIdleCallback=__name(function(callback){const start=Date.now();return setTimeout(__name(function(){const remaining=Math.max(0,50-(Date.now()-start));callback({didTimeout:remaining===0,timeRemaining(){return remaining}})},"rICCallback"),1)},"shimRIC")),typeof glob.cancelIdleCallback!="function"&&(glob.cancelIdleCallback=__name(function(id){clearTimeout(id)},"shimCancelRIC"))}__name(installRequestIdleCallback,"installRequestIdleCallback");const DEFAULT_DOCUMENT_SUB_COMPONENT_ID="__default_document_sub_component_id20231101__",MOVE_BUFFER_VALUE=2,ROTATE_BUFFER_VALUE=1;function checkIfMove(transform,previousTransform){if(previousTransform==null||transform==null)return!0;const{left:leftPrev=0,top:topPrev=0,height:heightPrev=0,width:widthPrev=0,angle:anglePrev=0}=previousTransform,{left=0,top=0,height=0,width=0,angle=0}=transform,allWidth=width,allHeight=height,allWidthPrev=widthPrev,allHeightPrev=heightPrev;return Math.abs(left-leftPrev)>MOVE_BUFFER_VALUE||Math.abs(top-topPrev)>MOVE_BUFFER_VALUE||Math.abs(allWidth-allWidthPrev)>MOVE_BUFFER_VALUE||Math.abs(allHeight-allHeightPrev)>MOVE_BUFFER_VALUE||Math.abs(angle-anglePrev)>ROTATE_BUFFER_VALUE}__name(checkIfMove,"checkIfMove");function binarySearchArray(arr,pos){let low=0,high=arr.length-1;for(;low<=high;){const mid=Math.floor((high+low)/2);if(pos<arr[mid]&&(mid===0||pos>=arr[mid-1]))return mid;if(pos>=arr[mid])low=mid+1;else if(pos<arr[mid])high=mid-1;else return-1}return-1}__name(binarySearchArray,"binarySearchArray");function orderSearchArray(arr,pos){let i=0,cur=0,cur_pre=0,cur_index=-1,i_ed=arr.length-1;for(;i<arr.length&&i_ed>=0&&i_ed>=i;){if(cur=arr[i_ed],i_ed===0?cur_pre=0:cur_pre=arr[i_ed-1],pos>=cur_pre&&pos<=cur){cur_index=i_ed;break}if(cur=arr[i],i===0?cur_pre=0:cur_pre=arr[i-1],pos>=cur_pre&&pos<cur){cur_index=i;break}i++,i_ed--}return cur_index}__name(orderSearchArray,"orderSearchArray");function searchArray(arr,num){let index2=arr.length-1;return num<0?-1:num<arr[0]?0:num>arr[arr.length-1]?Number.POSITIVE_INFINITY:(arr.length<40||num<=arr[20]||num>=arr[index2-20]?index2=orderSearchArray(arr,num):index2=binarySearchArray(arr,num),index2)}__name(searchArray,"searchArray");function codeToBlob(code){const blob=new Blob([code],{type:"text/javascript"});return window.URL.createObjectURL(blob)}__name(codeToBlob,"codeToBlob");var AutoFillSeries=(AutoFillSeries2=>(AutoFillSeries2[AutoFillSeries2.DEFAULT_SERIES=0]="DEFAULT_SERIES",AutoFillSeries2[AutoFillSeries2.ALTERNATE_SERIES=1]="ALTERNATE_SERIES",AutoFillSeries2))(AutoFillSeries||{}),BorderStyleTypes=(BorderStyleTypes2=>(BorderStyleTypes2[BorderStyleTypes2.NONE=0]="NONE",BorderStyleTypes2[BorderStyleTypes2.THIN=1]="THIN",BorderStyleTypes2[BorderStyleTypes2.HAIR=2]="HAIR",BorderStyleTypes2[BorderStyleTypes2.DOTTED=3]="DOTTED",BorderStyleTypes2[BorderStyleTypes2.DASHED=4]="DASHED",BorderStyleTypes2[BorderStyleTypes2.DASH_DOT=5]="DASH_DOT",BorderStyleTypes2[BorderStyleTypes2.DASH_DOT_DOT=6]="DASH_DOT_DOT",BorderStyleTypes2[BorderStyleTypes2.DOUBLE=7]="DOUBLE",BorderStyleTypes2[BorderStyleTypes2.MEDIUM=8]="MEDIUM",BorderStyleTypes2[BorderStyleTypes2.MEDIUM_DASHED=9]="MEDIUM_DASHED",BorderStyleTypes2[BorderStyleTypes2.MEDIUM_DASH_DOT=10]="MEDIUM_DASH_DOT",BorderStyleTypes2[BorderStyleTypes2.MEDIUM_DASH_DOT_DOT=11]="MEDIUM_DASH_DOT_DOT",BorderStyleTypes2[BorderStyleTypes2.SLANT_DASH_DOT=12]="SLANT_DASH_DOT",BorderStyleTypes2[BorderStyleTypes2.THICK=13]="THICK",BorderStyleTypes2))(BorderStyleTypes||{}),BorderType=(BorderType2=>(BorderType2.TOP="top",BorderType2.BOTTOM="bottom",BorderType2.LEFT="left",BorderType2.RIGHT="right",BorderType2.NONE="none",BorderType2.ALL="all",BorderType2.OUTSIDE="outside",BorderType2.INSIDE="inside",BorderType2.HORIZONTAL="horizontal",BorderType2.VERTICAL="vertical",BorderType2.TLBR="tlbr",BorderType2.TLBC_TLMR="tlbc_tlmr",BorderType2.TLBR_TLBC_TLMR="tlbr_tlbc_tlmr",BorderType2.BLTR="bl_tr",BorderType2.MLTR_BCTR="mltr_bctr",BorderType2))(BorderType||{}),ColorType=(ColorType2=>(ColorType2[ColorType2.UNSUPPORTED=0]="UNSUPPORTED",ColorType2[ColorType2.RGB=1]="RGB",ColorType2[ColorType2.HEX=2]="HEX",ColorType2[ColorType2.THEME=3]="THEME",ColorType2))(ColorType||{}),CommonHideTypes=(CommonHideTypes2=>(CommonHideTypes2[CommonHideTypes2.ON=0]="ON",CommonHideTypes2[CommonHideTypes2.OFF=1]="OFF",CommonHideTypes2))(CommonHideTypes||{}),CopyPasteType=(CopyPasteType2=>(CopyPasteType2[CopyPasteType2.PASTE_NORMAL=0]="PASTE_NORMAL",CopyPasteType2[CopyPasteType2.PASTE_NO_BORDERS=1]="PASTE_NO_BORDERS",CopyPasteType2[CopyPasteType2.PASTE_FORMAT=2]="PASTE_FORMAT",CopyPasteType2[CopyPasteType2.PASTE_FORMULA=3]="PASTE_FORMULA",CopyPasteType2[CopyPasteType2.PASTE_DATA_VALIDATION=4]="PASTE_DATA_VALIDATION",CopyPasteType2[CopyPasteType2.PASTE_VALUES=5]="PASTE_VALUES",CopyPasteType2[CopyPasteType2.PASTE_CONDITIONAL_FORMATTING=6]="PASTE_CONDITIONAL_FORMATTING",CopyPasteType2[CopyPasteType2.PASTE_COLUMN_WIDTHS=7]="PASTE_COLUMN_WIDTHS",CopyPasteType2))(CopyPasteType||{}),DeveloperMetadataVisibility=(DeveloperMetadataVisibility2=>(DeveloperMetadataVisibility2[DeveloperMetadataVisibility2.DOCUMENT=0]="DOCUMENT",DeveloperMetadataVisibility2[DeveloperMetadataVisibility2.PROJECT=1]="PROJECT",DeveloperMetadataVisibility2))(DeveloperMetadataVisibility||{}),Dimension=(Dimension2=>(Dimension2[Dimension2.COLUMNS=0]="COLUMNS",Dimension2[Dimension2.ROWS=1]="ROWS",Dimension2))(Dimension||{}),Direction=(Direction2=>(Direction2[Direction2.UP=0]="UP",Direction2[Direction2.RIGHT=1]="RIGHT",Direction2[Direction2.DOWN=2]="DOWN",Direction2[Direction2.LEFT=3]="LEFT",Direction2))(Direction||{});function getReverseDirection(direction){switch(direction){case 3:return 1;case 1:return 3;case 0:return 2;case 2:return 0}}__name(getReverseDirection,"getReverseDirection");var FormatType=(FormatType2=>(FormatType2[FormatType2.NUMBER_FORMAT_TYPE_UNSPECIFIED=0]="NUMBER_FORMAT_TYPE_UNSPECIFIED",FormatType2[FormatType2.TEXT=1]="TEXT",FormatType2[FormatType2.NUMBER=2]="NUMBER",FormatType2[FormatType2.PERCENT=3]="PERCENT",FormatType2[FormatType2.CURRENCY=4]="CURRENCY",FormatType2[FormatType2.DATE=5]="DATE",FormatType2[FormatType2.TIME=6]="TIME",FormatType2[FormatType2.DATE_TIME=7]="DATE_TIME",FormatType2[FormatType2.SCIENTIFIC=8]="SCIENTIFIC",FormatType2))(FormatType||{}),InterpolationPointType=(InterpolationPointType2=>(InterpolationPointType2[InterpolationPointType2.INTERPOLATION_POINT_TYPE_UNSPECIFIED=0]="INTERPOLATION_POINT_TYPE_UNSPECIFIED",InterpolationPointType2[InterpolationPointType2.MIN=1]="MIN",InterpolationPointType2[InterpolationPointType2.MAX=2]="MAX",InterpolationPointType2[InterpolationPointType2.NUMBER=3]="NUMBER",InterpolationPointType2[InterpolationPointType2.PERCENT=4]="PERCENT",InterpolationPointType2[InterpolationPointType2.PERCENTILE=5]="PERCENTILE",InterpolationPointType2))(InterpolationPointType||{}),LocaleType=(LocaleType2=>(LocaleType2.EN_US="enUS",LocaleType2.ZH_CN="zhCN",LocaleType2.RU_RU="ruRU",LocaleType2.ZH_TW="zhTW",LocaleType2.VI_VN="viVN",LocaleType2))(LocaleType||{}),ProtectionType=(ProtectionType2=>(ProtectionType2[ProtectionType2.RANGE=0]="RANGE",ProtectionType2[ProtectionType2.SHEET=1]="SHEET",ProtectionType2))(ProtectionType||{}),RelativeDate=(RelativeDate2=>(RelativeDate2[RelativeDate2.RELATIVE_DATE_UNSPECIFIED=0]="RELATIVE_DATE_UNSPECIFIED",RelativeDate2[RelativeDate2.PAST_YEAR=1]="PAST_YEAR",RelativeDate2[RelativeDate2.PAST_MONTH=2]="PAST_MONTH",RelativeDate2[RelativeDate2.PAST_WEEK=3]="PAST_WEEK",RelativeDate2[RelativeDate2.YESTERDAY=4]="YESTERDAY",RelativeDate2[RelativeDate2.TODAY=5]="TODAY",RelativeDate2[RelativeDate2.TOMORROW=6]="TOMORROW",RelativeDate2))(RelativeDate||{}),SheetTypes=(SheetTypes2=>(SheetTypes2[SheetTypes2.GRID=0]="GRID",SheetTypes2[SheetTypes2.KANBAN=1]="KANBAN",SheetTypes2[SheetTypes2.GANTT=2]="GANTT",SheetTypes2))(SheetTypes||{}),TextDirection=(TextDirection2=>(TextDirection2[TextDirection2.UNSPECIFIED=0]="UNSPECIFIED",TextDirection2[TextDirection2.LEFT_TO_RIGHT=1]="LEFT_TO_RIGHT",TextDirection2[TextDirection2.RIGHT_TO_LEFT=2]="RIGHT_TO_LEFT",TextDirection2))(TextDirection||{}),TextDecoration=(TextDecoration2=>(TextDecoration2[TextDecoration2.DASH=0]="DASH",TextDecoration2[TextDecoration2.DASH_DOT_DOT_HEAVY=1]="DASH_DOT_DOT_HEAVY",TextDecoration2[TextDecoration2.DASH_DOT_HEAVY=2]="DASH_DOT_HEAVY",TextDecoration2[TextDecoration2.DASHED_HEAVY=3]="DASHED_HEAVY",TextDecoration2[TextDecoration2.DASH_LONG=4]="DASH_LONG",TextDecoration2[TextDecoration2.DASH_LONG_HEAVY=5]="DASH_LONG_HEAVY",TextDecoration2[TextDecoration2.DOT_DASH=6]="DOT_DASH",TextDecoration2[TextDecoration2.DOT_DOT_DASH=7]="DOT_DOT_DASH",TextDecoration2[TextDecoration2.DOTTED=8]="DOTTED",TextDecoration2[TextDecoration2.DOTTED_HEAVY=9]="DOTTED_HEAVY",TextDecoration2[TextDecoration2.DOUBLE=10]="DOUBLE",TextDecoration2[TextDecoration2.NONE=11]="NONE",TextDecoration2[TextDecoration2.SINGLE=12]="SINGLE",TextDecoration2[TextDecoration2.THICK=13]="THICK",TextDecoration2[TextDecoration2.WAVE=14]="WAVE",TextDecoration2[TextDecoration2.WAVY_DOUBLE=15]="WAVY_DOUBLE",TextDecoration2[TextDecoration2.WAVY_HEAVY=16]="WAVY_HEAVY",TextDecoration2[TextDecoration2.WORDS=17]="WORDS",TextDecoration2))(TextDecoration||{}),HorizontalAlign=(HorizontalAlign2=>(HorizontalAlign2[HorizontalAlign2.UNSPECIFIED=0]="UNSPECIFIED",HorizontalAlign2[HorizontalAlign2.LEFT=1]="LEFT",HorizontalAlign2[HorizontalAlign2.CENTER=2]="CENTER",HorizontalAlign2[HorizontalAlign2.RIGHT=3]="RIGHT",HorizontalAlign2[HorizontalAlign2.JUSTIFIED=4]="JUSTIFIED",HorizontalAlign2[HorizontalAlign2.BOTH=5]="BOTH",HorizontalAlign2[HorizontalAlign2.DISTRIBUTED=6]="DISTRIBUTED",HorizontalAlign2))(HorizontalAlign||{}),VerticalAlign=(VerticalAlign2=>(VerticalAlign2[VerticalAlign2.UNSPECIFIED=0]="UNSPECIFIED",VerticalAlign2[VerticalAlign2.TOP=1]="TOP",VerticalAlign2[VerticalAlign2.MIDDLE=2]="MIDDLE",VerticalAlign2[VerticalAlign2.BOTTOM=3]="BOTTOM",VerticalAlign2))(VerticalAlign||{}),WrapStrategy=(WrapStrategy2=>(WrapStrategy2[WrapStrategy2.UNSPECIFIED=0]="UNSPECIFIED",WrapStrategy2[WrapStrategy2.OVERFLOW=1]="OVERFLOW",WrapStrategy2[WrapStrategy2.CLIP=2]="CLIP",WrapStrategy2[WrapStrategy2.WRAP=3]="WRAP",WrapStrategy2))(WrapStrategy||{}),FontItalic=(FontItalic2=>(FontItalic2[FontItalic2.NORMAL=0]="NORMAL",FontItalic2[FontItalic2.ITALIC=1]="ITALIC",FontItalic2))(FontItalic||{}),FontWeight=(FontWeight2=>(FontWeight2[FontWeight2.NORMAL=0]="NORMAL",FontWeight2[FontWeight2.BOLD=1]="BOLD",FontWeight2))(FontWeight||{}),BaselineOffset=(BaselineOffset2=>(BaselineOffset2[BaselineOffset2.NORMAL=1]="NORMAL",BaselineOffset2[BaselineOffset2.SUBSCRIPT=2]="SUBSCRIPT",BaselineOffset2[BaselineOffset2.SUPERSCRIPT=3]="SUPERSCRIPT",BaselineOffset2))(BaselineOffset||{}),BooleanNumber=(BooleanNumber2=>(BooleanNumber2[BooleanNumber2.FALSE=0]="FALSE",BooleanNumber2[BooleanNumber2.TRUE=1]="TRUE",BooleanNumber2))(BooleanNumber||{}),CellValueType=(CellValueType2=>(CellValueType2[CellValueType2.STRING=1]="STRING",CellValueType2[CellValueType2.NUMBER=2]="NUMBER",CellValueType2[CellValueType2.BOOLEAN=3]="BOOLEAN",CellValueType2[CellValueType2.FORCE_STRING=4]="FORCE_STRING",CellValueType2))(CellValueType||{}),ThemeColorType=(ThemeColorType2=>(ThemeColorType2[ThemeColorType2.DARK1=0]="DARK1",ThemeColorType2[ThemeColorType2.LIGHT1=1]="LIGHT1",ThemeColorType2[ThemeColorType2.DARK2=2]="DARK2",ThemeColorType2[ThemeColorType2.LIGHT2=3]="LIGHT2",ThemeColorType2[ThemeColorType2.ACCENT1=4]="ACCENT1",ThemeColorType2[ThemeColorType2.ACCENT2=5]="ACCENT2",ThemeColorType2[ThemeColorType2.ACCENT3=6]="ACCENT3",ThemeColorType2[ThemeColorType2.ACCENT4=7]="ACCENT4",ThemeColorType2[ThemeColorType2.ACCENT5=8]="ACCENT5",ThemeColorType2[ThemeColorType2.ACCENT6=9]="ACCENT6",ThemeColorType2[ThemeColorType2.HYPERLINK=10]="HYPERLINK",ThemeColorType2[ThemeColorType2.FOLLOWED_HYPERLINK=11]="FOLLOWED_HYPERLINK",ThemeColorType2))(ThemeColorType||{}),ThemeColors=(ThemeColors2=>(ThemeColors2.OFFICE="Office",ThemeColors2.OFFICE_2007_2010="Office 2007-2010",ThemeColors2.GRAYSCALE="Grayscale",ThemeColors2.BLUE_WARM="Blue Warm",ThemeColors2.BLUE="Blue",ThemeColors2.BLUE_II="Blue II",ThemeColors2.BLUE_GREEN="Blue Green",ThemeColors2.GREEN="Green",ThemeColors2.GREEN_YELLOW="Green Yellow",ThemeColors2.YELLOW="Yellow",ThemeColors2.YELLOW_ORANGE="Yellow Orange",ThemeColors2.ORANGE="Orange",ThemeColors2.ORANGE_RED="Orange Red",ThemeColors2.RED_ORANGE="Red Orange",ThemeColors2.RED="Red",ThemeColors2.RED_VIOLET="Red Violet",ThemeColors2.VIOLET="Violet",ThemeColors2.VIOLET_II="Violet II",ThemeColors2.MEDIAN="Median",ThemeColors2.PAPER="Paper",ThemeColors2.MARQUEE="Marquee",ThemeColors2.SLIPSTREAM="Slipstream",ThemeColors2.Aspect="Aspect",ThemeColors2))(ThemeColors||{}),BasicShapes=(BasicShapes2=>(BasicShapes2.Line="line",BasicShapes2.LineInv="lineInv",BasicShapes2.Triangle="triangle",BasicShapes2.RtTriangle="rtTriangle",BasicShapes2.Rect="rect",BasicShapes2.Diamond="diamond",BasicShapes2.Parallelogram="parallelogram",BasicShapes2.Trapezoid="trapezoid",BasicShapes2.NonIsocelesTrapezoid="nonIsocelesTrapezoid",BasicShapes2.Pentagon="pentagon",BasicShapes2.Hexagon="hexagon",BasicShapes2.Heptagon="heptagon",BasicShapes2.Octagon="octagon",BasicShapes2.Decagon="decagon",BasicShapes2.Dodecagon="dodecagon",BasicShapes2.Star4="star4",BasicShapes2.Star5="star5",BasicShapes2.Star6="star6",BasicShapes2.Star7="star7",BasicShapes2.Star8="star8",BasicShapes2.Star10="star10",BasicShapes2.Star12="star12",BasicShapes2.Star16="star16",BasicShapes2.Star24="star24",BasicShapes2.Star32="star32",BasicShapes2.RoundRect="roundRect",BasicShapes2.Round1Rect="round1Rect",BasicShapes2.Round2SameRect="round2SameRect",BasicShapes2.Round2DiagRect="round2DiagRect",BasicShapes2.Ellipse="ellipse",BasicShapes2))(BasicShapes||{}),ArrowsAndMarkersShapes=(ArrowsAndMarkersShapes2=>(ArrowsAndMarkersShapes2.RightArrow="rightArrow",ArrowsAndMarkersShapes2.LeftArrow="leftArrow",ArrowsAndMarkersShapes2.UpArrow="upArrow",ArrowsAndMarkersShapes2.DownArrow="downArrow",ArrowsAndMarkersShapes2.LeftRightArrow="leftRightArrow",ArrowsAndMarkersShapes2.UpDownArrow="upDownArrow",ArrowsAndMarkersShapes2.QuadArrow="quadArrow",ArrowsAndMarkersShapes2.LeftRightUpArrow="leftRightUpArrow",ArrowsAndMarkersShapes2.BentArrow="bentArrow",ArrowsAndMarkersShapes2.UturnArrow="uturnArrow",ArrowsAndMarkersShapes2.CircularArrow="circularArrow",ArrowsAndMarkersShapes2.NotchedRightArrow="notchedRightArrow",ArrowsAndMarkersShapes2.HomePlate="homePlate",ArrowsAndMarkersShapes2.Chevron="chevron",ArrowsAndMarkersShapes2.LeftCircularArrow="leftCircularArrow",ArrowsAndMarkersShapes2.LeftRightCircularArrow="leftRightCircularArrow",ArrowsAndMarkersShapes2))(ArrowsAndMarkersShapes||{}),OtherShapes=(OtherShapes2=>(OtherShapes2.Plaque="plaque",OtherShapes2.Can="can",OtherShapes2.Cube="cube",OtherShapes2.Bevel="bevel",OtherShapes2.Donut="donut",OtherShapes2.NoSmoking="noSmoking",OtherShapes2.BlockArc="blockArc",OtherShapes2.FoldedCorner="foldedCorner",OtherShapes2))(OtherShapes||{}),SpecialShapes=(SpecialShapes2=>(SpecialShapes2.SmileyFace="smileyFace",SpecialShapes2.Heart="heart",SpecialShapes2.LightningBolt="lightningBolt",SpecialShapes2.Sun="sun",SpecialShapes2.Moon="moon",SpecialShapes2.Cloud="cloud",SpecialShapes2.Arc="arc",SpecialShapes2.Backpack="backpack",SpecialShapes2.Frame="frame",SpecialShapes2.HalfFrame="halfFrame",SpecialShapes2.Corner="corner",SpecialShapes2.Chord="chord",SpecialShapes2.Pie="pie",SpecialShapes2.Teardrop="teardrop",SpecialShapes2.WedgeRectCallout="wedgeRectCallout",SpecialShapes2.WedgeRRectCallout="wedgeRRectCallout",SpecialShapes2.WedgeEllipseCallout="wedgeEllipseCallout",SpecialShapes2.CloudCallout="cloudCallout",SpecialShapes2.BorderCallout1="borderCallout1",SpecialShapes2.BorderCallout2="borderCallout2",SpecialShapes2.BorderCallout3="borderCallout3",SpecialShapes2.AccentCallout1="accentCallout1",SpecialShapes2.AccentCallout2="accentCallout2",SpecialShapes2.AccentCallout3="accentCallout3",SpecialShapes2.Callout1="callout1",SpecialShapes2.Callout2="callout2",SpecialShapes2.Callout3="callout3",SpecialShapes2.ActionButtonBackPrevious="actionButtonBackPrevious",SpecialShapes2.ActionButtonEnd="actionButtonEnd",SpecialShapes2.ActionButtonForwardNext="actionButtonForwardNext",SpecialShapes2.ActionButtonHelp="actionButtonHelp",SpecialShapes2.ActionButtonHome="actionButtonHome",SpecialShapes2.ActionButtonInformation="actionButtonInformation",SpecialShapes2.ActionButtonMovie="actionButtonMovie",SpecialShapes2.ActionButtonReturn="actionButtonReturn",SpecialShapes2.ActionButtonSound="actionButtonSound",SpecialShapes2))(SpecialShapes||{});const THEME_COLORS={[ThemeColors.OFFICE]:{[ThemeColorType.ACCENT1]:"#4472C4",[ThemeColorType.ACCENT2]:"#ED7D31",[ThemeColorType.ACCENT3]:"#A5A5A5",[ThemeColorType.ACCENT4]:"#70AD47",[ThemeColorType.ACCENT5]:"#5B9BD5",[ThemeColorType.ACCENT6]:"#70AD47",[ThemeColorType.DARK1]:"#000000",[ThemeColorType.DARK2]:"#44546A",[ThemeColorType.LIGHT1]:"#FFFFFF",[ThemeColorType.LIGHT2]:"#E7E6E6",[ThemeColorType.HYPERLINK]:"#0563C1",[ThemeColorType.FOLLOWED_HYPERLINK]:"#954F72"}},_ColorBuilder=class _ColorBuilder{constructor(){__publicField(this,"_themeValue",ThemeColorType.LIGHT1);__publicField(this,"_themeColors");__publicField(this,"_themeTint");__publicField(this,"_rgbValue","");__publicField(this,"_colorType");this._colorType=ColorType.UNSUPPORTED,this._themeColors=ThemeColors.OFFICE,this._themeTint=0}asRgbColor(){return new RgbColor(this._rgbValue,this)}asThemeColor(){return new ThemeColor(this._themeValue,this._themeTint,this._themeColors,this)}build(){switch(this._colorType){case ColorType.THEME:return this.asThemeColor();case ColorType.RGB:return this.asRgbColor();case ColorType.UNSUPPORTED:throw new Error("unsupported color type")}}setRgbColor(cssString){return this._colorType=ColorType.RGB,this._rgbValue=cssString,this}setThemeColors(value){this._colorType=ColorType.THEME,this._themeColors=value}setThemeTint(value){this._colorType=ColorType.THEME,this._themeTint=value}setThemeColor(theme){return this._colorType=ColorType.THEME,this._themeValue=theme,this}getColorType(){return this._colorType}};__name(_ColorBuilder,"ColorBuilder");let ColorBuilder=_ColorBuilder;const _Color=class _Color{constructor(builder){__publicField(this,"_builder");this._builder=builder}static rgbColorToHexValue(color){return`#${((1<<24)+(color.getRed()<<16)+(color.getGreen()<<8)+color.getBlue()).toString(16).slice(1)}`}static hexValueToRgbColor(hexValue){hexValue?hexValue.indexOf("#")>-1&&(hexValue=hexValue.substring(1)):hexValue="#000000";const r=+`0x${hexValue[0]}${hexValue[1]}`,g=+`0x${hexValue[2]}${hexValue[3]}`,b=+`0x${hexValue[4]}${hexValue[5]}`;return new ColorBuilder().setRgbColor(`rgb(${r},${g},${b})`).asRgbColor()}static hexToRgbString(hex){const shorthandRegex=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;hex=hex.replace(shorthandRegex,(m,r,g,b)=>r+r+g+g+b+b);const result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);let string=null;if(result){const r=Number.parseInt(result[1],16),g=Number.parseInt(result[2],16),b=Number.parseInt(result[3],16);string=`rgba(${r},${g},${b})`}return string}asRgbColor(){return this._builder.asRgbColor()}asThemeColor(){return this._builder.asThemeColor()}getColorType(){return this._builder.getColorType()}clone(){return new _Color(this._builder)}equals(color){return!1}};__name(_Color,"Color");let Color=_Color;const _HLSColor=class _HLSColor{constructor(rgbColor){__publicField(this,"_saturation",0);__publicField(this,"_hue",0);__publicField(this,"_lightness",0);__publicField(this,"_alpha",0);const red=rgbColor.getRed()/255,green=rgbColor.getGreen()/255,blue=rgbColor.getBlue()/255,alpha=rgbColor.getAlpha()/255,min=Math.min(red,Math.min(green,blue)),max=Math.max(red,Math.max(green,blue)),delta=max-min;if(max===min){this._hue=0,this._saturation=0,this._lightness=max;return}this._lightness=(min+max)/2,this._lightness<.5?this._saturation=delta/(max+min):this._saturation=delta/(2-max-min),red===max&&(this._hue=(green-blue)/delta),green===max&&(this._hue=2+(blue-red)/delta),blue===max&&(this._hue=4+(red-green)/delta),this._hue*=60,this._hue<0&&(this._hue+=360),this._alpha=alpha}asRgbColor(){const builder=new ColorBuilder;if(this._saturation===0)return builder.setRgbColor(`rgba(${this._lightness*255},${this._lightness*255},${this._lightness*255},${this._alpha*255})`),builder.asRgbColor();let t1;this._lightness<.5?t1=this._lightness*(1+this._saturation):t1=this._lightness+this._saturation-this._lightness*this._saturation;const t2=2*this._lightness-t1,hue=this._hue/360,tR=hue+1/3,red=this.setColor(t1,t2,tR),green=this.setColor(t1,t2,hue),tB=hue-1/3,blue=this.setColor(t1,t2,tB);return builder.setRgbColor(`rgba(${Math.round(red*255)},${Math.round(green*255)},${Math.round(blue*255)},${this._alpha*255})`),builder.asRgbColor()}getLightness(){return this._lightness}getHue(){return this._hue}getSaturation(){return this._saturation}getAlpha(){return this._alpha}setColor(t1,t2,t3){t3<0&&(t3+=1),t3>1&&(t3-=1);let color;return 6*t3<1?color=t2+(t1-t2)*6*t3:2*t3<1?color=t1:3*t3<2?color=t2+(t1-t2)*(2/3-t3)*6:color=t2,color}setLightness(lightness){this._lightness=lightness}};__name(_HLSColor,"HLSColor");let HLSColor=_HLSColor;const _RgbColor=class _RgbColor extends Color{constructor(cssString,builder){super(builder);__publicField(this,"_cssString");__publicField(this,"_red");__publicField(this,"_green");__publicField(this,"_blue");__publicField(this,"_alpha");let match=cssString.match(_RgbColor.RGBA_EXTRACT);if(match){const red=+match[1],green=+match[2],blue=+match[3],alpha=+match[4];this._cssString=cssString,this._red=red,this._green=green,this._blue=blue,this._alpha=alpha;return}if(match=cssString.match(_RgbColor.RGB_EXTRACT),match){const red=+match[1],green=+match[2],blue=+match[3];this._cssString=cssString,this._red=red,this._green=green,this._blue=blue,this._alpha=1;return}throw new Error("Invalid rgba or rgb color")}asHexString(){return Color.rgbColorToHexValue(this)}getRed(){let r=this._red+_RgbColor.RGB_COLOR_AMT;return r>255?r=255:r<0&&(r=0),r}getGreen(){let g=this._green+_RgbColor.RGB_COLOR_AMT;return g>255?g=255:g<0&&(g=0),g}getBlue(){let b=this._blue+_RgbColor.RGB_COLOR_AMT;return b>255?b=255:b<0&&(b=0),b}getAlpha(){return this._alpha}getColorType(){return ColorType.RGB}clone(){return new _RgbColor(this._cssString,this._builder)}asThemeColor(){throw new Error("rgb color not support to themeColor")}equals(color){return color instanceof _RgbColor?color._red===this._red&&color._blue===this._blue&&color._green===this._green&&color._alpha===this._alpha:!1}getCssString(){return this._cssString}};__name(_RgbColor,"RgbColor"),__publicField(_RgbColor,"RGB_COLOR_AMT",0),__publicField(_RgbColor,"RGBA_EXTRACT",new RegExp("\\s*rgba\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d.\\d|\\d\\s*)\\)\\s*")),__publicField(_RgbColor,"RGB_EXTRACT",new RegExp("\\s*rgb\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*)\\)\\s*"));let RgbColor=_RgbColor;const _ThemeColor=class _ThemeColor extends Color{constructor(theme,themeTint,themeColors,builder){super(builder);__publicField(this,"_themeColorType");__publicField(this,"_themeTint");__publicField(this,"_themeColors");this._themeColorType=theme,this._themeTint=themeTint,this._themeColors=themeColors}lumValue(tint,lum){if(tint==null)return lum;let value;return tint<0?value=lum*(1+tint):value=lum*(1-tint)+(255-255*(1-tint)),value}asRgbColor(){const themeColors=THEME_COLORS[this._themeColors];if(themeColors==null)throw new Error("not find themeColors type");const hexValue=themeColors[this._themeColorType];if(hexValue==null)throw new Error("not find themeColors value");let themeCache;if(_ThemeColor._cacheThemeColor.has(this._themeColors)){if(themeCache=_ThemeColor._cacheThemeColor.get(this._themeColors),themeCache.has(this._themeColorType))return themeCache.get(this._themeColorType)}else themeCache=new Map,_ThemeColor._cacheThemeColor.set(this._themeColors,themeCache);const hlsColor=new HLSColor(Color.hexValueToRgbColor(hexValue));hlsColor.setLightness(this.lumValue(this._themeTint,hlsColor.getLightness()*255)/255);const rgbColor=hlsColor.asRgbColor();return themeCache.set(this._themeColorType,rgbColor),rgbColor}clone(){return new _ThemeColor(this._themeColorType,this._themeTint,this._themeColors,this._builder)}equals(color){return color instanceof _ThemeColor?color._themeColorType===this._themeColorType:!1}getColorType(){return ColorType.THEME}getThemeColorType(){return this._themeColorType}};__name(_ThemeColor,"ThemeColor"),__publicField(_ThemeColor,"_cacheThemeColor",new Map);let ThemeColor=_ThemeColor;const RGB_PAREN="rgb(",RGBA_PAREN="rgba(",COLORS={aliceBlue:[240,248,255],antiqueWhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blancheAlmond:[255,235,205],blue:[0,0,255],blueViolet:[138,43,226],brown:[165,42,42],burlyWood:[222,184,135],cadetBlue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornFlowerBlue:[100,149,237],cornSilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkCyan:[0,139,139],darkGoldenrod:[184,132,11],darkGray:[169,169,169],darkGreen:[0,100,0],darkGrey:[169,169,169],darkKhaki:[189,183,107],darkMagenta:[139,0,139],darkOliveGreen:[85,107,47],darkOrange:[255,140,0],darkOrchid:[153,50,204],darkRed:[139,0,0],darkSalmon:[233,150,122],darkSeaGreen:[143,188,143],darkSlateBlue:[72,61,139],darkSlateGray:[47,79,79],darkSlateGrey:[47,79,79],darkTurquoise:[0,206,209],darkViolet:[148,0,211],deepPink:[255,20,147],deepSkyBlue:[0,191,255],dimGray:[105,105,105],dimGrey:[105,105,105],dodgerBlue:[30,144,255],firebrick:[178,34,34],floralWhite:[255,255,240],forestGreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostWhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenYellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotPink:[255,105,180],indianRed:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderBlush:[255,240,245],lawnGreen:[124,252,0],lemonChiffon:[255,250,205],lightblue:[173,216,230],lightCoral:[240,128,128],lightCyan:[224,255,255],lightGoldenrodYellow:[250,250,210],lightGray:[211,211,211],lightGreen:[144,238,144],lightGrey:[211,211,211],lightPink:[255,182,193],lightSalmon:[255,160,122],lightSeaGreen:[32,178,170],lightSkyBlue:[135,206,250],lightSlateGray:[119,136,153],lightSlateGrey:[119,136,153],lightSteelBlue:[176,196,222],lightYellow:[255,255,224],lime:[0,255,0],limeGreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumAquamarine:[102,205,170],mediumBlue:[0,0,205],mediumOrchid:[186,85,211],mediumPurple:[147,112,219],mediumSeaGreen:[60,179,113],mediumSlateBlue:[123,104,238],mediumSpringGreen:[0,250,154],mediumTurquoise:[72,209,204],mediumVioletRed:[199,21,133],midBightBlue:[25,25,112],mintCream:[245,255,250],mistyRose:[255,228,225],moccasin:[255,228,181],navajoWhite:[255,222,173],navy:[0,0,128],oldLace:[253,245,230],olive:[128,128,0],oliveDrab:[107,142,35],orange:[255,165,0],orangeRed:[255,69,0],orchid:[218,112,214],paleGoldenrod:[238,232,170],paleGreen:[152,251,152],paleTurquoise:[175,238,238],paleVioletRed:[219,112,147],papayaWhip:[255,239,213],peachPuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderBlue:[176,224,230],purple:[128,0,128],rebeccaPurple:[102,51,153],red:[255,0,0],rosyBrown:[188,143,143],royalBlue:[65,105,225],saddleBrown:[139,69,19],salmon:[250,128,114],sandyBrown:[244,164,96],seaGreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyBlue:[135,206,235],slateBlue:[106,90,205],slateGray:[119,128,144],slateGrey:[119,128,144],snow:[255,255,250],springGreen:[0,255,127],steelBlue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whiteSmoke:[245,245,245],yellow:[255,255,0],yellowGreen:[154,205,5]},_ColorKit=class _ColorKit{constructor(color){__publicField(this,"_color");__publicField(this,"_rgbColor");__publicField(this,"_isValid",!1);if(color==null){this._setNullColor();return}if(color instanceof _ColorKit){this._color={...color._color},this._rgbColor={...color._rgbColor};return}const colorObject=toColor(color);if(colorObject==null){this._setNullColor();return}this._color=colorObject;const rgbColorObject=toRgbColor(this._color);if(rgbColorObject==null){this._setNullColor();return}this._rgbColor=rgbColorObject,this._isValid=!0}static mix(color1,color2,amount){var _a13,_b2;amount=Math.min(1,Math.max(0,amount));const rgb1=new _ColorKit(color1).toRgb(),rgb2=new _ColorKit(color2).toRgb(),alpha1=(_a13=rgb1.a)!=null?_a13:1,alpha2=(_b2=rgb2.a)!=null?_b2:1,rgba={r:(rgb2.r-rgb1.r)*amount+rgb1.r,g:(rgb2.g-rgb1.g)*amount+rgb1.g,b:(rgb2.b-rgb1.b)*amount+rgb1.b,a:(alpha2-alpha1)*amount+alpha1};return new _ColorKit(rgba)}static getContrastRatio(foreground,background){const lumA=new _ColorKit(foreground).getLuminance(),lumB=new _ColorKit(background).getLuminance();return(Math.max(lumA,lumB)+.05)/(Math.min(lumA,lumB)+.05)}get isValid(){return this._isValid}toRgb(){return this._rgbColor}toRgbString(){const{r,g,b,a=1}=this.toRgb(),useAlpha=a<1;return`rgb${useAlpha?"a":""}(${r},${g},${b}${useAlpha?`,${a}`:""})`}toString(){return this.toRgbString()}toHexString(allowShort){const{r,g,b,a=1}=this.toRgb(),useAlpha=a<1,hex=[pad2(Math.round(r).toString(16)),pad2(Math.round(g).toString(16)),pad2(Math.round(b).toString(16)),pad2(Math.round(a*255).toString(16))];return allowShort&&hex[0][0]===hex[0][1]&&hex[1][0]===hex[1][1]&&hex[2][0]===hex[2][1]&&hex[3][0]===hex[3][1]?useAlpha?`#${hex[0][0]}${hex[1][0]}${hex[2][0]}${hex[3][0]}`:`#${hex[0][0]}${hex[1][0]}${hex[2][0]}`:useAlpha?`#${hex[0]}${hex[1]}${hex[2]}${hex[3]}`:`#${hex[0]}${hex[1]}${hex[2]}`}toHsv(){return rgb2Hsv(this.toRgb())}toHsl(){return rgb2Hsl(this.toRgb())}lighten(amount=10){const hsl=this.toHsl();return hsl.l+=amount,hsl.l=Math.min(Math.max(hsl.l,0),100),new _ColorKit(hsl)}darken(amount=10){const hsl=this.toHsl();return hsl.l-=amount,hsl.l=Math.min(Math.max(hsl.l,0),100),new _ColorKit(hsl)}setAlpha(value){return new _ColorKit({...this._rgbColor,a:value})}getLuminance(){let{r,g,b}=this.toRgb();return r=rgbNormalize(r),g=rgbNormalize(g),b=rgbNormalize(b),Number((.2126*r+.7152*g+.0722*b).toFixed(3))}getBrightness(){const{r,g,b}=this.toRgb();return(r*299+g*587+b*114)/1e3}getAlpha(){var _a13;return(_a13=this._color.a)!=null?_a13:1}isDark(){return this.getBrightness()<128}isLight(){return!this.isDark()}_setNullColor(){this._isValid=!1,this._color={r:0,g:0,b:0,a:0},this._rgbColor={r:0,g:0,b:0,a:0}}};__name(_ColorKit,"ColorKit");let ColorKit=_ColorKit;const pad2=__name(v=>v.length===1?`0${v}`:v,"pad2"),rgbNormalize=__name(val=>(val/=255,val<=.03928?val/12.92:((val+.055)/1.055)**2.4),"rgbNormalize"),toColor=__name(color=>{if(isObject(color)){if("r"in color){const rgb={r:Math.round(color.r),g:Math.round(color.g),b:Math.round(color.b)};return color.a!==void 0&&(rgb.a=color.a),rgb}if("l"in color){const hsl={h:Math.round(color.h),s:color.s,l:color.l};return color.a!==void 0&&(hsl.a=color.a),hsl}const hsv={h:Math.round(color.h),s:color.s,v:color.v};return color.a!==void 0&&(hsv.a=color.a),hsv}const parsedColor=color.trim();if(COLORS[parsedColor]){const colorArray=COLORS[parsedColor],rgb={r:Math.round(colorArray[0]),g:Math.round(colorArray[1]),b:Math.round(colorArray[2])};return rgb.a=colorArray[3]||1,rgb}if(parsedColor.startsWith("#"))return hexToColor(parsedColor);if(parsedColor.startsWith("rgb"))return rgbToColor(parsedColor);if(parsedColor.startsWith("hsl"))return hslToColor(parsedColor);if(parsedColor.startsWith("hsv"))return hsvToColor(parsedColor)},"toColor"),hexToColor=__name(color=>{const parsedColor=color.substring(1),re=new RegExp(`.{1,${parsedColor.length>=6?2:1}}`,"g");let colors=parsedColor.match(re);if(!colors||colors.length<3)throw new Error(`The color '${color}' is illegal hex color`);colors[0].length===1&&(colors=colors.map(n=>n+n));const rgbColor={r:Number.parseInt(colors[0],16),g:Number.parseInt(colors[1],16),b:Number.parseInt(colors[2],16)};return colors.length>3&&(rgbColor.a=Number.parseInt(colors[3],16)/255),rgbColor},"hexToColor"),rgbToColor=__name(color=>{const matcher=color.indexOf("(");if(matcher===-1)throw new Error(`The color '${color}' is illegal rgb color`);const values=color.substring(matcher+1,color.length-1).split(",");if(values.length<3)throw new Error(`The color '${color}' is illegal rgb color`);const rgbColor={r:Number.parseInt(values[0],10),g:Number.parseInt(values[1],10),b:Number.parseInt(values[2],10)};return values.length>3&&(rgbColor.a=Number.parseFloat(values[3])),rgbColor},"rgbToColor"),hslToColor=__name(color=>{const matcher=color.indexOf("(");if(matcher===-1)throw new Error(`The color '${color}' is illegal hsl color`);const values=color.substring(matcher+1,color.length-1).split(",");if(values.length<3)throw new Error(`The color '${color}' is illegal hsl color`);const hslColor={h:Number.parseInt(values[0],10),s:Number.parseFloat(values[1]),l:Number.parseFloat(values[2])};return values.length>3&&(hslColor.a=Number.parseFloat(values[3])),hslColor},"hslToColor"),hsvToColor=__name(color=>{const matcher=color.indexOf("(");if(matcher===-1)throw new Error(`The color '${color}' is illegal hsv color`);const values=color.substring(matcher+1,color.length-1).split(",");if(values.length<3)throw new Error(`The color '${color}' is illegal hsv color`);const hsvColor={h:Number.parseInt(values[0],10),s:Number.parseFloat(values[1]),v:Number.parseFloat(values[2])};return values.length>3&&(hsvColor.a=Number.parseFloat(values[3])),hsvColor},"hsvToColor"),toRgbColor=__name(color=>{const obj=toColor(color);if(obj!=null)return"r"in obj?obj:"l"in obj?hsl2Rgb(obj):hsv2Rgb(obj)},"toRgbColor"),hue2Rgb=__name((p,q,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+(q-p)*6*t:t<1/2?q:t<2/3?p+(q-p)*(2/3-t)*6:p),"hue2Rgb"),hsl2Rgb=__name(color=>{let{h,s,l:l2}=color;h/=360,s/=100,l2/=100;let r=0,g=0,b=0;if(s===0)r=g=b=l2;else{const q=l2<.5?l2*(1+s):l2+s-l2*s,p=2*l2-q;r=hue2Rgb(p,q,h+1/3),g=hue2Rgb(p,q,h),b=hue2Rgb(p,q,h-1/3)}const IRgbColor={r:Math.round(r*255),g:Math.round(g*255),b:Math.round(b*255)};return color.a!==void 0&&(IRgbColor.a=color.a),IRgbColor},"hsl2Rgb"),hsv2Rgb=__name(color=>{let{h,s,v}=color;h=h/360*6,s/=100,v/=100;const i=Math.floor(h),f=h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s),mod=i%6,r=[v,q,p,p,t,v][mod],g=[t,v,v,q,p,p][mod],b=[p,p,t,v,v,q][mod],IRgbColor={r:r*255,g:g*255,b:b*255};return color.a!==void 0&&(IRgbColor.a=color.a),IRgbColor},"hsv2Rgb"),rgb2Hsl=__name(color=>{let{r,g,b}=color;r/=255,g/=255,b/=255;const max=Math.max(r,g,b),min=Math.min(r,g,b),l2=(max+min)/2;let h,s;if(max===min)h=s=0;else{const d=max-min;switch(s=l2>.5?d/(2-max-min):d/(max+min),max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;default:h=(r-g)/d+4;break}h/=6}const hslColor={h:Math.round(h*360),s:Math.round(s*100),l:Math.round(l2*100)};return color.a!==void 0&&(hslColor.a=color.a),hslColor},"rgb2Hsl"),rgb2Hsv=__name(color=>{let{r,g,b}=color;r/=255,g/=255,b/=255;const max=Math.max(r,g,b),min=Math.min(r,g,b);let h;const v=max,d=max-min,s=max===0?0:d/max;if(max===min)h=0;else{switch(max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;default:h=(r-g)/d+4;break}h/=6}const hsvColor={h:Math.round(h*360),s:Math.round(s*100),v:Math.round(v*100)};return color.a!==void 0&&(hsvColor.a=color.a),hsvColor},"rgb2Hsv"),isUndefinedOrNull=__name(value=>value==null,"isUndefinedOrNull"),isObject=__name(value=>!isUndefinedOrNull(value)&&typeof value=="object","isObject");function isBlackColor(color){const hexRegex=/^#(?:[0]{3}|[0]{6})\b/,rgbRegex=/^rgb\s*\(\s*0+\s*,\s*0+\s*,\s*0+\s*\)$/,rgbaRegex=/^rgba\s*\(\s*0+\s*,\s*0+\s*,\s*0+\s*,\s*(1|1\.0*|0?\.\d+)\)$/,hslRegex=/^hsl\s*\(\s*0*\s*,\s*0%*\s*,\s*0%*\s*\)$/,hslaRegex=/^hsla\s*\(\s*0*\s*,\s*0%*\s*,\s*0%*\s*,\s*(1|1\.0*|0?\.\d+)\)$/;return!!(hexRegex.test(color)||rgbRegex.test(color)||rgbaRegex.test(color)||hslRegex.test(color)||hslaRegex.test(color))}__name(isBlackColor,"isBlackColor");function isWhiteColor(color){const hexRegex=/^#(?:[Ff]{3}|[Ff]{6})\b/,rgbRegex=/^rgb\s*\(\s*255\s*,\s*255\s*,\s*255\s*\)$/,rgbaRegex=/^rgba\s*\(\s*255\s*,\s*255\s*,\s*255\s*,\s*(1|1\.0*|0?\.\d+)\)$/,hslRegex=/^hsl\s*\(\s*0*\s*,\s*0%*\s*,\s*100%*\s*\)$/,hslaRegex=/^hsla\s*\(\s*0*\s*,\s*0%*\s*,\s*100%*\s*,\s*(1|1\.0*|0?\.\d+)\)$/;return!!(hexRegex.test(color)||rgbRegex.test(color)||rgbaRegex.test(color)||hslRegex.test(color)||hslaRegex.test(color))}__name(isWhiteColor,"isWhiteColor");var UpdateDocsAttributeType=(UpdateDocsAttributeType2=>(UpdateDocsAttributeType2[UpdateDocsAttributeType2.COVER=0]="COVER",UpdateDocsAttributeType2[UpdateDocsAttributeType2.REPLACE=1]="REPLACE",UpdateDocsAttributeType2[UpdateDocsAttributeType2.INTERSECTION=2]="INTERSECTION",UpdateDocsAttributeType2))(UpdateDocsAttributeType||{});function isICellData(value){return value&&(value.s!==void 0||value.p!==void 0||value.v!==void 0||value.t!==void 0||value.f!==void 0||value.si!==void 0)}__name(isICellData,"isICellData");function getCellValueType(cell){if(cell.t!==void 0)return cell.t;if(typeof cell.v=="string")return CellValueType.STRING;if(typeof cell.v=="number")return CellValueType.NUMBER;if(typeof cell.v=="boolean")return CellValueType.BOOLEAN}__name(getCellValueType,"getCellValueType");function isNullCell(cell){if(cell==null)return!0;const{v,f,si,p,s,custom}=cell;return!(!(v==null||typeof v=="string"&&v.length===0)||f!=null&&f.length>0||si!=null&&si.length>0||p!=null||custom!=null)}__name(isNullCell,"isNullCell");function isCellV(cell){return cell!=null&&(typeof cell=="string"||typeof cell=="number"||typeof cell=="boolean")}__name(isCellV,"isCellV");var DocStyleType=(DocStyleType2=>(DocStyleType2[DocStyleType2.character=0]="character",DocStyleType2[DocStyleType2.paragraph=1]="paragraph",DocStyleType2[DocStyleType2.table=2]="table",DocStyleType2[DocStyleType2.numbering=3]="numbering",DocStyleType2))(DocStyleType||{}),FollowNumberWithType=(FollowNumberWithType2=>(FollowNumberWithType2[FollowNumberWithType2.TAB=0]="TAB",FollowNumberWithType2[FollowNumberWithType2.SPACE=1]="SPACE",FollowNumberWithType2[FollowNumberWithType2.NOTHING=2]="NOTHING",FollowNumberWithType2))(FollowNumberWithType||{}),GlyphType=(GlyphType2=>(GlyphType2[GlyphType2.BULLET=0]="BULLET",GlyphType2[GlyphType2.NONE=1]="NONE",GlyphType2[GlyphType2.DECIMAL=2]="DECIMAL",GlyphType2[GlyphType2.DECIMAL_ZERO=3]="DECIMAL_ZERO",GlyphType2[GlyphType2.UPPER_LETTER=4]="UPPER_LETTER",GlyphType2[GlyphType2.LOWER_LETTER=5]="LOWER_LETTER",GlyphType2[GlyphType2.UPPER_ROMAN=6]="UPPER_ROMAN",GlyphType2[GlyphType2.LOWER_ROMAN=7]="LOWER_ROMAN",GlyphType2[GlyphType2.ORDINAL=8]="ORDINAL",GlyphType2[GlyphType2.CARDINAL_TEXT=9]="CARDINAL_TEXT",GlyphType2[GlyphType2.ORDINAL_TEXT=10]="ORDINAL_TEXT",GlyphType2[GlyphType2.HEX=11]="HEX",GlyphType2[GlyphType2.CHICAGO=12]="CHICAGO",GlyphType2[GlyphType2.IDEOGRAPH_DIGITAL=13]="IDEOGRAPH_DIGITAL",GlyphType2[GlyphType2.JAPANESE_COUNTING=14]="JAPANESE_COUNTING",GlyphType2[GlyphType2.AIUEO=15]="AIUEO",GlyphType2[GlyphType2.IROHA=16]="IROHA",GlyphType2[GlyphType2.DECIMAL_FULL_WIDTH=17]="DECIMAL_FULL_WIDTH",GlyphType2[GlyphType2.DECIMAL_HALF_WIDTH=18]="DECIMAL_HALF_WIDTH",GlyphType2[GlyphType2.JAPANESE_LEGAL=19]="JAPANESE_LEGAL",GlyphType2[GlyphType2.JAPANESE_DIGITAL_TEN_THOUSAND=20]="JAPANESE_DIGITAL_TEN_THOUSAND",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_CIRCLE=21]="DECIMAL_ENCLOSED_CIRCLE",GlyphType2[GlyphType2.DECIMAL_FULL_WIDTH2=22]="DECIMAL_FULL_WIDTH2",GlyphType2[GlyphType2.AIUEO_FULL_WIDTH=23]="AIUEO_FULL_WIDTH",GlyphType2[GlyphType2.IROHA_FULL_WIDTH=24]="IROHA_FULL_WIDTH",GlyphType2[GlyphType2.GANADA=25]="GANADA",GlyphType2[GlyphType2.CHOSUNG=26]="CHOSUNG",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_FULLSTOP=27]="DECIMAL_ENCLOSED_FULLSTOP",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_PAREN=28]="DECIMAL_ENCLOSED_PAREN",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_CIRCLE_CHINESE=29]="DECIMAL_ENCLOSED_CIRCLE_CHINESE",GlyphType2[GlyphType2.IDEOGRAPH_ENCLOSED_CIRCLE=30]="IDEOGRAPH_ENCLOSED_CIRCLE",GlyphType2[GlyphType2.IDEOGRAPH_TRADITIONAL=31]="IDEOGRAPH_TRADITIONAL",GlyphType2[GlyphType2.IDEOGRAPH_ZODIAC=32]="IDEOGRAPH_ZODIAC",GlyphType2[GlyphType2.IDEOGRAPH_ZODIAC_TRADITIONAL=33]="IDEOGRAPH_ZODIAC_TRADITIONAL",GlyphType2[GlyphType2.TAIWANESE_COUNTING=34]="TAIWANESE_COUNTING",GlyphType2[GlyphType2.IDEOGRAPH_LEGAL_TRADITIONAL=35]="IDEOGRAPH_LEGAL_TRADITIONAL",GlyphType2[GlyphType2.TAIWANESE_COUNTING_THOUSAND=36]="TAIWANESE_COUNTING_THOUSAND",GlyphType2[GlyphType2.TAIWANESE_DIGITAL=37]="TAIWANESE_DIGITAL",GlyphType2[GlyphType2.CHINESE_COUNTING=38]="CHINESE_COUNTING",GlyphType2[GlyphType2.CHINESE_LEGAL_SIMPLIFIED=39]="CHINESE_LEGAL_SIMPLIFIED",GlyphType2[GlyphType2.CHINESE_COUNTING_THOUSAND=40]="CHINESE_COUNTING_THOUSAND",GlyphType2[GlyphType2.KOREAN_DIGITAL=41]="KOREAN_DIGITAL",GlyphType2[GlyphType2.KOREAN_COUNTING=42]="KOREAN_COUNTING",GlyphType2[GlyphType2.KOREAN_LEGAL=43]="KOREAN_LEGAL",GlyphType2[GlyphType2.KOREAN_DIGITAL2=44]="KOREAN_DIGITAL2",GlyphType2[GlyphType2.VIETNAMESE_COUNTING=45]="VIETNAMESE_COUNTING",GlyphType2[GlyphType2.RUSSIAN_LOWER=46]="RUSSIAN_LOWER",GlyphType2[GlyphType2.RUSSIAN_UPPER=47]="RUSSIAN_UPPER",GlyphType2[GlyphType2.NUMBER_IN_DASH=48]="NUMBER_IN_DASH",GlyphType2[GlyphType2.HEBREW1=49]="HEBREW1",GlyphType2[GlyphType2.HEBREW2=50]="HEBREW2",GlyphType2[GlyphType2.ARABIC_ALPHA=51]="ARABIC_ALPHA",GlyphType2[GlyphType2.ARABIC_ABJAD=52]="ARABIC_ABJAD",GlyphType2[GlyphType2.HINDI_VOWELS=53]="HINDI_VOWELS",GlyphType2[GlyphType2.HINDI_CONSONANTS=54]="HINDI_CONSONANTS",GlyphType2[GlyphType2.HINDI_NUMBERS=55]="HINDI_NUMBERS",GlyphType2[GlyphType2.HINDI_COUNTING=56]="HINDI_COUNTING",GlyphType2[GlyphType2.THAI_LETTERS=57]="THAI_LETTERS",GlyphType2[GlyphType2.THAI_NUMBERS=58]="THAI_NUMBERS",GlyphType2[GlyphType2.THAI_COUNTING=59]="THAI_COUNTING",GlyphType2[GlyphType2.CUSTOM=60]="CUSTOM",GlyphType2))(GlyphType||{}),BulletAlignment=(BulletAlignment2=>(BulletAlignment2[BulletAlignment2.BULLET_ALIGNMENT_UNSPECIFIED=0]="BULLET_ALIGNMENT_UNSPECIFIED",BulletAlignment2[BulletAlignment2.START=1]="START",BulletAlignment2[BulletAlignment2.CENTER=2]="CENTER",BulletAlignment2[BulletAlignment2.END=3]="END",BulletAlignment2[BulletAlignment2.BOTH=4]="BOTH",BulletAlignment2))(BulletAlignment||{}),CustomRangeType=(CustomRangeType2=>(CustomRangeType2[CustomRangeType2.HYPERLINK=0]="HYPERLINK",CustomRangeType2[CustomRangeType2.FIELD=1]="FIELD",CustomRangeType2[CustomRangeType2.SDT=2]="SDT",CustomRangeType2[CustomRangeType2.BOOKMARK=3]="BOOKMARK",CustomRangeType2[CustomRangeType2.COMMENT=4]="COMMENT",CustomRangeType2[CustomRangeType2.CUSTOM=5]="CUSTOM",CustomRangeType2[CustomRangeType2.MENTION=6]="MENTION",CustomRangeType2[CustomRangeType2.UNI_FORMULA=7]="UNI_FORMULA",CustomRangeType2))(CustomRangeType||{}),CustomDecorationType=(CustomDecorationType2=>(CustomDecorationType2[CustomDecorationType2.COMMENT=0]="COMMENT",CustomDecorationType2))(CustomDecorationType||{}),BlockType=(BlockType2=>(BlockType2[BlockType2.DRAWING=0]="DRAWING",BlockType2[BlockType2.CUSTOM=1]="CUSTOM",BlockType2))(BlockType||{}),DocumentFlavor=(DocumentFlavor2=>(DocumentFlavor2[DocumentFlavor2.TRADITIONAL=0]="TRADITIONAL",DocumentFlavor2[DocumentFlavor2.MODERN=1]="MODERN",DocumentFlavor2))(DocumentFlavor||{}),GridType=(GridType2=>(GridType2[GridType2.DEFAULT=0]="DEFAULT",GridType2[GridType2.LINES=1]="LINES",GridType2[GridType2.LINES_AND_CHARS=2]="LINES_AND_CHARS",GridType2[GridType2.SNAP_TO_CHARS=3]="SNAP_TO_CHARS",GridType2))(GridType||{}),SectionType=(SectionType2=>(SectionType2[SectionType2.SECTION_TYPE_UNSPECIFIED=0]="SECTION_TYPE_UNSPECIFIED",SectionType2[SectionType2.CONTINUOUS=1]="CONTINUOUS",SectionType2[SectionType2.NEXT_PAGE=2]="NEXT_PAGE",SectionType2[SectionType2.EVEN_PAGE=3]="EVEN_PAGE",SectionType2[SectionType2.ODD_PAGE=4]="ODD_PAGE",SectionType2))(SectionType||{}),ColumnSeparatorType=(ColumnSeparatorType2=>(ColumnSeparatorType2[ColumnSeparatorType2.COLUMN_SEPARATOR_STYLE_UNSPECIFIED=0]="COLUMN_SEPARATOR_STYLE_UNSPECIFIED",ColumnSeparatorType2[ColumnSeparatorType2.NONE=1]="NONE",ColumnSeparatorType2[ColumnSeparatorType2.BETWEEN_EACH_COLUMN=2]="BETWEEN_EACH_COLUMN",ColumnSeparatorType2))(ColumnSeparatorType||{}),TextDirectionType=(TextDirectionType2=>(TextDirectionType2[TextDirectionType2.NORMAL=0]="NORMAL",TextDirectionType2[TextDirectionType2.TBRL=1]="TBRL",TextDirectionType2[TextDirectionType2.LRTBV=2]="LRTBV",TextDirectionType2))(TextDirectionType||{}),ParagraphElementType=(ParagraphElementType2=>(ParagraphElementType2[ParagraphElementType2.TEXT_RUN=0]="TEXT_RUN",ParagraphElementType2[ParagraphElementType2.AUTO_TEXT=1]="AUTO_TEXT",ParagraphElementType2[ParagraphElementType2.PAGE_BREAK=2]="PAGE_BREAK",ParagraphElementType2[ParagraphElementType2.COLUMN_BREAK=3]="COLUMN_BREAK",ParagraphElementType2[ParagraphElementType2.FOOT_NOTE_REFERENCE=4]="FOOT_NOTE_REFERENCE",ParagraphElementType2[ParagraphElementType2.HORIZONTAL_RULE=5]="HORIZONTAL_RULE",ParagraphElementType2[ParagraphElementType2.EQUATION=6]="EQUATION",ParagraphElementType2[ParagraphElementType2.DRAWING=7]="DRAWING",ParagraphElementType2[ParagraphElementType2.PERSON=8]="PERSON",ParagraphElementType2[ParagraphElementType2.RICH_LINK=9]="RICH_LINK",ParagraphElementType2))(ParagraphElementType||{}),WrapTextType=(WrapTextType2=>(WrapTextType2[WrapTextType2.BOTH_SIDES=0]="BOTH_SIDES",WrapTextType2[WrapTextType2.LEFT=1]="LEFT",WrapTextType2[WrapTextType2.RIGHT=2]="RIGHT",WrapTextType2[WrapTextType2.LARGEST=3]="LARGEST",WrapTextType2))(WrapTextType||{}),PositionedObjectLayoutType=(PositionedObjectLayoutType2=>(PositionedObjectLayoutType2[PositionedObjectLayoutType2.INLINE=0]="INLINE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_NONE=1]="WRAP_NONE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_POLYGON=2]="WRAP_POLYGON",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_SQUARE=3]="WRAP_SQUARE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_THROUGH=4]="WRAP_THROUGH",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_TIGHT=5]="WRAP_TIGHT",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_TOP_AND_BOTTOM=6]="WRAP_TOP_AND_BOTTOM",PositionedObjectLayoutType2))(PositionedObjectLayoutType||{}),NamedStyleType=(NamedStyleType2=>(NamedStyleType2[NamedStyleType2.NAMED_STYLE_TYPE_UNSPECIFIED=0]="NAMED_STYLE_TYPE_UNSPECIFIED",NamedStyleType2[NamedStyleType2.NORMAL_TEXT=1]="NORMAL_TEXT",NamedStyleType2[NamedStyleType2.TITLE=2]="TITLE",NamedStyleType2[NamedStyleType2.SUBTITLE=3]="SUBTITLE",NamedStyleType2[NamedStyleType2.HEADING_1=4]="HEADING_1",NamedStyleType2[NamedStyleType2.HEADING_2=5]="HEADING_2",NamedStyleType2[NamedStyleType2.HEADING_3=6]="HEADING_3",NamedStyleType2[NamedStyleType2.HEADING_4=7]="HEADING_4",NamedStyleType2[NamedStyleType2.HEADING_5=8]="HEADING_5",NamedStyleType2[NamedStyleType2.HEADING_6=9]="HEADING_6",NamedStyleType2))(NamedStyleType||{}),SpacingRule=(SpacingRule2=>(SpacingRule2[SpacingRule2.AUTO=0]="AUTO",SpacingRule2[SpacingRule2.AT_LEAST=1]="AT_LEAST",SpacingRule2[SpacingRule2.EXACT=2]="EXACT",SpacingRule2))(SpacingRule||{}),DashStyleType=(DashStyleType2=>(DashStyleType2[DashStyleType2.DASH_STYLE_UNSPECIFIED=0]="DASH_STYLE_UNSPECIFIED",DashStyleType2[DashStyleType2.SOLID=1]="SOLID",DashStyleType2[DashStyleType2.DOT=2]="DOT",DashStyleType2[DashStyleType2.DASH=3]="DASH",DashStyleType2))(DashStyleType||{}),TabStopAlignment=(TabStopAlignment2=>(TabStopAlignment2[TabStopAlignment2.TAB_STOP_ALIGNMENT_UNSPECIFIED=0]="TAB_STOP_ALIGNMENT_UNSPECIFIED",TabStopAlignment2[TabStopAlignment2.START=1]="START",TabStopAlignment2[TabStopAlignment2.CENTER=2]="CENTER",TabStopAlignment2[TabStopAlignment2.END=3]="END",TabStopAlignment2))(TabStopAlignment||{}),WidthType=(WidthType2=>(WidthType2.EVENLY_DISTRIBUTED="0",WidthType2.FIXED_WIDTH="1",WidthType2))(WidthType||{}),ContentAlignment=(ContentAlignment2=>(ContentAlignment2[ContentAlignment2.CONTENT_ALIGNMENT_UNSPECIFIED=0]="CONTENT_ALIGNMENT_UNSPECIFIED",ContentAlignment2[ContentAlignment2.CONTENT_ALIGNMENT_UNSUPPORTED=1]="CONTENT_ALIGNMENT_UNSUPPORTED",ContentAlignment2[ContentAlignment2.TOP=2]="TOP",ContentAlignment2[ContentAlignment2.MIDDLE=3]="MIDDLE",ContentAlignment2[ContentAlignment2.BOTTOM=4]="BOTTOM",ContentAlignment2))(ContentAlignment||{}),FontStyleType=(FontStyleType2=>(FontStyleType2.NORMAL="normal",FontStyleType2.BOLD="bold",FontStyleType2.ITALIC="italic",FontStyleType2))(FontStyleType||{}),ObjectRelativeFromH=(ObjectRelativeFromH2=>(ObjectRelativeFromH2[ObjectRelativeFromH2.PAGE=0]="PAGE",ObjectRelativeFromH2[ObjectRelativeFromH2.COLUMN=1]="COLUMN",ObjectRelativeFromH2[ObjectRelativeFromH2.CHARACTER=2]="CHARACTER",ObjectRelativeFromH2[ObjectRelativeFromH2.MARGIN=3]="MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.INSIDE_MARGIN=4]="INSIDE_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.OUTSIDE_MARGIN=5]="OUTSIDE_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.LEFT_MARGIN=6]="LEFT_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.RIGHT_MARGIN=7]="RIGHT_MARGIN",ObjectRelativeFromH2))(ObjectRelativeFromH||{}),ObjectRelativeFromV=(ObjectRelativeFromV2=>(ObjectRelativeFromV2[ObjectRelativeFromV2.PAGE=0]="PAGE",ObjectRelativeFromV2[ObjectRelativeFromV2.PARAGRAPH=1]="PARAGRAPH",ObjectRelativeFromV2[ObjectRelativeFromV2.LINE=2]="LINE",ObjectRelativeFromV2[ObjectRelativeFromV2.MARGIN=3]="MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.TOP_MARGIN=4]="TOP_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.BOTTOM_MARGIN=5]="BOTTOM_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.INSIDE_MARGIN=6]="INSIDE_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.OUTSIDE_MARGIN=7]="OUTSIDE_MARGIN",ObjectRelativeFromV2))(ObjectRelativeFromV||{}),NumberUnitType=(NumberUnitType2=>(NumberUnitType2[NumberUnitType2.POINT=0]="POINT",NumberUnitType2[NumberUnitType2.LINE=1]="LINE",NumberUnitType2[NumberUnitType2.CHARACTER=2]="CHARACTER",NumberUnitType2[NumberUnitType2.PIXEL=3]="PIXEL",NumberUnitType2))(NumberUnitType||{}),AlignTypeH=(AlignTypeH2=>(AlignTypeH2[AlignTypeH2.CENTER=0]="CENTER",AlignTypeH2[AlignTypeH2.INSIDE=1]="INSIDE",AlignTypeH2[AlignTypeH2.LEFT=2]="LEFT",AlignTypeH2[AlignTypeH2.OUTSIDE=3]="OUTSIDE",AlignTypeH2[AlignTypeH2.RIGHT=4]="RIGHT",AlignTypeH2[AlignTypeH2.BOTH=5]="BOTH",AlignTypeH2[AlignTypeH2.DISTRIBUTE=6]="DISTRIBUTE",AlignTypeH2))(AlignTypeH||{}),AlignTypeV=(AlignTypeV2=>(AlignTypeV2[AlignTypeV2.BOTTOM=0]="BOTTOM",AlignTypeV2[AlignTypeV2.CENTER=1]="CENTER",AlignTypeV2[AlignTypeV2.INSIDE=2]="INSIDE",AlignTypeV2[AlignTypeV2.OUTSIDE=3]="OUTSIDE",AlignTypeV2[AlignTypeV2.TOP=4]="TOP",AlignTypeV2))(AlignTypeV||{}),characterSpacingControlType=(characterSpacingControlType2=>(characterSpacingControlType2[characterSpacingControlType2.compressPunctuation=0]="compressPunctuation",characterSpacingControlType2[characterSpacingControlType2.compressPunctuationAndJapaneseKana=1]="compressPunctuationAndJapaneseKana",characterSpacingControlType2[characterSpacingControlType2.doNotCompress=2]="doNotCompress",characterSpacingControlType2))(characterSpacingControlType||{}),PageOrientType=(PageOrientType2=>(PageOrientType2[PageOrientType2.PORTRAIT=0]="PORTRAIT",PageOrientType2[PageOrientType2.LANDSCAPE=1]="LANDSCAPE",PageOrientType2))(PageOrientType||{}),ArrangeTypeEnum=(ArrangeTypeEnum2=>(ArrangeTypeEnum2[ArrangeTypeEnum2.forward=0]="forward",ArrangeTypeEnum2[ArrangeTypeEnum2.backward=1]="backward",ArrangeTypeEnum2[ArrangeTypeEnum2.front=2]="front",ArrangeTypeEnum2[ArrangeTypeEnum2.back=3]="back",ArrangeTypeEnum2))(ArrangeTypeEnum||{}),DrawingTypeEnum=(DrawingTypeEnum2=>(DrawingTypeEnum2[DrawingTypeEnum2.UNRECOGNIZED=-1]="UNRECOGNIZED",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_IMAGE=0]="DRAWING_IMAGE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_SHAPE=1]="DRAWING_SHAPE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_CHART=2]="DRAWING_CHART",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_TABLE=3]="DRAWING_TABLE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_SMART_ART=4]="DRAWING_SMART_ART",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_VIDEO=5]="DRAWING_VIDEO",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_GROUP=6]="DRAWING_GROUP",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_UNIT=7]="DRAWING_UNIT",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_DOM=8]="DRAWING_DOM",DrawingTypeEnum2))(DrawingTypeEnum||{}),RANGE_TYPE=(RANGE_TYPE2=>(RANGE_TYPE2[RANGE_TYPE2.NORMAL=0]="NORMAL",RANGE_TYPE2[RANGE_TYPE2.ROW=1]="ROW",RANGE_TYPE2[RANGE_TYPE2.COLUMN=2]="COLUMN",RANGE_TYPE2[RANGE_TYPE2.ALL=3]="ALL",RANGE_TYPE2))(RANGE_TYPE||{}),AbsoluteRefType=(AbsoluteRefType2=>(AbsoluteRefType2[AbsoluteRefType2.NONE=0]="NONE",AbsoluteRefType2[AbsoluteRefType2.ROW=1]="ROW",AbsoluteRefType2[AbsoluteRefType2.COLUMN=2]="COLUMN",AbsoluteRefType2[AbsoluteRefType2.ALL=3]="ALL",AbsoluteRefType2))(AbsoluteRefType||{});function selectionToArray(range){return[range.startRow,range.startColumn,range.endRow,range.endColumn]}__name(selectionToArray,"selectionToArray");function getCellInfoInMergeData(row,column,mergeData){let isMerged=!1,isMergedMainCell=!1,newEndRow=row,newEndColumn=column,mergeRow=row,mergeColumn=column;if(mergeData==null)return{actualRow:row,actualColumn:column,isMergedMainCell,isMerged,endRow:newEndRow,endColumn:newEndColumn,startRow:mergeRow,startColumn:mergeColumn};for(let i=0;i<mergeData.length;i++){const{startRow:startRowMarge,endRow:endRowMarge,startColumn:startColumnMarge,endColumn:endColumnMarge}=mergeData[i];if(row===startRowMarge&&column===startColumnMarge){newEndRow=endRowMarge,newEndColumn=endColumnMarge,mergeRow=startRowMarge,mergeColumn=startColumnMarge,isMergedMainCell=!0;break}if(row>=startRowMarge&&row<=endRowMarge&&column>=startColumnMarge&&column<=endColumnMarge){newEndRow=endRowMarge,newEndColumn=endColumnMarge,mergeRow=startRowMarge,mergeColumn=startColumnMarge,isMerged=!0;break}}return{actualRow:row,actualColumn:column,isMergedMainCell,isMerged,endRow:newEndRow,endColumn:newEndColumn,startRow:mergeRow,startColumn:mergeColumn}}__name(getCellInfoInMergeData,"getCellInfoInMergeData");var PageType=(PageType2=>(PageType2[PageType2.SLIDE=0]="SLIDE",PageType2[PageType2.MASTER=1]="MASTER",PageType2[PageType2.LAYOUT=2]="LAYOUT",PageType2[PageType2.HANDOUT_MASTER=3]="HANDOUT_MASTER",PageType2[PageType2.NOTES_MASTER=4]="NOTES_MASTER",PageType2))(PageType||{}),PageElementType=(PageElementType2=>(PageElementType2[PageElementType2.SHAPE=0]="SHAPE",PageElementType2[PageElementType2.IMAGE=1]="IMAGE",PageElementType2[PageElementType2.TEXT=2]="TEXT",PageElementType2[PageElementType2.SPREADSHEET=3]="SPREADSHEET",PageElementType2[PageElementType2.DOCUMENT=4]="DOCUMENT",PageElementType2[PageElementType2.SLIDE=5]="SLIDE",PageElementType2))(PageElementType||{}),RelativeSlideLink=(RelativeSlideLink2=>(RelativeSlideLink2[RelativeSlideLink2.RELATIVE_SLIDE_LINK_UNSPECIFIED=0]="RELATIVE_SLIDE_LINK_UNSPECIFIED",RelativeSlideLink2[RelativeSlideLink2.NEXT_SLIDE=1]="NEXT_SLIDE",RelativeSlideLink2[RelativeSlideLink2.PREVIOUS_SLIDE=2]="PREVIOUS_SLIDE",RelativeSlideLink2[RelativeSlideLink2.FIRST_SLIDE=3]="FIRST_SLIDE",RelativeSlideLink2[RelativeSlideLink2.LAST_SLIDE=4]="LAST_SLIDE",RelativeSlideLink2))(RelativeSlideLink||{});const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let random=__name(bytes=>crypto.getRandomValues(new Uint8Array(bytes)),"random"),customRandom=__name((alphabet,defaultSize,getRandom)=>{let mask=(2<<Math.log(alphabet.length-1)/Math.LN2)-1,step=-~(1.6*mask*defaultSize/alphabet.length);return(size=defaultSize)=>{let id="";for(;;){let bytes=getRandom(step),j=step;for(;j--;)if(id+=alphabet[bytes[j]&mask]||"",id.length===size)return id}}},"customRandom"),customAlphabet=__name((alphabet,size=21)=>customRandom(alphabet,size,random),"customAlphabet"),nanoid=__name((size=21)=>{let id="",bytes=crypto.getRandomValues(new Uint8Array(size));for(;size--;)id+=urlAlphabet[bytes[size]&63];return id},"nanoid");const topLevelDomainSet=new Set(["ac","ad","ae","aero","af","ag","ai","al","am","ao","aq","ar","arpa","as","asia","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","biz","bj","bm","bn","bo","br","bs","bt","bv","bw","by","bz","ca","cat","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","com","coop","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","edu","ee","eg","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gov","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","info","int","io","iq","ir","is","it","je","jm","jo","jobs","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mg","mh","mil","mk","ml","mm","mn","mo","mobi","mp","mq","mr","ms","mt","mu","museum","mv","mw","mx","my","mz","na","name","nc","ne","net","nf","ng","ni","nl","no","np","nr","nu","nz","om","onion","org","pa","pe","pf","pg","ph","pk","pl","pm","pn","post","pr","pro","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","su","sv","sx","sy","sz","tc","td","tel","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","uk","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","yt","za","zm","zw"]),re_weburl=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");function isLegalUrl(url){if(!Number.isNaN(+url))return!1;if(url.startsWith("http://localhost:3002")||url.startsWith("localhost:3002"))return!0;if(re_weburl.test(url)){if(hasProtocol(url))return!0;try{const topLevelDomain=new URL(normalizeUrl(url)).hostname.split(".").pop();if(topLevelDomain&&topLevelDomainSet.has(topLevelDomain))return!0}catch{return!1}}return!1}__name(isLegalUrl,"isLegalUrl");function hasProtocol(urlString){return/^[a-zA-Z]+:\/\//.test(urlString)}__name(hasProtocol,"hasProtocol");function isEmail(url){return/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(url)}__name(isEmail,"isEmail");function normalizeUrl(urlStr){return hasProtocol(urlStr)?urlStr:isEmail(urlStr)?`mailto://${urlStr}`:`https://${urlStr}`}__name(normalizeUrl,"normalizeUrl");const rmsPrefix=/^-ms-/,rDashAlpha=/-([a-z])/g,alphabets=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],_Tools=class _Tools{static stringAt(index2){let str="",idx=index2;for(;idx>=alphabets.length;)idx/=alphabets.length,idx-=1,str+=alphabets[idx%alphabets.length];const last=index2%alphabets.length;return str+=alphabets[last],str}static indexAt(code){let ret=0;for(let i=0;i<code.length-1;i+=1){const idx=code.charCodeAt(i)-65,expoNet=code.length-1-i;ret+=alphabets.length**expoNet+alphabets.length*idx}return ret+=code.charCodeAt(code.length-1)-65,ret}static deleteBlank(value){return _Tools.isString(value)?value.replace(/\s/g,""):value}static getSystemType(){const sUserAgent=navigator.userAgent,isWin=navigator.platform==="Win32"||navigator.platform==="Windows",isMac=navigator.platform==="Mac68K"||navigator.platform==="MacPPC"||navigator.platform==="Macintosh"||navigator.platform==="MacIntel";if(isMac)return"Mac";if(navigator.platform==="X11"&&!isWin&&!isMac)return"Unix";if(String(navigator.platform).indexOf("Linux")>-1)return"Linux";if(isWin){if(sUserAgent.indexOf("Windows NT 5.0")>-1||sUserAgent.indexOf("Windows 2000")>-1)return"Windows 2000";if(sUserAgent.indexOf("Windows NT 5.1")>-1||sUserAgent.indexOf("Windows XP")>-1)return"Windows XP";if(sUserAgent.indexOf("Windows NT 5.2")>-1||sUserAgent.indexOf("Windows 2003")>-1)return"Windows 2003";if(sUserAgent.indexOf("Windows NT 6.0")>-1||sUserAgent.indexOf("Windows Vista")>-1)return"Windows Vista";if(sUserAgent.indexOf("Windows NT 6.1")>-1||sUserAgent.indexOf("Windows 7")>-1)return"Windows 7";if(sUserAgent.indexOf("Windows NT 10")>-1||sUserAgent.indexOf("Windows 10")>-1)return"Windows 10";if(sUserAgent.indexOf("Windows NT 11")>-1||sUserAgent.indexOf("Windows 11")>-1)return"Windows 11"}return"Unknown system"}static getBrowserType(){const userAgent=navigator.userAgent,isOpera=userAgent.indexOf("Opera")>-1,isIE=userAgent.indexOf("compatible")>-1&&userAgent.indexOf("MSIE")>-1&&!isOpera,isIE11=userAgent.indexOf("Trident")>-1&&userAgent.indexOf("rv:11.0")>-1,isEdge=userAgent.indexOf("Edge")>-1,isFF=userAgent.indexOf("Firefox")>-1,isSafari=userAgent.indexOf("Safari")>-1&&userAgent.indexOf("Chrome")===-1,isChrome=userAgent.indexOf("Chrome")>-1&&userAgent.indexOf("Safari")>-1;if(isIE){new RegExp("MSIE (\\d+\\.\\d+);").test(userAgent);const fIEVersion=Number.parseFloat(RegExp.$1);return fIEVersion===7?"IE7":fIEVersion===8?"IE8":fIEVersion===9?"IE9":fIEVersion===10?"IE10":"0"}return isFF?"FF":isOpera?"Opera":isSafari?"Safari":isChrome?"Chrome":isEdge?"Edge":isIE11?"IE11":"Unknown browser"}static generateRandomId(n=21,alphabet){return generateRandomId(n,alphabet)}static getClassName(instance){return instance.constructor.name}static deepMerge(target,...sources){sources.forEach(item=>item&&deepItem(item));function deepArray(array,to){array.forEach((value,key)=>{var _a13,_b2;if(_Tools.isArray(value)){const origin=(_a13=to[key])!=null?_a13:[];to[key]=origin,deepArray(value,origin);return}if(_Tools.isObject(value)){const origin=(_b2=to[key])!=null?_b2:{};to[key]=origin,deepObject(value,origin);return}to[key]=value})}__name(deepArray,"deepArray");function deepObject(object,to){Object.keys(object).forEach(key=>{var _a13,_b2;const value=object[key];if(_Tools.isObject(value)){const origin=(_a13=to[key])!=null?_a13:{};to[key]=origin,deepObject(value,origin);return}if(_Tools.isArray(value)){const origin=(_b2=to[key])!=null?_b2:[];to[key]=origin,deepArray(value,origin);return}to[key]=value})}__name(deepObject,"deepObject");function deepItem(item){Object.keys(item).forEach(key=>{var _a13,_b2;const value=item[key];if(_Tools.isArray(value)){const origin=(_a13=target[key])!=null?_a13:[];target[key]=origin,deepArray(value,origin);return}if(_Tools.isObject(value)){const origin=(_b2=target[key])!=null?_b2:{};target[key]=origin,deepObject(value,origin);return}target[key]=value})}return __name(deepItem,"deepItem"),target}static numberFixed(value,digit){return Number(Number(value).toFixed(digit))}static diffValue(one,tow){function diffValue(oneValue,towValue){const oneType=_Tools.getValueType(oneValue),towType=_Tools.getValueType(towValue);return oneType!==towType?!1:_Tools.isArray(oneValue)?diffArrays(oneValue,towValue):_Tools.isObject(oneValue)?diffObject(oneValue,towValue):_Tools.isDate(oneValue)?oneValue.getTime()===towValue.getTime():_Tools.isRegExp(oneValue)?oneValue.toString()===towValue.toString():oneValue===towValue}__name(diffValue,"diffValue");function diffArrays(oneArray,towArray){if(one.length!==tow.length)return!1;for(let i=0,len=oneArray.length;i<len;i++){const oneValue=oneArray[i],towValue=towArray[i];if(!diffValue(oneValue,towValue))return!1}return!0}__name(diffArrays,"diffArrays");function diffObject(oneObject,towObject){const oneKeys=Object.keys(oneObject),towKeys=Object.keys(towObject);if(oneKeys.length!==towKeys.length)return!1;for(const key of oneKeys){if(!towKeys.includes(key))return!1;const oneValue=oneObject[key],towValue=towObject[key];if(!diffValue(oneValue,towValue))return!1}return!0}return __name(diffObject,"diffObject"),diffValue(one,tow)}static deepClone(value){if(!this.isDefine(value))return value;if(this.isRegExp(value))return new RegExp(value);if(this.isDate(value))return new Date(value);if(this.isArray(value)){const clone=[];return value.forEach((item,index2)=>{clone[index2]=_Tools.deepClone(item)}),clone}if(this.isObject(value)){const clone={};return Object.keys(value).forEach(key=>{const item=value[key];clone[key]=_Tools.deepClone(item)}),Object.setPrototypeOf(clone,Object.getPrototypeOf(value)),clone}return value}static getLanguage(){const defaultValue="en-US";return globalThis.navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||defaultValue}static getValueType(value){return Object.prototype.toString.apply(value)}static isDefine(value){return value!=null}static isBlank(value){return this.isDefine(value)?this.isString(value)?value.trim()==="":!1:!0}static isAssignableFrom(object,clazz){return object instanceof clazz}static isBoolean(value){return this.getValueType(value)==="[object Boolean]"}static isPlainObject(value){return this.isDefine(value)?Object.getPrototypeOf(value)===Object.getPrototypeOf({}):!1}static isFunction(value){return this.getValueType(value)==="[object Function]"}static isDate(value){return this.getValueType(value)==="[object Date]"}static isRegExp(value){return this.getValueType(value)==="[object RegExp]"}static isArray(value){return this.getValueType(value)==="[object Array]"}static isString(value){return this.getValueType(value)==="[object String]"}static isNumber(value){return this.getValueType(value)==="[object Number]"}static isStringNumber(value){return!isNaN(Number.parseFloat(value))&&isFinite(value)}static isObject(value){return this.getValueType(value)==="[object Object]"}static isEmptyObject(value){for(const _key in value)return!1;return!0}static isMobile(){let clientWidth=0,clientHeight=0;return document.body.clientWidth&&(clientWidth=document.body.clientWidth),document.body.clientHeight&&(clientHeight=document.body.clientHeight),this.isAndroid()||this.isIPhone()||this.isTablet()||clientWidth<350&&clientHeight<500}static isTablet(){return/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase())}static isWeChat(){const userAgent=navigator.userAgent.toLowerCase();return String(userAgent.match(/MicroMessenger/i))==="micromessenger"}static isAndroid(){const userAgent=navigator.userAgent;return userAgent.indexOf("Android")>-1||userAgent.indexOf("Linux")>-1}static isIPhone(){return/iPhone/i.test(navigator.userAgent)}static isLegalUrl(url){return isLegalUrl(url)}static normalizeUrl(url){return normalizeUrl(url)}static itCount(count){return callback=>{for(let i=0;i<count;i++)callback&&callback()}}static hasLength(target,length){return _Tools.isDefine(target)?_Tools.isDefine(length)?target.length===length:target.length>0:!1}static capitalize(str){return str.charAt(0).toUpperCase()+str.slice(1)}static fCamelCase(_all,letter){return letter.toUpperCase()}static camelCase(str){return str.replace(rmsPrefix,"ms-").replace(rDashAlpha,this.fCamelCase)}static removeNull(value){return this.isObject(value)&&Object.keys(value).forEach(key=>{const item=value[key];item==null?delete value[key]:_Tools.removeNull(item)}),value}static fillTwoDimensionalArray(rows,columns,value){return new Array(rows).fill(value).map(item=>new Array(columns).fill(value))}static numToWord(x){let s="";for(;x>0;){let m=x%26;m=m===0?m=26:m,s=String.fromCharCode(96+m)+s,x=(x-m)/26}return s.toLocaleUpperCase()}static ABCatNum(a){if(a==null||a.length===0)return Number.NaN;const str=a.toLowerCase().split(""),al=str.length;let numOut=0,charnum=0;for(let i=0;i<al;i++)charnum=str[i].charCodeAt(0)-96,numOut+=charnum*26**(al-i-1);return numOut===0?Number.NaN:numOut-1}static chatAtABC(n){let s="";for(;n>=0;)s=String.fromCharCode(n%26+97)+s,n=Math.floor(n/26)-1;return s.toUpperCase()}static randSort(arr){for(let i=0,len=arr.length;i<len;i++){const rand=Number.parseInt((Math.random()*len).toString()),temp=arr[rand];arr[rand]=arr[i],arr[i]=temp}return arr}static commonExtend(originJson,extendJson){const resultJsonObject={};for(const attr in originJson)resultJsonObject[attr]=originJson[attr];for(const attr in extendJson)extendJson[attr]!=null&&(resultJsonObject[attr]=extendJson[attr]);return resultJsonObject}static commonExtend1(originJson,extendJson){for(const attr in originJson)extendJson[attr]==null&&(extendJson[attr]=originJson[attr]);return extendJson}static arrayToObject(array){const obj={};return array.forEach((row,i)=>{obj[i]={},row.forEach((column,j)=>{obj[i][j]=column})}),obj}static hasIntersectionBetweenTwoRanges(range1Start,range1End,range2Start,range2End){return range1End>=range2Start&&range2End>=range1Start}static isStartValidPosition(name){return/^[A-Za-z_]/.test(name)}static isValidParameter(name){const containsInvalidChars=/[~!@#$%^&*()+=\-{}\[\]\|:;"'<>,?\/ ]+/.test(name),isValidLength=name.length<=255;return!containsInvalidChars&&isValidLength}static set(data,propertyPath,value){const paths=propertyPath.split("."),key=paths.pop();paths.forEach(prop=>{data[prop]||(data[prop]={}),data=data[prop]}),key&&(data[key]=value)}static clamp(value,min,max){return Math.max(min,Math.min(max,value))}};__name(_Tools,"Tools");let Tools=_Tools;function generateRandomId(n=21,alphabet){return alphabet?customAlphabet(alphabet,n)():nanoid(n)}__name(generateRandomId,"generateRandomId");function makeCellToSelection(cellInfo){const{actualRow,actualColumn,isMerged,isMergedMainCell,mergeInfo}=cellInfo;let{startY,endY,startX,endX}=cellInfo,startRow=actualRow,startColumn=actualColumn,endRow=actualRow,endColumn=actualColumn;if(isMerged&&mergeInfo){const{startRow:mergeStartRow,startColumn:mergeStartColumn,endRow:mergeEndRow,endColumn:mergeEndColumn,startY:mergeStartY,endY:mergeEndY,startX:mergeStartX,endX:mergeEndX}=mergeInfo;startRow=mergeStartRow,startColumn=mergeStartColumn,endRow=mergeEndRow,endColumn=mergeEndColumn,startY=mergeStartY,endY=mergeEndY,startX=mergeStartX,endX=mergeEndX}return isMergedMainCell&&(startY=mergeInfo.startY,endY=mergeInfo.endY,startX=mergeInfo.startX,endX=mergeInfo.endX,endRow=mergeInfo.endRow,endColumn=mergeInfo.endColumn),{startRow,startColumn,endRow,endColumn,startY,endY,startX,endX}}__name(makeCellToSelection,"makeCellToSelection");function makeCellRangeToRangeData(cellInfo){if(!cellInfo)return;const{actualRow,actualColumn,isMerged,isMergedMainCell,startRow:mergeStartRow,startColumn:mergeStartColumn,endRow:mergeEndRow,endColumn:mergeEndColumn}=cellInfo;let startRow=actualRow,startColumn=actualColumn,endRow=actualRow,endColumn=actualColumn;return(isMerged||isMergedMainCell)&&(startRow=mergeStartRow,startColumn=mergeStartColumn,endRow=mergeEndRow,endColumn=mergeEndColumn),{startRow,startColumn,endRow,endColumn}}__name(makeCellRangeToRangeData,"makeCellRangeToRangeData");function isEmptyCell(cell){var _a13;return!cell||(((_a13=cell==null?void 0:cell.v)==null?void 0:_a13.toString())||"").length===0&&!cell.p}__name(isEmptyCell,"isEmptyCell");function isCellCoverable(cell){return isEmptyCell(cell)&&(cell==null?void 0:cell.coverable)!==!1}__name(isCellCoverable,"isCellCoverable");function getColorStyle(color){if(color){if(color.rgb)return color.rgb;if(color.th)return new ColorBuilder().setThemeColor(color.th).asThemeColor().asRgbColor().getCssString()}return null}__name(getColorStyle,"getColorStyle");function isFormulaString(value){return Tools.isString(value)&&value.substring(0,1)==="="&&value.length>1}__name(isFormulaString,"isFormulaString");function isFormulaId(value){return Tools.isString(value)&&value.length>0}__name(isFormulaId,"isFormulaId");function handleStyleToString(style,isCell=!1){var _a13;let str="";const styleMap=new Map([["ff",()=>{style.ff&&(str+=`font-family: ${style.ff}; `)}],["fs",()=>{if(style.fs){let fs=style.fs;style.va&&(fs/=2),str+=`font-size: ${fs}pt; `}}],["it",()=>{style.it&&(str+="font-style: italic; ")}],["bl",()=>{style.bl&&(str+="font-weight: bold; ")}],["ul",()=>{var _a14;(_a14=style.ul)!=null&&_a14.s&&(str.indexOf("text-decoration-line")>-1?str=str.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(_,p1)=>`${p1} underline`):str+="text-decoration: underline; ",style.ul.cl&&str.indexOf("text-decoration-color")===-1&&(str+=`text-decoration-color: ${getColorStyle(style.ul.cl)}; `),style.ul.t&&str.indexOf("text-decoration-style")===-1&&(str+=`text-decoration-style: ${style.ul.t} `))}],["st",()=>{var _a14;(_a14=style.st)!=null&&_a14.s&&(str.indexOf("text-decoration-line")>-1?str=str.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(_,p1)=>`${p1} line-through`):str+="text-decoration-line: line-through; ",style.st.cl&&str.indexOf("text-decoration-color")===-1&&(str+=`text-decoration-color: ${getColorStyle(style.st.cl)}; `),style.st.t&&str.indexOf("text-decoration-style")===-1&&(str+=`text-decoration-style: ${style.st.t} `))}],["ol",()=>{var _a14;(_a14=style.ol)!=null&&_a14.s&&(str.indexOf("text-decoration-line")>-1?str=str.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g,(_,p1)=>`${p1} overline`):str+="text-decoration-line: overline; ",style.ol.cl&&str.indexOf("text-decoration-color")===-1&&(str+=`text-decoration-color: ${getColorStyle(style.ol.cl)}; `),style.ol.t&&str.indexOf("text-decoration-style")===-1&&(str+=`text-decoration-style: ${style.ol.t} `))}],["bg",()=>{style.bg&&(str+=`background: ${getColorStyle(style.bg)}; `)}],["bd",()=>{var _a14,_b2,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l;(_a14=style.bd)!=null&&_a14.b&&(str+=`border-bottom: ${getBorderStyle((_b2=style.bd)==null?void 0:_b2.b.s)} ${(_c=getColorStyle(style.bd.b.cl))!=null?_c:""}; `),(_d=style.bd)!=null&&_d.t&&(str+=`border-top: ${getBorderStyle((_e=style.bd)==null?void 0:_e.t.s)} ${(_f=getColorStyle(style.bd.t.cl))!=null?_f:""}; `),(_g=style.bd)!=null&&_g.r&&(str+=`border-right: ${getBorderStyle((_h=style.bd)==null?void 0:_h.r.s)} ${(_i=getColorStyle(style.bd.r.cl))!=null?_i:""}; `),(_j=style.bd)!=null&&_j.l&&(str+=`border-left: ${getBorderStyle((_k=style.bd)==null?void 0:_k.l.s)} ${(_l=getColorStyle(style.bd.l.cl))!=null?_l:""}; `)}],["cl",()=>{style.cl&&(str+=`color: ${getColorStyle(style.cl)}; `)}],["va",()=>{style.va===BaselineOffset.SUBSCRIPT?str+="vertical-align: sub; ":style.va===BaselineOffset.SUPERSCRIPT&&(str+="vertical-align: super; ")}],["td",()=>{style.td===TextDirection.LEFT_TO_RIGHT?str+="direction: ltr; ":style.td===TextDirection.RIGHT_TO_LEFT&&(str+="direction: rtl; ")}],["tr",()=>{var _a14,_b2,_c;style.tr&&(str+=`--data-rotate: (${(_a14=style.tr)==null?void 0:_a14.a}deg${(_b2=style.tr)!=null&&_b2.v?` ,${(_c=style.tr)==null?void 0:_c.v}`:""});`)}],["ht",()=>{style.ht===HorizontalAlign.LEFT?str+="text-align: left; ":style.ht===HorizontalAlign.RIGHT?str+="text-align: right; ":style.ht===HorizontalAlign.CENTER?str+="text-align: center; ":style.ht===HorizontalAlign.JUSTIFIED&&(str+="text-align: justify; ")}],["vt",()=>{style.vt===VerticalAlign.BOTTOM?str+="vertical-align: bottom; ":style.vt===VerticalAlign.TOP?str+="vertical-align: top; ":style.vt===VerticalAlign.MIDDLE&&(str+="vertical-align: middle; ")}],["tb",()=>{style.tb===WrapStrategy.CLIP?str+="white-space: nowrap; overflow-x: hidden; ":style.tb===WrapStrategy.WRAP&&(str+="white-space: normal;")}],["pd",()=>{var _a14,_b2,_c,_d,_e,_f,_g,_h;const b=`${(_a14=style.pd)==null?void 0:_a14.b}pt`,t=`${(_b2=style.pd)==null?void 0:_b2.t}pt`,l2=`${(_c=style.pd)==null?void 0:_c.l}pt`,r=`${(_d=style.pd)==null?void 0:_d.r}pt`;(_e=style.pd)!=null&&_e.b&&(str+=`padding-bottom: ${b}; `),(_f=style.pd)!=null&&_f.t&&(str+=`padding-top: ${t}; `),(_g=style.pd)!=null&&_g.l&&(str+=`padding-left: ${l2}; `),(_h=style.pd)!=null&&_h.r&&(str+=`padding-right: ${r}; `)}]]),cellSkip=["bd","tr","tb"];for(const k in style)isCell&&cellSkip.includes(k)||(_a13=styleMap.get(k))==null||_a13();return str}__name(handleStyleToString,"handleStyleToString");function getBorderStyle(type2){let str="";return type2===BorderStyleTypes.NONE?str="none":type2===BorderStyleTypes.THIN?str="0.5pt solid":type2===BorderStyleTypes.HAIR?str="0.5pt double":type2===BorderStyleTypes.DOTTED?str="0.5pt dotted":type2===BorderStyleTypes.DASHED||type2===BorderStyleTypes.DASH_DOT?str="0.5pt dashed":type2===BorderStyleTypes.DASH_DOT_DOT?str="0.5pt dotted":type2===BorderStyleTypes.DOUBLE?str="0.5pt double":type2===BorderStyleTypes.MEDIUM?str="1pt solid":type2===BorderStyleTypes.MEDIUM_DASHED||type2===BorderStyleTypes.MEDIUM_DASH_DOT?str="1pt dashed":type2===BorderStyleTypes.MEDIUM_DASH_DOT_DOT?str="1pt dotted":type2===BorderStyleTypes.SLANT_DASH_DOT?str="0.5pt dashed":type2===BorderStyleTypes.THICK&&(str="1.5pt solid"),str}__name(getBorderStyle,"getBorderStyle");function getBorderStyleType(type2){let str=0;if(type2=type2.trim(),type2==="none")str=BorderStyleTypes.NONE;else if(type2==="0.5pt solid")str=BorderStyleTypes.THIN;else if(type2==="0.5pt double")str=BorderStyleTypes.HAIR;else if(type2==="0.5pt dotted")str=BorderStyleTypes.DOTTED;else if(type2==="0.5pt dashed")str=BorderStyleTypes.DASHED;else if(type2==="1pt solid")str=BorderStyleTypes.MEDIUM;else if(type2==="1pt dashed")str=BorderStyleTypes.MEDIUM_DASHED;else if(type2==="1pt dotted")str=BorderStyleTypes.MEDIUM_DASH_DOT_DOT;else if(type2==="1.5pt solid")str=BorderStyleTypes.THICK;else if(!type2.includes("none"))str=BorderStyleTypes.THIN;else return BorderStyleTypes.NONE;return str}__name(getBorderStyleType,"getBorderStyleType");function getDocsUpdateBody(model,segmentId){let body=model.body;if(segmentId){const{headers,footers}=model;headers!=null&&headers[segmentId]?body=headers[segmentId].body:footers!=null&&footers[segmentId]&&(body=footers[segmentId].body)}return body}__name(getDocsUpdateBody,"getDocsUpdateBody");function isValidRange(range){const{startRow,endRow,startColumn,endColumn,rangeType}=range;return!(startRow<0||startColumn<0||endRow<0||endColumn<0||!(Number.isNaN(startRow)&&Number.isNaN(endRow))&&rangeType===RANGE_TYPE.COLUMN||!(Number.isNaN(startColumn)&&Number.isNaN(endColumn))&&rangeType===RANGE_TYPE.ROW||rangeType!==RANGE_TYPE.ROW&&rangeType!==RANGE_TYPE.COLUMN&&(Number.isNaN(startColumn)||Number.isNaN(startRow)||Number.isNaN(endColumn)||Number.isNaN(endRow)))}__name(isValidRange,"isValidRange");function cellToRange(row,col){return{startRow:row,endRow:row,startColumn:col,endColumn:col}}__name(cellToRange,"cellToRange");function deepCompare(arg1,arg2){return Object.prototype.toString.call(arg1)===Object.prototype.toString.call(arg2)?Object.prototype.toString.call(arg1)==="[object Object]"||Object.prototype.toString.call(arg1)==="[object Array]"?Object.keys(arg1).length!==Object.keys(arg2).length?!1:Object.keys(arg1).every(key=>deepCompare(arg1[key],arg2[key])):arg1===arg2:!1}__name(deepCompare,"deepCompare");function isSameStyleTextRun(tr1,tr2){const ts1=tr1.ts||{},ts2=tr2.ts||{};return tr1.sId!==tr2.sId?!1:deepCompare(ts1,ts2)}__name(isSameStyleTextRun,"isSameStyleTextRun");function checkForSubstrings(searchString,substrings){return substrings.some(substring=>searchString.indexOf(substring)>-1)}__name(checkForSubstrings,"checkForSubstrings");function horizontalLineSegmentsSubtraction(A1,A2,B1,B2){if(A1>A2&&([A1,A2]=[A2,A1]),B1>B2&&([B1,B2]=[B2,B1]),A2<B1||B2<A1)return[A1,A2];B1<A1&&(B1=A1),B2>A2&&(B2=A2);const subLength=B2-B1+1;let result=[];return A1===B1?result=[B2+1-subLength,A2-subLength]:A2===B2?result=[A1,B1-1]:result=[A1,A2-subLength],result}__name(horizontalLineSegmentsSubtraction,"horizontalLineSegmentsSubtraction");function checkParagraphHasBullet(paragraph){if(paragraph==null)return!1;const bullet=paragraph.bullet;return(bullet==null?void 0:bullet.listId)!=null}__name(checkParagraphHasBullet,"checkParagraphHasBullet");function checkParagraphHasIndent(paragraph){if(paragraph==null)return!1;const paragraphStyle=paragraph.paragraphStyle;return checkParagraphHasIndentByStyle(paragraphStyle)}__name(checkParagraphHasIndent,"checkParagraphHasIndent");function checkParagraphHasIndentByStyle(paragraphStyle){var _a13;return!(paragraphStyle==null||(paragraphStyle.indentStart==null||paragraphStyle.indentStart.v===0)&&paragraphStyle.hanging==null||((_a13=paragraphStyle.hanging)==null?void 0:_a13.v)===0)}__name(checkParagraphHasIndentByStyle,"checkParagraphHasIndentByStyle");function insertTextToContent(content,start,text){return content.slice(0,start)+text+content.slice(start)}__name(insertTextToContent,"insertTextToContent");function deleteContent(content,start,end){return start>end?content:content.slice(0,start)+content.slice(end)}__name(deleteContent,"deleteContent");function isRealNum(val){return val===null||val.toString().replace(/\s/g,"")===""||typeof val=="boolean"?!1:!isNaN(val)}__name(isRealNum,"isRealNum");function hashAlgorithm(str){let hash=0;for(let i=0;i<str.length;i++)hash=str.charCodeAt(i)+(hash<<6)+(hash<<16)-hash;return hash>>>0}__name(hashAlgorithm,"hashAlgorithm");function __values(o){var s=typeof Symbol=="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:__name(function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}},"next")};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}__name(__values,"__values");function __read(o,n){var m=typeof Symbol=="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{for(;(n===void 0||n-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}__name(__read,"__read");function __spreadArray$2(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i<l2;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))}__name(__spreadArray$2,"__spreadArray$2");function isFunction(value){return typeof value=="function"}__name(isFunction,"isFunction");function createErrorClass(createImpl){var _super=__name(function(instance){Error.call(instance),instance.stack=new Error().stack},"_super"),ctorFunc=createImpl(_super);return ctorFunc.prototype=Object.create(Error.prototype),ctorFunc.prototype.constructor=ctorFunc,ctorFunc}__name(createErrorClass,"createErrorClass");var UnsubscriptionError=createErrorClass(function(_super){return __name(function(errors){_super(this),this.message=errors?errors.length+` errors occurred during unsubscription:
2
+ `+errors.map(function(err,i){return i+1+") "+err.toString()}).join(`
3
+ `):"",this.name="UnsubscriptionError",this.errors=errors},"UnsubscriptionErrorImpl")});function arrRemove(arr,item){if(arr){var index2=arr.indexOf(item);0<=index2&&arr.splice(index2,1)}}__name(arrRemove,"arrRemove");var Subscription=function(){function Subscription2(initialTeardown){this.initialTeardown=initialTeardown,this.closed=!1,this._parentage=null,this._finalizers=null}return __name(Subscription2,"Subscription"),Subscription2.prototype.unsubscribe=function(){var e_1,_a13,e_2,_b2,errors;if(!this.closed){this.closed=!0;var _parentage=this._parentage;if(_parentage)if(this._parentage=null,Array.isArray(_parentage))try{for(var _parentage_1=__values(_parentage),_parentage_1_1=_parentage_1.next();!_parentage_1_1.done;_parentage_1_1=_parentage_1.next()){var parent_1=_parentage_1_1.value;parent_1.remove(this)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_parentage_1_1&&!_parentage_1_1.done&&(_a13=_parentage_1.return)&&_a13.call(_parentage_1)}finally{if(e_1)throw e_1.error}}else _parentage.remove(this);var initialFinalizer=this.initialTeardown;if(isFunction(initialFinalizer))try{initialFinalizer()}catch(e){errors=e instanceof UnsubscriptionError?e.errors:[e]}var _finalizers=this._finalizers;if(_finalizers){this._finalizers=null;try{for(var _finalizers_1=__values(_finalizers),_finalizers_1_1=_finalizers_1.next();!_finalizers_1_1.done;_finalizers_1_1=_finalizers_1.next()){var finalizer=_finalizers_1_1.value;try{execFinalizer(finalizer)}catch(err){errors=errors!=null?errors:[],err instanceof UnsubscriptionError?errors=__spreadArray$2(__spreadArray$2([],__read(errors)),__read(err.errors)):errors.push(err)}}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_finalizers_1_1&&!_finalizers_1_1.done&&(_b2=_finalizers_1.return)&&_b2.call(_finalizers_1)}finally{if(e_2)throw e_2.error}}}if(errors)throw new UnsubscriptionError(errors)}},Subscription2.prototype.add=function(teardown){var _a13;if(teardown&&teardown!==this)if(this.closed)execFinalizer(teardown);else{if(teardown instanceof Subscription2){if(teardown.closed||teardown._hasParent(this))return;teardown._addParent(this)}(this._finalizers=(_a13=this._finalizers)!==null&&_a13!==void 0?_a13:[]).push(teardown)}},Subscription2.prototype._hasParent=function(parent){var _parentage=this._parentage;return _parentage===parent||Array.isArray(_parentage)&&_parentage.includes(parent)},Subscription2.prototype._addParent=function(parent){var _parentage=this._parentage;this._parentage=Array.isArray(_parentage)?(_parentage.push(parent),_parentage):_parentage?[_parentage,parent]:parent},Subscription2.prototype._removeParent=function(parent){var _parentage=this._parentage;_parentage===parent?this._parentage=null:Array.isArray(_parentage)&&arrRemove(_parentage,parent)},Subscription2.prototype.remove=function(teardown){var _finalizers=this._finalizers;_finalizers&&arrRemove(_finalizers,teardown),teardown instanceof Subscription2&&teardown._removeParent(this)},Subscription2.EMPTY=function(){var empty=new Subscription2;return empty.closed=!0,empty}(),Subscription2}();Subscription.EMPTY;function isSubscription(value){return value instanceof Subscription||value&&"closed"in value&&isFunction(value.remove)&&isFunction(value.add)&&isFunction(value.unsubscribe)}__name(isSubscription,"isSubscription");function execFinalizer(finalizer){isFunction(finalizer)?finalizer():finalizer.unsubscribe()}__name(execFinalizer,"execFinalizer");function toDisposable(v){let disposed=!1;return v?isSubscription(v)?{dispose:__name(()=>v.unsubscribe(),"dispose")}:typeof v=="function"?{dispose:__name(()=>{disposed||(disposed=!0,v())},"dispose")}:v:toDisposable(()=>{})}__name(toDisposable,"toDisposable");function fromObservable(subscription){return toDisposable(()=>{subscription.unsubscribe()})}__name(fromObservable,"fromObservable");const _DisposableCollection=class _DisposableCollection{constructor(){__publicField(this,"_disposables",new Set)}add(disposable){const d=toDisposable(disposable);return this._disposables.add(d),{dispose:__name(()=>{d.dispose(),this._disposables.delete(d)},"dispose")}}dispose(){this._disposables.forEach(item=>{item.dispose()}),this._disposables.clear()}};__name(_DisposableCollection,"DisposableCollection");let DisposableCollection=_DisposableCollection;const _Disposable=class _Disposable{constructor(){__publicField(this,"_disposed",!1);__publicField(this,"_collection",new DisposableCollection)}disposeWithMe(disposable){return this._collection.add(disposable)}ensureNotDisposed(){if(this._disposed)throw new Error("[Disposable]: object is disposed!")}dispose(){this._disposed||(this._disposed=!0,this._collection.dispose())}};__name(_Disposable,"Disposable");let Disposable=_Disposable;const _RxDisposable=class _RxDisposable extends Disposable{constructor(){super(...arguments);__publicField(this,"dispose$",new rxjs.Subject)}dispose(){super.dispose(),this.dispose$.next(),this.dispose$.complete()}};__name(_RxDisposable,"RxDisposable");let RxDisposable=_RxDisposable;const _RCDisposable=class _RCDisposable extends Disposable{constructor(_rootDisposable){super();__publicField(this,"_ref",0);this._rootDisposable=_rootDisposable}inc(){if(this._disposed)throw new Error("[RCDisposable]: should not ref to a disposed.");this._ref+=1}dec(){this._ref-=1,this._ref===0&&(this._rootDisposable.dispose(),this.dispose())}};__name(_RCDisposable,"RCDisposable");let RCDisposable=_RCDisposable;const _LRUHelper=class _LRUHelper{static hasLength(array,size){return array.length===size}static getValueType(value){return Object.prototype.toString.apply(value)}static isObject(value){return this.getValueType(value)==="[object Object]"}static isIterable(value){return value[Symbol.iterator]!=null}static isNumber(value){return this.getValueType(value)==="[object Number]"}};__name(_LRUHelper,"LRUHelper");let LRUHelper=_LRUHelper;function remove(arr,item){const index2=arr.indexOf(item);return index2>-1?(arr.splice(index2,1),!0):!1}__name(remove,"remove");function dedupe(arr){const deduplicated=new Set,result=[];for(const element of arr)deduplicated.has(element)||(deduplicated.add(element),result.push(element));return result}__name(dedupe,"dedupe");function findLast(arr,callback){for(let i=arr.length-1;i>-1;i--){const item=arr[i];if(callback(item,i))return item}return null}__name(findLast,"findLast");function rotate(arr,steps){if(arr.length===0)return arr;const offset=steps%arr.length;return arr.slice(offset).concat(arr.slice(0,offset))}__name(rotate,"rotate");function groupBy(arr,keyFn){const groups=new Map;return arr.forEach(element=>{const key=keyFn(element);let group=groups.get(key);groups.has(key)||(group=[],groups.set(key,group)),group.push(element)}),groups}__name(groupBy,"groupBy");function makeArray(thing){return Array.isArray(thing)?thing:[thing]}__name(makeArray,"makeArray");const NEWER=Symbol("newer"),OLDER=Symbol("older"),_KeyIterator=class _KeyIterator{constructor(oldestEntry){__publicField(this,"entry");this.entry=oldestEntry}[Symbol.iterator](){return this}next(){const ent=this.entry;return ent?(this.entry=ent[NEWER],{done:!1,value:ent.key}):{done:!0,value:void 0}}};__name(_KeyIterator,"KeyIterator");let KeyIterator=_KeyIterator;const _ValueIterator=class _ValueIterator{constructor(oldestEntry){__publicField(this,"entry");this.entry=oldestEntry}[Symbol.iterator](){return this}next(){const ent=this.entry;return ent?(this.entry=ent[NEWER],{done:!1,value:ent.value}):{done:!0,value:void 0}}};__name(_ValueIterator,"ValueIterator");let ValueIterator=_ValueIterator;const _EntryIterator=class _EntryIterator{constructor(oldestEntry){__publicField(this,"entry");this.entry=oldestEntry}[Symbol.iterator](){return this}next(){const ent=this.entry;return ent?(this.entry=ent[NEWER],{done:!1,value:[ent.key,ent.value]}):{done:!0,value:void 0}}};__name(_EntryIterator,"EntryIterator");let EntryIterator=_EntryIterator;var _a,_b;_b=NEWER,_a=OLDER;const _Entry=class _Entry{constructor(key,value){__publicField(this,"key");__publicField(this,"value");__publicField(this,_b);__publicField(this,_a);this.key=key,this.value=value,this[NEWER]=void 0,this[OLDER]=void 0}toJSON(){return{key:this.key,value:this.value}}};__name(_Entry,"Entry");let Entry=_Entry;const _LRUMap=class _LRUMap{constructor(...parameter){__publicField(this,"_keymap");__publicField(this,"size",0);__publicField(this,"limit");__publicField(this,"oldest");__publicField(this,"newest");__publicField(this,"_onShiftListeners",[]);if(LRUHelper.hasLength(parameter,1)){if(LRUHelper.isNumber(parameter[0])){const limit=parameter[0];this._initialize(limit,void 0);return}if(LRUHelper.isIterable(parameter[0])){const entries=parameter[0];this._initialize(0,entries);return}return}if(LRUHelper.hasLength(parameter,2)){const limit=parameter[0],entries=parameter[1];this._initialize(limit,entries)}}onShift(callback){if(this._onShiftListeners.indexOf(callback)===-1)return this._onShiftListeners.push(callback),toDisposable(()=>remove(this._onShiftListeners,callback));throw new Error("[LRUMap]: the listener has been registered!")}_initialize(limit,entries){this.oldest=void 0,this.newest=void 0,this.size=0,this.limit=limit,this._keymap=new Map,entries&&(this.assign(entries),limit<1&&(this.limit=this.size))}_markEntryAsUsed(entry){entry!==this.newest&&(entry[NEWER]&&(entry===this.oldest&&(this.oldest=entry[NEWER]),entry[NEWER][OLDER]=entry[OLDER]),entry[OLDER]&&(entry[OLDER][NEWER]=entry[NEWER]),entry[NEWER]=void 0,entry[OLDER]=this.newest,this.newest&&(this.newest[NEWER]=entry),this.newest=entry)}assign(entries){let entry,limit=this.limit||Number.MAX_VALUE;this._keymap.clear();const it=entries[Symbol.iterator]();for(let itv=it.next();!itv.done;itv=it.next()){const e=new Entry(itv.value[0],itv.value[1]);if(this._keymap.set(e.key,e),entry?(entry[NEWER]=e,e[OLDER]=entry):this.oldest=e,entry=e,limit--===0)throw new Error("overflow")}this.newest=entry,this.size=this._keymap.size}set(key,value){let entry=this._keymap.get(key);return entry?(entry.value=value,this._markEntryAsUsed(entry),this):(this._keymap.set(key,entry=new Entry(key,value)),this.newest?(this.newest[NEWER]=entry,entry[OLDER]=this.newest):this.oldest=entry,this.newest=entry,++this.size,this.size>this.limit&&this.shift(),this)}shift(){const entry=this.oldest;if(entry)return this.oldest&&this.oldest[NEWER]?(this.oldest=this.oldest[NEWER],this.oldest[OLDER]=void 0):(this.oldest=void 0,this.newest=void 0),entry[NEWER]=entry[OLDER]=void 0,this._keymap.delete(entry.key),--this.size,this._onShiftListeners.forEach(callback=>callback(entry)),[entry.key,entry.value]}get(key){const entry=this._keymap.get(key);if(entry)return this._markEntryAsUsed(entry),entry.value}has(key){return this._keymap.has(key)}find(key){const e=this._keymap.get(key);return e?e.value:void 0}delete(key){const entry=this._keymap.get(key);if(entry)return this._keymap.delete(entry.key),entry[NEWER]&&entry[OLDER]?(entry[OLDER][NEWER]=entry[NEWER],entry[NEWER][OLDER]=entry[OLDER]):entry[NEWER]?(entry[NEWER][OLDER]=void 0,this.oldest=entry[NEWER]):entry[OLDER]?(entry[OLDER][NEWER]=void 0,this.newest=entry[OLDER]):this.oldest=this.newest=void 0,this.size--,entry.value}clear(){this.oldest=void 0,this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new KeyIterator(this.oldest)}values(){return new ValueIterator(this.oldest)}entries(){return this[Symbol.iterator]()}[Symbol.iterator](){return new EntryIterator(this.oldest)}forEach(fun,thisObj){typeof thisObj!="object"&&(thisObj=this);let entry=this.oldest;for(;entry;)fun.call(thisObj,entry.value,entry.key,this),entry=entry[NEWER]}toJSON(){const s=new Array(this.size);let i=0,entry=this.oldest;for(;entry;)s[i++]={key:entry.key,value:entry.value},entry=entry[NEWER];return s}toString(){let s="",entry=this.oldest;for(;entry;)s+=`${String(entry.key)}:${entry.value}`,entry=entry[NEWER],entry&&(s+=" < ");return s}};__name(_LRUMap,"LRUMap");let LRUMap=_LRUMap;function getArrayLength(o){let maxIndex=0;const keys=Object.keys(o);for(const key of keys){const rowIndex=Number(key);maxIndex=Math.max(maxIndex,rowIndex)}return maxIndex+1}__name(getArrayLength,"getArrayLength");function insertMatrixArray(index2,value,o){const length=getArrayLength(o),array=o;for(let i=length-1;i>=index2;i--)array[i+1]=array[i];array[index2]=value}__name(insertMatrixArray,"insertMatrixArray");function spliceArray(start,count,o){const length=Object.keys(o).reduce((max,key)=>Math.max(max,Number.parseInt(key)),0)+1;for(let i=start;i<length;i++)i<start+count?delete o[i]:o[i]!==void 0&&(o[i-count]=o[i],delete o[i])}__name(spliceArray,"spliceArray");function concatMatrixArray(source,target){const srcArray=source,srcKeys=Object.keys(srcArray),srcLength=srcKeys.length,targetArray=target,targetKeys=Object.keys(targetArray),targetLength=targetKeys.length,containerArray={};let master=0;for(let i=0;i<srcLength;i++,master++){const key=srcKeys[i];containerArray[master]=srcArray[key]}for(let i=0;i<targetLength;i++,master++){const key=targetKeys[i];containerArray[master]=targetArray[key]}return containerArray}__name(concatMatrixArray,"concatMatrixArray");function sliceMatrixArray(start,end,matrixArray){const array=matrixArray;if(getArrayLength(matrixArray)>0){const fragment={};let effective=0;for(let i=start;i<=end;i++)array[i]&&(fragment[effective]=array[i],effective++);return fragment}return{}}__name(sliceMatrixArray,"sliceMatrixArray");function moveMatrixArray(fromIndex,count,toIndex,o){const moveBackward=fromIndex>toIndex;if(!moveBackward&&fromIndex+count>toIndex)throw new Error("Invalid move operation");moveBackward?_moveBackward(fromIndex,count,toIndex,o):_moveForward(fromIndex,count,toIndex,o)}__name(moveMatrixArray,"moveMatrixArray");function _moveBackward(fromIndex,count,toIndex,o){const array=o,toMove=[];for(let i=fromIndex;i<fromIndex+count;i++)toMove.push(array[i]);for(let i=fromIndex-1;i>=toIndex;i--){const item=array[i];array[i+count]=item,item===void 0&&delete array[i+count]}toMove.forEach((item,index2)=>{array[toIndex+index2]=item,item===void 0&&delete array[toIndex+index2]})}__name(_moveBackward,"_moveBackward");function _moveForward(fromIndex,count,toIndex,o){const array=o,toMove=[];for(let i=fromIndex;i<fromIndex+count;i++)toMove.push(array[i]);for(let i=fromIndex+count;i<toIndex;i++){const item=array[i];array[i-count]=item,item===void 0&&delete array[i-count]}toMove.forEach((item,index2)=>{array[toIndex+index2-count]=item,item===void 0&&delete array[toIndex+index2-count]})}__name(_moveForward,"_moveForward");const _ObjectMatrix=class _ObjectMatrix{constructor(matrix={}){__publicField(this,"_matrix");this._setOriginValue(matrix)}static MakeObjectMatrixSize(size){return new _ObjectMatrix({[size-1]:{}})}getMatrix(){return this._matrix}forEach(callback){const matrix=this._matrix,matrixRow=Object.keys(matrix);for(const row of matrixRow){const rowNumber=Number(row),columns=matrix[rowNumber];if(callback(rowNumber,columns)===!1)return this}return this}forRow(callback){const matrix=this._matrix,matrixRow=Object.keys(matrix);for(const row of matrixRow){const rowNumber=Number(row),columns=matrix[rowNumber];if(callback(rowNumber,Object.keys(columns).map(col=>Number(col)))===!1)return this}return this}forValue(callback){const matrix=this._matrix,matrixRow=Object.keys(matrix);for(const row of matrixRow){const rowNumber=Number(row),columns=matrix[rowNumber];if(!columns)continue;const columnKeys=Object.keys(columns);for(const column of columnKeys){const colNumber=Number(column),value=columns[Number(column)];if(callback(rowNumber,colNumber,value)===!1)return this}}return this}swapRow(src,target){const srcRow=this._matrix[src],targetRow=this._matrix[target];this._matrix[src]=targetRow,this._matrix[target]=srcRow}getRow(rowIndex){return this._matrix[rowIndex]}getRowOrCreate(rowIndex){let row=this.getRow(rowIndex);return row==null&&(row={},this._matrix[rowIndex]=row),row}reset(){this._setOriginValue({})}hasValue(){const matrix=this._matrix,matrixRow=Object.keys(matrix);if(matrixRow.length===0)return!1;for(const row of matrixRow){const rowNumber=Number(row),columns=matrix[rowNumber];if(Object.keys(columns).length>0)return!0}return!1}getValue(row,column){var _a13,_b2;return(_b2=(_a13=this._matrix)==null?void 0:_a13[row])==null?void 0:_b2[column]}setValue(row,column,value){const objectArray=this.getRowOrCreate(row);objectArray[column]=value}deleteValue(row,column){var _a13,_b2;(_b2=(_a13=this._matrix)==null?void 0:_a13[row])==null||delete _b2[column]}realDeleteValue(row,column){var _a13,_b2,_c;if((_b2=(_a13=this._matrix)==null?void 0:_a13[row])==null||delete _b2[column],this.getRow(row)){const objectArray=this.getRow(row);if(objectArray==null)return;Object.keys(objectArray).length===0&&((_c=this._matrix)==null||delete _c[row])}}setRow(rowNumber,row){this._matrix[rowNumber]=row}moveRows(start,count,target){moveMatrixArray(start,count,target,this._matrix)}moveColumns(start,count,target){this.forEach((row,value)=>{moveMatrixArray(start,count,target,value)})}insertRows(start,count){for(let r=start;r<start+count;r++)insertMatrixArray(r,{},this._matrix)}insertColumns(start,count){for(let c=start;c<start+count;c++)this.forEach((row,data)=>{data&&insertMatrixArray(c,void 0,data)})}removeRows(start,count){spliceArray(start,count,this._matrix)}removeColumns(start,count){this.forEach((row,value)=>{value&&spliceArray(start,count,value)})}getFragment(startRow,endRow,startColumn,endColumn){const objectMatrix=new _ObjectMatrix;let insertRow=0;for(let r=startRow;r<=endRow;r++){const row={};let insertColumn=0;for(let c=startColumn;c<=endColumn;c++){const value=this.getValue(r,c);row[insertColumn]=value,insertColumn++}objectMatrix.setRow(insertRow,row),insertRow++}return objectMatrix}getSlice(startRow,endRow,startColumn,endColumn){const objectMatrix=new _ObjectMatrix;for(let r=startRow;r<=endRow;r++)for(let c=startColumn;c<=endColumn;c++){const value=this.getValue(r,c);value&&objectMatrix.setValue(r,c,Tools.deepClone(value))}return objectMatrix}getSizeOf(){return Object.keys(this._matrix).length}getLength(){return getArrayLength(this._matrix)}getRange(){const endRow=this.getLength()-1;let endColumn=0;const length=this.getLength();for(let i=0;i<length;i++){const row=this.getRow(i);if(row){const columnLength=getArrayLength(row)-1;endColumn=columnLength>endColumn?columnLength:endColumn}}return{startRow:0,startColumn:0,endRow,endColumn}}toNativeArray(){const native=new Array;return this.forValue((row,col,value)=>{native.push(value)}),native}toArray(){const array=[];return this.forRow((row,cols)=>{array[row]==null&&(array[row]=[]),cols.forEach(column=>{array[row][column]=this.getValue(row,column)})}),array}toFullArray(){const range=this.getRange(),{endColumn,endRow}=range,array=[];for(let i=0;i<=endRow;i++){const subArr=Array(endColumn+1).fill(void 0);array.push(subArr)}return this.forValue((row,col,value)=>{array[row][col]=value}),array}toJSON(){return this._matrix}clone(){const json=JSON.stringify(this._matrix);return JSON.parse(json)}getData(){const json=JSON.stringify(this._matrix);return JSON.parse(json)}getArrayData(){let startRow=0,startColumn=0,initRow=!1,initColumn=!1;const objectMatrix=new _ObjectMatrix;return this.forEach((rowIndex,rowObject)=>{initRow||(initRow=!0,startRow=rowIndex),Object.keys(rowObject).forEach(column=>{const columnIndex=Number(column);initColumn?columnIndex<startColumn&&(startColumn=columnIndex):(initColumn=!0,startColumn=columnIndex);const value=this.getValue(rowIndex,columnIndex);objectMatrix.setValue(rowIndex-startRow,columnIndex-startColumn,value)})}),objectMatrix.getData()}getDataRange(){let startRow=0,startColumn=0,endColumn=0,endRow=-1,initRow=!1,initColumn=!1;return this.forEach((rowIndex,row)=>{if(initRow||(initRow=!0,startRow=rowIndex),row==null)return;const rowSize=getArrayLength(row)-1;rowSize>endColumn&&(endColumn=rowSize),Object.keys(row).forEach(column=>{const columnIndex=Number(column);initColumn?columnIndex<startColumn&&(startColumn=columnIndex):(initColumn=!0,startColumn=columnIndex)}),rowIndex>endRow&&(endRow=rowIndex)}),{startRow,startColumn,endRow,endColumn}}getDiscreteRanges(){const ranges=[];return this.forEach((r,row)=>{Object.keys(row).forEach(col=>{const c=Number(col);let merged=!1;for(const range of ranges)if(r>=range.startRow&&r<=range.endRow+1&&c>=range.startColumn&&c<=range.endColumn+1){range.endRow=Math.max(r,range.endRow),range.endColumn=Math.max(c,range.endColumn),merged=!0;break}merged||ranges.push({startRow:r,endRow:r,startColumn:c,endColumn:c})})}),ranges}merge(newObject){this.forValue((row,column)=>{const cellValue=newObject.getValue(row,column);cellValue!=null&&this.setValue(row,column,cellValue)})}_setOriginValue(matrix={}){this._matrix=matrix}};__name(_ObjectMatrix,"ObjectMatrix");let ObjectMatrix=_ObjectMatrix;const _Rectangle=class _Rectangle{static clone(src){return src.rangeType!==void 0?{startRow:src.startRow,startColumn:src.startColumn,endRow:src.endRow,endColumn:src.endColumn,rangeType:src.rangeType}:{startRow:src.startRow,startColumn:src.startColumn,endRow:src.endRow,endColumn:src.endColumn}}static equals(src,target){return src==null||target==null?!1:src.endRow===target.endRow&&src.endColumn===target.endColumn&&src.startRow===target.startRow&&src.startColumn===target.startColumn&&(src.rangeType===target.rangeType||src.rangeType===void 0&&target.rangeType===RANGE_TYPE.NORMAL||target.rangeType===void 0&&src.rangeType===RANGE_TYPE.NORMAL)}static intersects(src,target){if(src.rangeType===RANGE_TYPE.ROW&&target.rangeType===RANGE_TYPE.COLUMN||src.rangeType===RANGE_TYPE.COLUMN&&target.rangeType===RANGE_TYPE.ROW)return!0;if(src.rangeType===RANGE_TYPE.ROW&&target.rangeType===RANGE_TYPE.ROW)return src.startRow<=target.endRow&&src.endRow>=target.startRow;if(src.rangeType===RANGE_TYPE.COLUMN&&target.rangeType===RANGE_TYPE.COLUMN)return src.startColumn<=target.endColumn&&src.endColumn>=target.startColumn;const MAX=Math.floor(Number.MAX_SAFE_INTEGER/10),currentStartRow=Number.isNaN(src.startRow)?0:src.startRow,currentEndRow=Number.isNaN(src.endRow)?MAX:src.endRow,currentStartColumn=Number.isNaN(src.startColumn)?0:src.startColumn,currentEndColumn=Number.isNaN(src.endColumn)?MAX:src.endColumn,incomingStartRow=Number.isNaN(target.startRow)?0:target.startRow,incomingEndRow=Number.isNaN(target.endRow)?MAX:target.endRow,incomingStartColumn=Number.isNaN(target.startColumn)?0:target.startColumn,incomingEndColumn=Number.isNaN(target.endColumn)?MAX:target.endColumn,zx=Math.abs(currentStartColumn+currentEndColumn-incomingStartColumn-incomingEndColumn),x=Math.abs(currentStartColumn-currentEndColumn)+Math.abs(incomingStartColumn-incomingEndColumn),zy=Math.abs(currentStartRow+currentEndRow-incomingStartRow-incomingEndRow),y=Math.abs(currentStartRow-currentEndRow)+Math.abs(incomingStartRow-incomingEndRow);return zx<=x&&zy<=y}static getIntersects(src,target){const currentStartRow=src.startRow,currentEndRow=src.endRow,currentStartColumn=src.startColumn,currentEndColumn=src.endColumn,incomingStartRow=target.startRow,incomingEndRow=target.endRow,incomingStartColumn=target.startColumn,incomingEndColumn=target.endColumn;let startColumn,startRow,endColumn,endRow;if(incomingStartRow<=currentEndRow)incomingStartRow>=currentStartRow?startRow=incomingStartRow:startRow=currentStartRow;else return null;if(incomingEndRow>=currentStartRow)incomingEndRow>=currentEndRow?endRow=currentEndRow:endRow=incomingEndRow;else return null;if(incomingStartColumn<=currentEndColumn)incomingStartColumn>currentStartColumn?startColumn=incomingStartColumn:startColumn=currentStartColumn;else return null;if(incomingEndColumn>=currentStartColumn)incomingEndColumn>=currentEndColumn?endColumn=currentEndColumn:endColumn=incomingEndColumn;else return null;return{startRow,endRow,startColumn,endColumn,rangeType:RANGE_TYPE.NORMAL}}static contains(src,target){return src.startRow<=target.startRow&&src.endRow>=target.endRow&&src.startColumn<=target.startColumn&&src.endColumn>=target.endColumn}static realContain(src,target){return _Rectangle.contains(src,target)&&(src.startRow<target.startRow||src.endRow>target.endRow||src.startColumn<target.startColumn||src.endColumn>target.endColumn)}static union(...ranges){return ranges.reduce((acc,current)=>({startRow:Math.min(acc.startRow,current.startRow),startColumn:Math.min(acc.startColumn,current.startColumn),endRow:Math.max(acc.endRow,current.endRow),endColumn:Math.max(acc.endColumn,current.endColumn),rangeType:RANGE_TYPE.NORMAL}),ranges[0])}static realUnion(...ranges){const hasColRange=ranges.some(range=>range.rangeType===RANGE_TYPE.COLUMN),hasRowRange=ranges.some(range=>range.rangeType===RANGE_TYPE.ROW),res=_Rectangle.union(...ranges);return{startColumn:hasRowRange?Number.NaN:res.startColumn,endColumn:hasRowRange?Number.NaN:res.endColumn,startRow:hasColRange?Number.NaN:res.startRow,endRow:hasColRange?Number.NaN:res.endRow,rangeType:hasRowRange?RANGE_TYPE.ROW:hasColRange?RANGE_TYPE.COLUMN:RANGE_TYPE.NORMAL}}static subtract(range1,range2){if(range2.startRow>range1.endRow||range2.endRow<range1.startRow||range2.startColumn>range1.endColumn||range2.endColumn<range1.startColumn)return[range1];const ranges=[];range2.startRow>=range1.startRow&&ranges.push({startRow:range1.startRow,startColumn:range1.startColumn,endRow:range2.startRow-1,endColumn:range1.endColumn}),range2.endRow<=range1.endRow&&ranges.push({startRow:range2.endRow+1,startColumn:range1.startColumn,endRow:range1.endRow,endColumn:range1.endColumn});const topBoundary=Math.max(range1.startRow,range2.startRow),bottomBoundary=Math.min(range1.endRow,range2.endRow);return range2.startColumn>=range1.startColumn&&ranges.push({startRow:topBoundary,startColumn:range1.startColumn,endRow:bottomBoundary,endColumn:range2.startColumn-1}),range2.endColumn<=range1.endColumn&&ranges.push({startRow:topBoundary,startColumn:range2.endColumn+1,endRow:bottomBoundary,endColumn:range1.endColumn}),ranges.filter(range=>range.startRow<=range.endRow&&range.startColumn<=range.endColumn)}static hasIntersectionBetweenTwoRect(rect1,rect2){return!(rect1.left>rect2.right||rect1.right<rect2.left||rect1.top>rect2.bottom||rect1.bottom<rect2.top)}static getIntersectionBetweenTwoRect(rect1,rect2){const left=Math.max(rect1.left,rect2.left),right=Math.min(rect1.right,rect2.right),top=Math.max(rect1.top,rect2.top),bottom=Math.min(rect1.bottom,rect2.bottom);return right<=left||bottom<=top?null:{left,right,top,bottom,width:right-left,height:bottom-top}}};__name(_Rectangle,"Rectangle"),__publicField(_Rectangle,"getRelativeRange",__name((range,originRange)=>({startRow:range.startRow-originRange.startRow,endRow:range.endRow-range.startRow,startColumn:range.startColumn-originRange.startColumn,endColumn:range.endColumn-range.startColumn}),"getRelativeRange")),__publicField(_Rectangle,"getPositionRange",__name((relativeRange,originRange,absoluteRange)=>({...absoluteRange||{},startRow:absoluteRange&&[AbsoluteRefType.ROW,AbsoluteRefType.ALL].includes(absoluteRange.startAbsoluteRefType||0)?absoluteRange.startRow:relativeRange.startRow+originRange.startRow,endRow:absoluteRange&&[AbsoluteRefType.ROW,AbsoluteRefType.ALL].includes(absoluteRange.endAbsoluteRefType||0)?absoluteRange.endRow:relativeRange.endRow+relativeRange.startRow+originRange.startRow,startColumn:absoluteRange&&[AbsoluteRefType.COLUMN,AbsoluteRefType.ALL].includes(absoluteRange.startAbsoluteRefType||0)?absoluteRange.startColumn:relativeRange.startColumn+originRange.startColumn,endColumn:absoluteRange&&[AbsoluteRefType.COLUMN,AbsoluteRefType.ALL].includes(absoluteRange.endAbsoluteRefType||0)?absoluteRange.endColumn:relativeRange.endColumn+relativeRange.startColumn+originRange.startColumn}),"getPositionRange")),__publicField(_Rectangle,"moveHorizontal",__name((range,step=0,length=0)=>({...range,startColumn:range.startColumn+step,endColumn:range.endColumn+step+length}),"moveHorizontal")),__publicField(_Rectangle,"moveVertical",__name((range,step=0,length=0)=>({...range,startRow:range.startRow+step,endRow:range.endRow+step+length}),"moveVertical")),__publicField(_Rectangle,"moveOffset",__name((range,offsetX,offsetY)=>({...range,startRow:range.startRow+offsetY,endRow:range.endRow+offsetY,startColumn:range.startColumn+offsetX,endColumn:range.endColumn+offsetX}),"moveOffset"));let Rectangle=_Rectangle;const _RefAlias=class _RefAlias{constructor(values,keys){__publicField(this,"_values",[]);__publicField(this,"_keys",[]);__publicField(this,"_keyMaps",new Map);this._values=values,this._keys=keys,values.forEach(item=>{this._initKeyMap(item)})}_initKeyMap(item){this._keys.forEach(key=>{const value=item[key],keyMap=this._keyMaps.get(key)||new Map;keyMap.set(value,item),this._keyMaps.set(key,keyMap)})}getValue(key,keyGroup){const keys=keyGroup||this._keys;for(let index2=0;index2<keys.length;index2++){const keyMap=this._keyMaps.get(keys[index2]);if(keyMap!=null&&keyMap.has(key))return keyMap.get(key)}return null}hasValue(key){for(let index2=0;index2<this._keys.length;index2++){const keyMap=this._keyMaps.get(this._keys[index2]);if(keyMap!=null&&keyMap.has(key))return!0}return!1}addValue(item){this._values.push(item),this._initKeyMap(item)}setValue(key,attr,value){const item=this.getValue(key);item&&Object.keys(item).includes(attr)&&(item[attr]=value)}deleteValue(key){const value=this.getValue(key);if(value){this._keys.forEach(keyItem=>{const keyMap=this._keyMaps.get(keyItem),_key=value[keyItem];keyMap==null||keyMap.delete(_key)});const index2=this._values.findIndex(item=>item===value);this._values.splice(index2,1)}}getValues(){return this._values}getKeyMap(key){var _a13;return[...((_a13=this._keyMaps.get(key))==null?void 0:_a13.keys())||[]]}clear(){this._values=[],this._keys=[],this._keyMaps.clear()}};__name(_RefAlias,"RefAlias");let RefAlias=_RefAlias;function createRowColIter(rowStart,rowEnd,colStart,colEnd){return{forEach(cb){for(let r=rowStart;r<=rowEnd;r++)for(let c=colStart;c<=colEnd;c++)cb(r,c)}}}__name(createRowColIter,"createRowColIter");function ABCToNumber(a){if(a==null||a.length===0)return Number.NaN;const str=a.toLowerCase().split(""),al=str.length,getCharNumber=__name(charX=>charX.charCodeAt(0)-96,"getCharNumber");let numOut=0,charnum=0;for(let i=0;i<al;i++)charnum=getCharNumber(str[i]),numOut+=charnum*26**(al-i-1);return numOut===0?Number.NaN:numOut-1}__name(ABCToNumber,"ABCToNumber");const orderA=65,orderZ=90,order_a=97;function numberToABC(n){const len=orderZ-orderA+1;let s="";for(;n>=0;)s=String.fromCharCode(n%len+orderA)+s,n=Math.floor(n/len)-1;return s}__name(numberToABC,"numberToABC");function repeatStringNumTimes(string,times){let repeatedString="";for(;times>0;)repeatedString+=string,times--;return repeatedString}__name(repeatStringNumTimes,"repeatStringNumTimes");function numberToListABC(n,uppercase=!1){const len=orderZ-orderA+1;let order=order_a;uppercase&&(order=orderA);const abc=String.fromCharCode(n%len+order),times=Math.floor(n/len)+1;return repeatStringNumTimes(abc,times)}__name(numberToListABC,"numberToListABC");function sortRules(oa,ob){return oa.zIndex>ob.zIndex?1:oa.zIndex===ob.zIndex?0:-1}__name(sortRules,"sortRules");function sortRulesByDesc(oa,ob){return oa.zIndex>ob.zIndex?-1:oa.zIndex===ob.zIndex?0:1}__name(sortRulesByDesc,"sortRulesByDesc");function sortRulesFactory(key="index",ruler=1){return(oa,ob)=>oa[key]>ob[key]?ruler:oa[key]===ob[key]?0:-ruler}__name(sortRulesFactory,"sortRulesFactory");function debounce(func,wait){let timeout;function run(...args){const context=this,later=__name(function(){timeout=null,func.apply(context,args)},"later");clearTimeout(timeout),timeout=setTimeout(later,wait)}return __name(run,"run"),Object.defineProperty(run,"cancel",{value:__name(()=>{clearTimeout(timeout)},"value"),enumerable:!1,writable:!1}),run}__name(debounce,"debounce");function getBodySliceHtml(body,startIndex,endIndex){const{dataStream,textRuns=[]}=body;let cursorIndex=startIndex;const spanList=[];for(const textRun of textRuns){const{st,ed}=textRun;Tools.hasIntersectionBetweenTwoRanges(startIndex,endIndex,st,ed)&&(st>cursorIndex?(spanList.push(dataStream.slice(cursorIndex,st)),spanList.push(covertTextRunToHtml(dataStream,{...textRun,ed:Math.min(ed,endIndex)}))):spanList.push(covertTextRunToHtml(dataStream,{...textRun,st:cursorIndex,ed:Math.min(ed,endIndex)}))),cursorIndex=Math.max(startIndex,Math.min(ed,endIndex))}return cursorIndex!==endIndex&&spanList.push(dataStream.slice(cursorIndex,endIndex)),spanList.join("")}__name(getBodySliceHtml,"getBodySliceHtml");function convertBodyToHtml(body,withParagraphInfo=!0){var _a13;if(withParagraphInfo&&((_a13=body.paragraphs)!=null&&_a13.length)){const{dataStream,paragraphs=[]}=body;let result="",cursorIndex=-1;for(const paragraph of paragraphs){const{startIndex,paragraphStyle={}}=paragraph,{spaceAbove,spaceBelow,lineSpacing}=paragraphStyle,style=[];spaceAbove!=null&&(typeof spaceAbove=="number"?style.push(`margin-top: ${spaceAbove}px`):style.push(`margin-top: ${spaceAbove.v}px`)),spaceBelow!=null&&(typeof spaceBelow=="number"?style.push(`margin-bottom: ${spaceBelow}px`):style.push(`margin-bottom: ${spaceBelow.v}px`)),lineSpacing!=null&&style.push(`line-height: ${lineSpacing}`),startIndex>cursorIndex+1?result+=`<p class="UniverNormal" ${style.length?`style="${style.join("; ")};"`:""}>${getBodySliceHtml(body,cursorIndex+1,startIndex)}</p>`:result+=`<p class="UniverNormal" ${style.length?`style="${style.join("; ")};"`:""}></p>`,cursorIndex=startIndex}return cursorIndex!==dataStream.length&&(result+=getBodySliceHtml(body,cursorIndex,dataStream.length)),result}else return getBodySliceHtml(body,0,body.dataStream.length)}__name(convertBodyToHtml,"convertBodyToHtml");function covertTextRunToHtml(dataStream,textRun){const{st:start,ed,ts={}}=textRun,{ff,fs,it,bl,ul,st,ol,bg,cl,va}=ts;let html=dataStream.slice(start,ed);const style=[];return it===BooleanNumber.TRUE&&(html=`<i>${html}</i>`),va===BaselineOffset.SUPERSCRIPT?html=`<sup>${html}</sup>`:va===BaselineOffset.SUBSCRIPT&&(html=`<sub>${html}</sub>`),(ul==null?void 0:ul.s)===BooleanNumber.TRUE&&(html=`<u>${html}</u>`),(st==null?void 0:st.s)===BooleanNumber.TRUE&&(html=`<s>${html}</s>`),bl===BooleanNumber.TRUE&&(html=`<strong>${html}</strong>`),ff&&style.push(`font-family: ${ff}`),cl&&style.push(`color: ${cl.rgb}`),fs&&style.push(`font-size: ${fs}pt`),ol&&style.push("text-decoration: overline"),bg&&style.push(`background: ${bg.rgb}`),style.length?`<span style="${style.join("; ")};">${html}</span>`:html}__name(covertTextRunToHtml,"covertTextRunToHtml");const DEFAULT_RANGE_ARRAY={sheetId:"",range:{startRow:-1,endRow:-1,startColumn:-1,endColumn:-1}},DEFAULT_RANGE={startRow:-1,startColumn:-1,endRow:-1,endColumn:-1},DEFAULT_SELECTION={startRow:0,startColumn:0,endRow:0,endColumn:0},DEFAULT_CELL={row:0,column:0},DEFAULT_STYLES={ff:"Arial",fs:11,it:BooleanNumber.FALSE,bl:BooleanNumber.FALSE,ul:{s:BooleanNumber.FALSE},st:{s:BooleanNumber.FALSE},ol:{s:BooleanNumber.FALSE},tr:{a:0,v:BooleanNumber.FALSE},td:TextDirection.UNSPECIFIED,cl:{rgb:"#000"},bg:{rgb:"#fff"},ht:HorizontalAlign.UNSPECIFIED,vt:VerticalAlign.UNSPECIFIED,tb:WrapStrategy.UNSPECIFIED,pd:{t:0,r:0,b:0,l:0}},DEFAULT_SLIDE={id:"default_slide",title:"defaultSlide",pageSize:{width:300,height:300}};var EXTENSION_NAMES=(EXTENSION_NAMES2=>(EXTENSION_NAMES2.ARRAY_CONVERTOR="ARRAY_CONVERTOR",EXTENSION_NAMES2.MATRIX_CONVERTOR="MATRIX_CONVERTOR",EXTENSION_NAMES2))(EXTENSION_NAMES||{});function isAllFormatInTextRuns(key,body){const{textRuns=[]}=body;let len=0;for(const textRun of textRuns){const{ts={},st,ed}=textRun;if(ts[key]==null)return BooleanNumber.FALSE;switch(key){case"bl":case"it":{if(ts[key]===BooleanNumber.FALSE)return BooleanNumber.FALSE;break}case"ul":case"st":{if(ts[key].s===BooleanNumber.FALSE)return BooleanNumber.FALSE;break}default:throw new Error(`unknown style key: ${key} in IStyleBase`)}len+=ed-st}return body.dataStream.indexOf(`\r
4
+ `)===len?BooleanNumber.TRUE:BooleanNumber.FALSE}__name(isAllFormatInTextRuns,"isAllFormatInTextRuns");const _Range=class _Range{constructor(workSheet,range,_deps){__publicField(this,"_range");__publicField(this,"_worksheet");this._deps=_deps,this._range=range,this._worksheet=workSheet}static foreach(range,action){const{startRow,startColumn,endRow,endColumn}=range;for(let i=startRow;i<=endRow;i++)for(let j=startColumn;j<=endColumn;j++)action(i,j)}getRangeData(){return this._range}getValue(){return this.getValues()[0][0]}getValues(){const{startRow,endRow,startColumn,endColumn}=this._range,range=[];for(let r=startRow;r<=endRow;r++){const row=[];for(let c=startColumn;c<=endColumn;c++)row.push(this.getMatrix().getValue(r,c)||null);range.push(row)}return range}getMatrix(){const{startRow,endRow,startColumn,endColumn}=this._range,sheetMatrix=this._worksheet.getCellMatrix(),rangeMatrix=new ObjectMatrix;for(let r=startRow;r<=endRow;r++)for(let c=startColumn;c<=endColumn;c++)rangeMatrix.setValue(r,c,sheetMatrix.getValue(r,c)||null);return rangeMatrix}getMatrixObject(){const{startRow,endRow,startColumn,endColumn}=this._range,sheetMatrix=this._worksheet.getCellMatrix(),rangeMatrix=new ObjectMatrix;for(let r=startRow;r<=endRow;r++)for(let c=startColumn;c<=endColumn;c++)rangeMatrix.setValue(r-startRow,c-startColumn,sheetMatrix.getValue(r,c)||{});return rangeMatrix}getA1Notation(){const{startRow,endRow,startColumn,endColumn}=this._range;let start,end;return startColumn<endColumn?(start=Tools.numToWord(startColumn+1)+(startRow+1),end=Tools.numToWord(endColumn+1)+(endRow+1)):(start=Tools.numToWord(endColumn+1)+(endRow+1),end=Tools.numToWord(startColumn+1)+(startRow+1)),start===end?`${start}`:`${start}:${end}`}getBackground(){return this.getBackgrounds()[0][0]}getBackgrounds(){const styles=this._deps.getStyles();return this.getValues().map(row=>row.map(cell=>{var _a13;const rgbColor=styles.getStyleByCell(cell);return((_a13=rgbColor==null?void 0:rgbColor.bg)==null?void 0:_a13.rgb)||DEFAULT_STYLES.bg.rgb}))}getCell(row,column){const{startRow,endRow,startColumn,endColumn}=this._range,cell={startRow:startRow+row,endRow:startRow+row,startColumn:startColumn+column,endColumn:startColumn+column};return new _Range(this._worksheet,cell,this._deps)}getColumn(){return this._range.startColumn}getObjectValue(options={}){return this.getObjectValues(options)[0][0]}getObjectValues(options={}){var _a13;const{startRow,endRow,startColumn,endColumn}=this._range,values=this._worksheet.getCellMatrix().getFragment(startRow,endRow,startColumn,endColumn).getData();if(options.isIncludeStyle){const style=this._deps.getStyles();for(let r=0;r<=endRow-startRow;r++)for(let c=0;c<=endColumn-startColumn;c++){if(values==null||((_a13=values==null?void 0:values[r])==null?void 0:_a13[c])==null)continue;const s=values[r][c].s;s&&(values[r][c].s=style.get(s))}}return values}getFontColor(){return this.getFontColors()[0][0]}getFontColors(){const styles=this._deps.getStyles();return this.getValues().map(row=>row.map(cell=>{var _a13;const cellStyle=styles.getStyleByCell(cell);return((_a13=cellStyle==null?void 0:cellStyle.cl)==null?void 0:_a13.rgb)||DEFAULT_STYLES.cl.rgb}))}getFontFamilies(){return this._getStyles("ff")}getFontFamily(){return this.getFontFamilies()[0][0]}getUnderlines(){return this._getStyles("ul")}getUnderline(){var _a13,_b2;const{p}=(_a13=this.getValue())!=null?_a13:{};return p&&Array.isArray((_b2=p.body)==null?void 0:_b2.textRuns)&&p.body.textRuns.length>0?isAllFormatInTextRuns("ul",p.body)===BooleanNumber.TRUE?{s:BooleanNumber.TRUE}:{s:BooleanNumber.FALSE}:this.getUnderlines()[0][0]}getOverlines(){return this._getStyles("ol")}getOverline(){return this.getOverlines()[0][0]}getStrikeThrough(){var _a13,_b2;const{p}=(_a13=this.getValue())!=null?_a13:{};return p&&Array.isArray((_b2=p.body)==null?void 0:_b2.textRuns)&&p.body.textRuns.length>0?isAllFormatInTextRuns("st",p.body)===BooleanNumber.TRUE?{s:BooleanNumber.TRUE}:{s:BooleanNumber.FALSE}:this.getStrikeThroughs()[0][0]}getStrikeThroughs(){return this._getStyles("st")}getFontSize(){var _a13,_b2;const p=((_a13=this.getValue())==null?void 0:_a13.p)||{};return p&&Array.isArray((_b2=p.body)==null?void 0:_b2.textRuns)&&p.body.textRuns.length>0?p.body.textRuns.some(textRun=>{var _a14;return((_a14=textRun==null?void 0:textRun.ts)==null?void 0:_a14.fs)!=null})?Math.max(...p.body.textRuns.map(textRun=>{var _a14;return((_a14=textRun==null?void 0:textRun.ts)==null?void 0:_a14.fs)||0})):this.getFontSizes()[0][0]:this.getFontSizes()[0][0]}getFontSizes(){return this._getStyles("fs")}getBorder(){return this.getBorders()[0][0]}getBorders(){return this._getStyles("bd")}getFontStyle(){var _a13,_b2;const{p}=(_a13=this.getValue())!=null?_a13:{};return p&&Array.isArray((_b2=p.body)==null?void 0:_b2.textRuns)&&p.body.textRuns.length>0?isAllFormatInTextRuns("it",p.body)===BooleanNumber.TRUE?FontItalic.ITALIC:FontItalic.NORMAL:this._getFontStyles()[0][0]}_getFontStyles(){return this._getStyles("it")}getFontWeight(){var _a13,_b2;const{p}=(_a13=this.getValue())!=null?_a13:{};return p&&Array.isArray((_b2=p.body)==null?void 0:_b2.textRuns)&&p.body.textRuns.length>0?isAllFormatInTextRuns("bl",p.body)===BooleanNumber.TRUE?FontWeight.BOLD:FontWeight.NORMAL:this._getFontWeights()[0][0]}_getFontWeights(){return this._getStyles("bl")}getGridId(){return this._worksheet.getSheetId()}getHeight(){const{_range:_rangeData,_worksheet}=this,{startRow,endRow}=_rangeData;let h=0;for(let i=0;i<=endRow-startRow;i++){const hh=_worksheet.getRowHeight(i);h+=hh}return h}getHorizontalAlignment(){return this.getHorizontalAlignments()[0][0]}getHorizontalAlignments(){return this._getStyles("ht")}getLastColumn(){return this._range.endColumn}getLastRow(){return this._range.endRow}getNumColumns(){const{startColumn,endColumn}=this._range;return endColumn-startColumn+1}getNumRows(){const{startRow,endRow}=this._range;return endRow-startRow+1}getRichTextValue(){return this.getRichTextValues()[0][0]}getRichTextValues(){return this.getValues().map(row=>row.map(cell=>(cell==null?void 0:cell.p)||""))}getRowIndex(){return this._range.startRow}getSheet(){return this._worksheet}getTextDirection(){return this.getTextDirections()[0][0]}getTextDirections(){return this._getStyles("td")}getTextRotation(){return this.getTextRotations()[0][0]}getTextRotations(){return this._getStyles("tr")}getTextStyle(){return this.getTextStyles()[0][0]}getTextStyles(){const styles=this._deps.getStyles();return this.getValues().map(row=>row.map(cell=>styles.getStyleByCell(cell)))}getVerticalAlignment(){return this.getVerticalAlignments()[0][0]}getVerticalAlignments(){return this._getStyles("vt")}getWidth(){const{_range:_rangeData,_worksheet}=this,{startColumn,endColumn}=_rangeData;let w=0;for(let i=0;i<=endColumn-startColumn;i++)w+=_worksheet.getColumnWidth(i);return w}getWrap(){return this.getWrapStrategy()===WrapStrategy.WRAP?BooleanNumber.TRUE:BooleanNumber.FALSE}getWrapStrategies(){return this._getStyles("tb")}getWrapStrategy(){return this.getWrapStrategies()[0][0]}forEach(action){_Range.foreach(this._range,action)}_getStyles(styleKey){const styles=this._deps.getStyles();return this.getValues().map(row=>row.map(cell=>{const style=styles&&styles.getStyleByCell(cell);return style&&style[styleKey]||DEFAULT_STYLES[styleKey]}))}};__name(_Range,"Range"),__publicField(_Range,"transformRange",__name((range,worksheet)=>range.rangeType===RANGE_TYPE.ALL?{startColumn:0,startRow:0,endColumn:worksheet.getMaxColumns()-1,endRow:worksheet.getMaxRows()-1}:range.rangeType===RANGE_TYPE.COLUMN?{startRow:0,endRow:worksheet.getMaxRows()-1,startColumn:range.startColumn,endColumn:range.endColumn}:range.rangeType===RANGE_TYPE.ROW?{startColumn:0,endColumn:worksheet.getMaxColumns()-1,startRow:range.startRow,endRow:range.endRow}:range,"transformRange"));let Range=_Range;function maximalRectangle(matrix,match){if(matrix.length===0||matrix[0].length===0)return null;const heights=new Array(matrix[0].length).fill(0);let maxArea=0,maxRect=null;for(let row=0;row<matrix.length;row++){for(let col=0;col<matrix[0].length;col++)heights[col]=match(matrix[row][col])?heights[col]+1:0;const areaWithRect=largestRectangleArea(heights);areaWithRect.area>maxArea&&(maxArea=areaWithRect.area,maxRect={startColumn:areaWithRect.start,startRow:row-areaWithRect.height+1,endColumn:areaWithRect.end,endRow:row})}return maxRect}__name(maximalRectangle,"maximalRectangle");function largestRectangleArea(heights){const stack=[];let maxArea=0,maxRect={area:0,height:0,start:0,end:0},index2=0;for(;index2<heights.length;)if(stack.length===0||heights[index2]>=heights[stack[stack.length-1]])stack.push(index2++);else{const height=heights[stack.pop()],width=stack.length===0?index2:index2-stack[stack.length-1]-1;height*width>maxArea&&(maxArea=height*width,maxRect={area:maxArea,height,start:stack.length===0?0:stack[stack.length-1]+1,end:index2-1})}for(;stack.length>0;){const height=heights[stack.pop()],width=stack.length===0?index2:index2-stack[stack.length-1]-1;height*width>maxArea&&(maxArea=height*width,maxRect={area:maxArea,height,start:stack.length===0?0:stack[stack.length-1]+1,end:index2-1})}return maxRect}__name(largestRectangleArea,"largestRectangleArea");function resetMatrix(matrix,range){Range.foreach(range,(row,col)=>{matrix[row][col]=void 0})}__name(resetMatrix,"resetMatrix");function queryObjectMatrix(matrix,match){const arrayMatrix=matrix.toFullArray(),results=[];for(;;){const rectangle=maximalRectangle(arrayMatrix,match);if(!rectangle)break;results.push(rectangle),resetMatrix(arrayMatrix,rectangle)}return results}__name(queryObjectMatrix,"queryObjectMatrix");function moveRangeByOffset(range,refOffsetX,refOffsetY,ignoreAbsolute=!1){let newRange={...range};const startAbsoluteRefType=newRange.startAbsoluteRefType||AbsoluteRefType.NONE,endAbsoluteRefType=newRange.endAbsoluteRefType||AbsoluteRefType.NONE;return!ignoreAbsolute&&startAbsoluteRefType===AbsoluteRefType.ALL&&endAbsoluteRefType===AbsoluteRefType.ALL?newRange:ignoreAbsolute||startAbsoluteRefType===AbsoluteRefType.NONE&&endAbsoluteRefType===AbsoluteRefType.NONE?Rectangle.moveOffset(newRange,refOffsetX,refOffsetY):(startAbsoluteRefType===AbsoluteRefType.NONE?newRange={...newRange,startRow:newRange.startRow+refOffsetY,startColumn:newRange.startColumn+refOffsetX}:startAbsoluteRefType===AbsoluteRefType.COLUMN?newRange={...newRange,startRow:newRange.startRow+refOffsetY}:startAbsoluteRefType===AbsoluteRefType.ROW&&(newRange={...newRange,startColumn:newRange.startColumn+refOffsetX}),endAbsoluteRefType===AbsoluteRefType.NONE?newRange={...newRange,endRow:newRange.endRow+refOffsetY,endColumn:newRange.endColumn+refOffsetX}:endAbsoluteRefType===AbsoluteRefType.COLUMN?newRange={...newRange,endRow:newRange.endRow+refOffsetY}:endAbsoluteRefType===AbsoluteRefType.ROW&&(newRange={...newRange,endColumn:newRange.endColumn+refOffsetX}),newRange)}__name(moveRangeByOffset,"moveRangeByOffset");var IdentifierDecoratorSymbol=Symbol("$$IDENTIFIER_DECORATOR");function isIdentifierDecorator(thing){return thing&&thing[IdentifierDecoratorSymbol]===!0}__name(isIdentifierDecorator,"isIdentifierDecorator");function isCtor(thing){return typeof thing=="function"}__name(isCtor,"isCtor");function isClassDependencyItem(thing){return!!(thing&&typeof thing.useClass<"u")}__name(isClassDependencyItem,"isClassDependencyItem");function isFactoryDependencyItem(thing){return!!(thing&&typeof thing.useFactory<"u")}__name(isFactoryDependencyItem,"isFactoryDependencyItem");function isValueDependencyItem(thing){return!!(thing&&typeof thing.useValue<"u")}__name(isValueDependencyItem,"isValueDependencyItem");function isExistingDependencyItem(thing){return!!(thing&&typeof thing.useExisting<"u")}__name(isExistingDependencyItem,"isExistingDependencyItem");function isAsyncDependencyItem(thing){return!!(thing&&typeof thing.useAsync<"u")}__name(isAsyncDependencyItem,"isAsyncDependencyItem");var AsyncHookSymbol=Symbol("AsyncHook");function isAsyncHook(thing){return!!(thing&&thing.__symbol===AsyncHookSymbol)}__name(isAsyncHook,"isAsyncHook");function prettyPrintIdentifier(id){return typeof id>"u"?"undefined":isCtor(id)&&!id[IdentifierDecoratorSymbol]?id.name:id.toString()}__name(prettyPrintIdentifier,"prettyPrintIdentifier");exports.Quantity=void 0;(function(Quantity){Quantity.MANY="many",Quantity.OPTIONAL="optional",Quantity.REQUIRED="required"})(exports.Quantity||(exports.Quantity={}));exports.LookUp=void 0;(function(LookUp){LookUp.SELF="self",LookUp.SKIP_SELF="skipSelf"})(exports.LookUp||(exports.LookUp={}));var __extends$4=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),RediError=function(_super){__extends$4(RediError2,_super);function RediError2(message){return _super.call(this,"[redi]: ".concat(message))||this}return __name(RediError2,"RediError"),RediError2}(Error),__extends$3=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),TARGET=Symbol("$$TARGET"),DEPENDENCIES=Symbol("$$DEPENDENCIES"),DependencyDescriptorNotFoundError=function(_super){__extends$3(DependencyDescriptorNotFoundError2,_super);function DependencyDescriptorNotFoundError2(index2,target){var msg="Could not find dependency registered on the ".concat(index2,' (indexed) parameter of the constructor of "').concat(prettyPrintIdentifier(target),'".');return _super.call(this,msg)||this}return __name(DependencyDescriptorNotFoundError2,"DependencyDescriptorNotFoundError"),DependencyDescriptorNotFoundError2}(RediError),IdentifierUndefinedError=function(_super){__extends$3(IdentifierUndefinedError2,_super);function IdentifierUndefinedError2(target,index2){var msg='It seems that you register "undefined" as dependency on the '.concat(index2+1,' parameter of "').concat(prettyPrintIdentifier(target),'". Please make sure that there is not cyclic dependency among your TypeScript files, or consider using "forwardRef". For more info please visit our website https://redi.wendell.fun/docs/debug#could-not-find-dependency-registered-on');return _super.call(this,msg)||this}return __name(IdentifierUndefinedError2,"IdentifierUndefinedError"),IdentifierUndefinedError2}(RediError);function getDependencies(registerTarget){var target=registerTarget;return target[DEPENDENCIES]||[]}__name(getDependencies,"getDependencies");function getDependencyByIndex(registerTarget,index2){var allDependencies=getDependencies(registerTarget),dep=allDependencies.find(function(descriptor){return descriptor.paramIndex===index2});if(!dep)throw new DependencyDescriptorNotFoundError(index2,registerTarget);return dep}__name(getDependencyByIndex,"getDependencyByIndex");function setDependency(registerTarget,identifier,paramIndex,quantity,lookUp){quantity===void 0&&(quantity=exports.Quantity.REQUIRED);var descriptor={paramIndex,identifier,quantity,lookUp,withNew:!1};if(typeof identifier>"u")throw new IdentifierUndefinedError(registerTarget,paramIndex);var target=registerTarget;target[TARGET]===target?target[DEPENDENCIES].push(descriptor):(target[DEPENDENCIES]=[descriptor],target[TARGET]=target)}__name(setDependency,"setDependency");var knownIdentifiers=new Set;function createIdentifier(id){if(knownIdentifiers.has(id))throw new RediError('Identifier "'.concat(id,'" already exists.'));knownIdentifiers.add(id);var decorator=__name(function(registerTarget,_key,index2){setDependency(registerTarget,decorator,index2)},"decorator");return decorator.toString=function(){return id},decorator[IdentifierDecoratorSymbol]=!0,decorator}__name(createIdentifier,"createIdentifier");var __extends$2=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),QuantityCheckError=function(_super){__extends$2(QuantityCheckError2,_super);function QuantityCheckError2(id,quantity,actual){var msg='Expect "'.concat(quantity,'" dependency items for id "').concat(prettyPrintIdentifier(id),'" but get ').concat(actual,".");return _super.call(this,msg)||this}return __name(QuantityCheckError2,"QuantityCheckError"),QuantityCheckError2}(RediError);function checkQuantity(id,quantity,length){if(quantity===exports.Quantity.OPTIONAL&&length>1||quantity===exports.Quantity.REQUIRED&&length!==1)throw new QuantityCheckError(id,quantity,length)}__name(checkQuantity,"checkQuantity");function retrieveQuantity(quantity,arr){return quantity===exports.Quantity.MANY?arr:arr[0]}__name(retrieveQuantity,"retrieveQuantity");function changeQuantity(target,index2,quantity){var descriptor=getDependencyByIndex(target,index2);descriptor.quantity=quantity}__name(changeQuantity,"changeQuantity");function quantifyDecoratorFactoryProducer(quantity){return __name(function decoratorFactory(id){return this instanceof decoratorFactory?this:function(registerTarget,_key,index2){if(id)setDependency(registerTarget,id,index2,quantity);else{if(quantity===exports.Quantity.REQUIRED)throw new IdentifierUndefinedError(registerTarget,index2);changeQuantity(registerTarget,index2,quantity)}}},"decoratorFactory")}__name(quantifyDecoratorFactoryProducer,"quantifyDecoratorFactoryProducer");var Many=quantifyDecoratorFactoryProducer(exports.Quantity.MANY),Optional=quantifyDecoratorFactoryProducer(exports.Quantity.OPTIONAL),Inject=quantifyDecoratorFactoryProducer(exports.Quantity.REQUIRED);function forwardRef(wrapper){return{unwrap:wrapper}}__name(forwardRef,"forwardRef");function isForwardRef(thing){return!!thing&&typeof thing.unwrap=="function"}__name(isForwardRef,"isForwardRef");function normalizeForwardRef(id){return isForwardRef(id)?id.unwrap():id}__name(normalizeForwardRef,"normalizeForwardRef");function isDisposable(thing){return!!thing&&typeof thing.dispose=="function"}__name(isDisposable,"isDisposable");var __extends$1$1=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();function isBareClassDependency(thing){return thing.length===1}__name(isBareClassDependency,"isBareClassDependency");var ResolvingStack=[];function pushResolvingStack(id){ResolvingStack.push(id)}__name(pushResolvingStack,"pushResolvingStack");function popupResolvingStack(){ResolvingStack.pop()}__name(popupResolvingStack,"popupResolvingStack");function clearResolvingStack(){ResolvingStack.length=0}__name(clearResolvingStack,"clearResolvingStack");var DependencyNotFoundForModuleError=function(_super){__extends$1$1(DependencyNotFoundForModuleError2,_super);function DependencyNotFoundForModuleError2(toInstantiate,id,index2){var msg='Cannot find "'.concat(prettyPrintIdentifier(id),'" registered by any injector. It is the ').concat(index2,'th param of "').concat(isIdentifierDecorator(toInstantiate)?prettyPrintIdentifier(toInstantiate):toInstantiate.name,'".');return _super.call(this,msg)||this}return __name(DependencyNotFoundForModuleError2,"DependencyNotFoundForModuleError"),DependencyNotFoundForModuleError2}(RediError),DependencyNotFoundError=function(_super){__extends$1$1(DependencyNotFoundError2,_super);function DependencyNotFoundError2(id){var _this=this,msg='Cannot find "'.concat(prettyPrintIdentifier(id),'" registered by any injector. The stack of dependencies is: "').concat(ResolvingStack.map(function(id2){return prettyPrintIdentifier(id2)}).join(" -> "),'".');return _this=_super.call(this,msg)||this,clearResolvingStack(),_this}return __name(DependencyNotFoundError2,"DependencyNotFoundError"),DependencyNotFoundError2}(RediError),DependencyCollection=function(){function DependencyCollection2(dependencies){var _this=this;this.dependencyMap=new Map,this.normalizeDependencies(dependencies).map(function(pair){return _this.add(pair[0],pair[1])})}return __name(DependencyCollection2,"DependencyCollection"),DependencyCollection2.prototype.add=function(ctorOrId,val){typeof val>"u"&&(val={useClass:ctorOrId,lazy:!1});var arr=this.dependencyMap.get(ctorOrId);typeof arr>"u"&&(arr=[],this.dependencyMap.set(ctorOrId,arr)),arr.push(val)},DependencyCollection2.prototype.delete=function(id){this.dependencyMap.delete(id)},DependencyCollection2.prototype.get=function(id,quantity){quantity===void 0&&(quantity=exports.Quantity.REQUIRED);var ret=this.dependencyMap.get(id);return checkQuantity(id,quantity,ret.length),retrieveQuantity(quantity,ret)},DependencyCollection2.prototype.has=function(id){return this.dependencyMap.has(id)},DependencyCollection2.prototype.append=function(dependencies){var _this=this;this.normalizeDependencies(dependencies).forEach(function(pair){return _this.add(pair[0],pair[1])})},DependencyCollection2.prototype.dispose=function(){this.dependencyMap.clear()},DependencyCollection2.prototype.normalizeDependencies=function(dependencies){return dependencies.map(function(dependency){var id=dependency[0],val;return isBareClassDependency(dependency)?val={useClass:dependency[0],lazy:!1}:val=dependency[1],[id,val]})},DependencyCollection2}(),ResolvedDependencyCollection=function(){function ResolvedDependencyCollection2(){this.resolvedDependencies=new Map}return __name(ResolvedDependencyCollection2,"ResolvedDependencyCollection"),ResolvedDependencyCollection2.prototype.add=function(id,val){var arr=this.resolvedDependencies.get(id);typeof arr>"u"&&(arr=[],this.resolvedDependencies.set(id,arr)),arr.push(val)},ResolvedDependencyCollection2.prototype.has=function(id){return this.resolvedDependencies.has(id)},ResolvedDependencyCollection2.prototype.delete=function(id){if(this.resolvedDependencies.has(id)){var things=this.resolvedDependencies.get(id);things.forEach(function(t){return isDisposable(t)?t.dispose():void 0}),this.resolvedDependencies.delete(id)}},ResolvedDependencyCollection2.prototype.get=function(id,quantity){quantity===void 0&&(quantity=exports.Quantity.REQUIRED);var ret=this.resolvedDependencies.get(id);if(!ret)throw new DependencyNotFoundError(id);return checkQuantity(id,quantity,ret.length),quantity===exports.Quantity.MANY?ret:ret[0]},ResolvedDependencyCollection2.prototype.dispose=function(){Array.from(this.resolvedDependencies.values()).forEach(function(items){items.forEach(function(item){return isDisposable(item)?item.dispose():void 0})}),this.resolvedDependencies.clear()},ResolvedDependencyCollection2}();function changeLookup(target,index2,lookUp){var descriptor=getDependencyByIndex(target,index2);descriptor.lookUp=lookUp}__name(changeLookup,"changeLookup");function lookupDecoratorFactoryProducer(lookUp){return __name(function DecoratorFactory(){return this instanceof DecoratorFactory?this:function(target,_key,index2){changeLookup(target,index2,lookUp)}},"DecoratorFactory")}__name(lookupDecoratorFactoryProducer,"lookupDecoratorFactoryProducer");var SkipSelf=lookupDecoratorFactoryProducer(exports.LookUp.SKIP_SELF),Self=lookupDecoratorFactoryProducer(exports.LookUp.SELF);function changeToSelf(target,index2,withNew){var descriptor=getDependencyByIndex(target,index2);descriptor.withNew=withNew}__name(changeToSelf,"changeToSelf");function withNewDecoratorFactoryProducer(withNew){return __name(function DecoratorFactory(){return this instanceof DecoratorFactory?this:function(target,_key,index2){changeToSelf(target,index2,withNew)}},"DecoratorFactory")}__name(withNewDecoratorFactoryProducer,"withNewDecoratorFactoryProducer");var WithNew=withNewDecoratorFactoryProducer(!0);function normalizeFactoryDeps(deps,startIndex){return startIndex===void 0&&(startIndex=0),deps?deps.map(function(dep,index2){if(index2+=startIndex,!Array.isArray(dep))return{paramIndex:index2,identifier:dep,quantity:exports.Quantity.REQUIRED,withNew:!1};var modifiers=dep.slice(0,dep.length-1),identifier=dep[dep.length-1],lookUp=void 0,quantity=exports.Quantity.REQUIRED,withNew=!1;return modifiers.forEach(function(modifier){if(modifier instanceof Self)lookUp=exports.LookUp.SELF;else if(modifier instanceof SkipSelf)lookUp=exports.LookUp.SKIP_SELF;else if(modifier instanceof Optional)quantity=exports.Quantity.OPTIONAL;else if(modifier instanceof Many)quantity=exports.Quantity.MANY;else if(modifier instanceof WithNew)withNew=!0;else throw new RediError("unknown dep modifier ".concat(modifier,"."))}),{paramIndex:index2,identifier,quantity,lookUp,withNew}}):[]}__name(normalizeFactoryDeps,"normalizeFactoryDeps");var runWhenIdle;(function(){if(typeof requestIdleCallback<"u"&&typeof cancelIdleCallback<"u")runWhenIdle=__name(function(runner,timeout){var handle=requestIdleCallback(runner,typeof timeout=="number"?{timeout}:void 0),disposed=!1;return function(){disposed||(disposed=!0,cancelIdleCallback(handle))}},"runWhenIdle");else{var dummyIdle_1=Object.freeze({didTimeout:!0,timeRemaining:__name(function(){return 15},"timeRemaining")});runWhenIdle=__name(function(runner){var handle=setTimeout(function(){return runner(dummyIdle_1)}),disposed=!1;return function(){disposed||(disposed=!0,clearTimeout(handle))}},"runWhenIdle")}})();var IdleValue=function(){function IdleValue2(executor){var _this=this;this.didRun=!1,this.selfExecutor=function(){try{_this.value=executor()}catch(err){_this.error=err}finally{_this.didRun=!0}},this.disposeCallback=runWhenIdle(function(){return _this.selfExecutor()})}return __name(IdleValue2,"IdleValue"),IdleValue2.prototype.hasRun=function(){return this.didRun},IdleValue2.prototype.dispose=function(){this.disposeCallback()},IdleValue2.prototype.getValue=function(){if(this.didRun||(this.dispose(),this.selfExecutor()),this.error)throw this.error;return this.value},IdleValue2}(),__extends$5=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),__assign$1=__name(function(){return __assign$1=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p])}return t},__assign$1.apply(this,arguments)},"__assign$1"),__spreadArray$1=__name(function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i<l2;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))},"__spreadArray$1"),MAX_RESOLUTIONS_QUEUED=300,NotInstantiatedSymbol=Symbol("$$NOT_INSTANTIATED_SYMBOL"),CircularDependencyError=function(_super){__extends$5(CircularDependencyError2,_super);function CircularDependencyError2(id){return _super.call(this,'Detecting cyclic dependency. The last identifier is "'.concat(prettyPrintIdentifier(id),'".'))||this}return __name(CircularDependencyError2,"CircularDependencyError"),CircularDependencyError2}(RediError),InjectorAlreadyDisposedError=function(_super){__extends$5(InjectorAlreadyDisposedError2,_super);function InjectorAlreadyDisposedError2(){return _super.call(this,"Injector cannot be accessed after it was disposed.")||this}return __name(InjectorAlreadyDisposedError2,"InjectorAlreadyDisposedError"),InjectorAlreadyDisposedError2}(RediError),AsyncItemReturnAsyncItemError=function(_super){__extends$5(AsyncItemReturnAsyncItemError2,_super);function AsyncItemReturnAsyncItemError2(id){return _super.call(this,'Async item "'.concat(prettyPrintIdentifier(id),'" returns another async item.'))||this}return __name(AsyncItemReturnAsyncItemError2,"AsyncItemReturnAsyncItemError"),AsyncItemReturnAsyncItemError2}(RediError),GetAsyncItemFromSyncApiError=function(_super){__extends$5(GetAsyncItemFromSyncApiError2,_super);function GetAsyncItemFromSyncApiError2(id){return _super.call(this,'Cannot get async item "'.concat(prettyPrintIdentifier(id),'" from sync api.'))||this}return __name(GetAsyncItemFromSyncApiError2,"GetAsyncItemFromSyncApiError"),GetAsyncItemFromSyncApiError2}(RediError),AddDependencyAfterResolutionError=function(_super){__extends$5(AddDependencyAfterResolutionError2,_super);function AddDependencyAfterResolutionError2(id){return _super.call(this,'Cannot add dependency "'.concat(prettyPrintIdentifier(id),'" after it is already resolved.'))||this}return __name(AddDependencyAfterResolutionError2,"AddDependencyAfterResolutionError"),AddDependencyAfterResolutionError2}(RediError),DeleteDependencyAfterResolutionError=function(_super){__extends$5(DeleteDependencyAfterResolutionError2,_super);function DeleteDependencyAfterResolutionError2(id){return _super.call(this,'Cannot dependency dependency "'.concat(prettyPrintIdentifier(id),'" after it is already resolved.'))||this}return __name(DeleteDependencyAfterResolutionError2,"DeleteDependencyAfterResolutionError"),DeleteDependencyAfterResolutionError2}(RediError),Injector=function(){function Injector2(dependencies,parent){parent===void 0&&(parent=null),this.parent=parent,this.children=[],this.resolutionOngoing=0,this.disposed=!1,this.dependencyCollection=new DependencyCollection(dependencies||[]),this.resolvedDependencyCollection=new ResolvedDependencyCollection,parent&&parent.children.push(this)}return __name(Injector2,"Injector"),Injector2.prototype.createChild=function(dependencies){return this._ensureInjectorNotDisposed(),new Injector2(dependencies,this)},Injector2.prototype.dispose=function(){this.children.forEach(function(c){return c.dispose()}),this.children.length=0,this.dependencyCollection.dispose(),this.resolvedDependencyCollection.dispose(),this.deleteSelfFromParent(),this.disposed=!0},Injector2.prototype.deleteSelfFromParent=function(){if(this.parent){var index2=this.parent.children.indexOf(this);index2>-1&&this.parent.children.splice(index2,1)}},Injector2.prototype.add=function(dependency){this._ensureInjectorNotDisposed();var identifierOrCtor=dependency[0],item=dependency[1];if(this.resolvedDependencyCollection.has(identifierOrCtor))throw new AddDependencyAfterResolutionError(identifierOrCtor);typeof item>"u"?this.dependencyCollection.add(identifierOrCtor):isAsyncDependencyItem(item)||isClassDependencyItem(item)||isValueDependencyItem(item)||isFactoryDependencyItem(item)?this.dependencyCollection.add(identifierOrCtor,item):this.resolvedDependencyCollection.add(identifierOrCtor,item)},Injector2.prototype.replace=function(dependency){this._ensureInjectorNotDisposed();var identifier=dependency[0];if(this.resolvedDependencyCollection.has(identifier))throw new AddDependencyAfterResolutionError(identifier);this.dependencyCollection.delete(identifier),dependency.length===1?this.dependencyCollection.add(identifier):this.dependencyCollection.add(identifier,dependency[1])},Injector2.prototype.delete=function(identifier){if(this._ensureInjectorNotDisposed(),this.resolvedDependencyCollection.has(identifier))throw new DeleteDependencyAfterResolutionError(identifier);this.dependencyCollection.delete(identifier)},Injector2.prototype.invoke=function(cb){for(var _this=this,args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];this._ensureInjectorNotDisposed();var accessor={get:__name(function(id,quantityOrLookup,lookUp){return _this._get(id,quantityOrLookup,lookUp)},"get")};return cb.apply(void 0,__spreadArray$1([accessor],args,!1))},Injector2.prototype.has=function(id){var _a13;return this.dependencyCollection.has(id)||((_a13=this.parent)===null||_a13===void 0?void 0:_a13.has(id))||!1},Injector2.prototype.get=function(id,quantityOrLookup,lookUp){this._ensureInjectorNotDisposed();var newResult=this._get(id,quantityOrLookup,lookUp);if(Array.isArray(newResult)&&newResult.some(function(r){return isAsyncHook(r)})||isAsyncHook(newResult))throw new GetAsyncItemFromSyncApiError(id);return newResult},Injector2.prototype._get=function(id,quantityOrLookup,lookUp,toSelf){var quantity=exports.Quantity.REQUIRED;if(quantityOrLookup===exports.Quantity.REQUIRED||quantityOrLookup===exports.Quantity.OPTIONAL||quantityOrLookup===exports.Quantity.MANY?quantity=quantityOrLookup:lookUp=quantityOrLookup,!toSelf){var cachedResult=this.getValue(id,quantity,lookUp);if(cachedResult!==NotInstantiatedSymbol)return cachedResult}return this.createDependency(id,quantity,lookUp,!toSelf)},Injector2.prototype.getAsync=function(id){this._ensureInjectorNotDisposed();var cachedResult=this.getValue(id,exports.Quantity.REQUIRED);if(cachedResult!==NotInstantiatedSymbol)return Promise.resolve(cachedResult);var newResult=this.createDependency(id,exports.Quantity.REQUIRED);return isAsyncHook(newResult)?newResult.whenReady():Promise.resolve(newResult)},Injector2.prototype.createInstance=function(ctor){for(var customArgs=[],_i=1;_i<arguments.length;_i++)customArgs[_i-1]=arguments[_i];return this._ensureInjectorNotDisposed(),this._resolveClassImpl.apply(this,__spreadArray$1([{useClass:ctor}],customArgs,!1))},Injector2.prototype._resolveDependency=function(id,item,shouldCache){shouldCache===void 0&&(shouldCache=!0);var result;pushResolvingStack(id);try{isValueDependencyItem(item)?result=this._resolveValueDependency(id,item):isFactoryDependencyItem(item)?result=this._resolveFactory(id,item,shouldCache):isClassDependencyItem(item)?result=this._resolveClass(id,item,shouldCache):isExistingDependencyItem(item)?result=this._resolveExisting(id,item):result=this._resolveAsync(id,item),popupResolvingStack()}catch(e){throw popupResolvingStack(),e}return result},Injector2.prototype._resolveExisting=function(id,item){var thing=this.get(item.useExisting);return this.resolvedDependencyCollection.add(id,thing),thing},Injector2.prototype._resolveValueDependency=function(id,item){var thing=item.useValue;return this.resolvedDependencyCollection.add(id,thing),thing},Injector2.prototype._resolveClass=function(id,item,shouldCache){var _this=this;shouldCache===void 0&&(shouldCache=!0),item.useClass;var thing;if(item.lazy){var idle_1=new IdleValue(function(){return _this._ensureInjectorNotDisposed(),_this._resolveClassImpl(item)});thing=new Proxy(Object.create(null),{get:__name(function(target,key){if(key in target)return target[key];if(key!=="whenReady"){var thing2=idle_1.getValue(),property=thing2[key];return typeof property!="function"||(property=property.bind(thing2),target[key]=property),property}},"get"),set:__name(function(_target,key,value){return idle_1.getValue()[key]=value,!0},"set")})}else thing=this._resolveClassImpl(item);return id&&shouldCache&&this.resolvedDependencyCollection.add(id,thing),thing},Injector2.prototype._resolveClassImpl=function(item){for(var _a13,extraParams=[],_i=1;_i<arguments.length;_i++)extraParams[_i-1]=arguments[_i];var ctor=item.useClass;this.markNewResolution(ctor);for(var declaredDependencies=getDependencies(ctor).sort(function(a,b){return a.paramIndex-b.paramIndex}).map(function(descriptor){return __assign$1(__assign$1({},descriptor),{identifier:normalizeForwardRef(descriptor.identifier)})}),resolvedArgs=[],_b2=0,declaredDependencies_1=declaredDependencies;_b2<declaredDependencies_1.length;_b2++){var dep=declaredDependencies_1[_b2];try{var thing_1=this._get(dep.identifier,dep.quantity,dep.lookUp,dep.withNew);resolvedArgs.push(thing_1)}catch(error){throw error instanceof DependencyNotFoundError?new DependencyNotFoundForModuleError(ctor,dep.identifier,dep.paramIndex):error}}var args=__spreadArray$1([],extraParams,!0),firstDependencyArgIndex=declaredDependencies.length>0?declaredDependencies[0].paramIndex:args.length;if(args.length!==firstDependencyArgIndex){console.warn("[redi]: Expect ".concat(firstDependencyArgIndex," custom parameter(s) of ").concat(prettyPrintIdentifier(ctor)," but get ").concat(args.length,"."));var delta=firstDependencyArgIndex-args.length;delta>0?args=__spreadArray$1(__spreadArray$1([],args,!0),new Array(delta).fill(void 0),!0):args=args.slice(0,firstDependencyArgIndex)}var thing=new(ctor.bind.apply(ctor,__spreadArray$1(__spreadArray$1([void 0],args,!1),resolvedArgs,!1)));return(_a13=item==null?void 0:item.onInstantiation)===null||_a13===void 0||_a13.call(item,thing),this.markResolutionCompleted(),thing},Injector2.prototype._resolveFactory=function(id,item,shouldCache){var _a13;this.markNewResolution(id);for(var declaredDependencies=normalizeFactoryDeps(item.deps),resolvedArgs=[],_i=0,declaredDependencies_2=declaredDependencies;_i<declaredDependencies_2.length;_i++){var dep=declaredDependencies_2[_i];try{var thing_2=this._get(dep.identifier,dep.quantity,dep.lookUp,dep.withNew);resolvedArgs.push(thing_2)}catch(error){throw error instanceof DependencyNotFoundError?new DependencyNotFoundForModuleError(id,dep.identifier,dep.paramIndex):error}}var thing=item.useFactory.apply(null,resolvedArgs);return shouldCache&&this.resolvedDependencyCollection.add(id,thing),this.markResolutionCompleted(),(_a13=item==null?void 0:item.onInstantiation)===null||_a13===void 0||_a13.call(item,thing),thing},Injector2.prototype._resolveAsync=function(id,item){var _this=this,asyncLoader={__symbol:AsyncHookSymbol,whenReady:__name(function(){return _this._resolveAsyncImpl(id,item)},"whenReady")};return asyncLoader},Injector2.prototype._resolveAsyncImpl=function(id,item){var _this=this;return item.useAsync().then(function(thing){var resolvedCheck=_this.getValue(id);if(resolvedCheck!==NotInstantiatedSymbol)return resolvedCheck;var ret;if(Array.isArray(thing)){var item_1=thing[1];if(isAsyncDependencyItem(item_1))throw new AsyncItemReturnAsyncItemError(id);ret=_this._resolveDependency(id,item_1)}else isCtor(thing)?ret=_this._resolveClassImpl({useClass:thing,onInstantiation:item.onInstantiation}):ret=thing;return _this.resolvedDependencyCollection.add(id,ret),ret})},Injector2.prototype.getValue=function(id,quantity,lookUp){var _this=this;quantity===void 0&&(quantity=exports.Quantity.REQUIRED);var onSelf=__name(function(){return _this.dependencyCollection.has(id)&&!_this.resolvedDependencyCollection.has(id)?NotInstantiatedSymbol:_this.resolvedDependencyCollection.get(id,quantity)},"onSelf"),onParent=__name(function(){return _this.parent?_this.parent.getValue(id,quantity):NotInstantiatedSymbol},"onParent");return lookUp===exports.LookUp.SKIP_SELF?onParent():lookUp===exports.LookUp.SELF||this.resolvedDependencyCollection.has(id)||this.dependencyCollection.has(id)?onSelf():onParent()},Injector2.prototype.createDependency=function(id,quantity,lookUp,shouldCache){var _this=this;quantity===void 0&&(quantity=exports.Quantity.REQUIRED),shouldCache===void 0&&(shouldCache=!0);var onSelf=__name(function(){var registrations=_this.dependencyCollection.get(id,quantity),ret=null;return Array.isArray(registrations)?ret=registrations.map(function(dependencyItem){return _this._resolveDependency(id,dependencyItem,shouldCache)}):registrations&&(ret=_this._resolveDependency(id,registrations,shouldCache)),ret},"onSelf"),onParent=__name(function(){if(_this.parent)return _this.parent.createDependency(id,quantity,void 0,shouldCache);if(quantity===exports.Quantity.OPTIONAL)return null;throw pushResolvingStack(id),new DependencyNotFoundError(id)},"onParent");return lookUp===exports.LookUp.SKIP_SELF?onParent():id===Injector2?this:this.dependencyCollection.has(id)?onSelf():onParent()},Injector2.prototype.markNewResolution=function(id){if(this.resolutionOngoing+=1,this.resolutionOngoing>=MAX_RESOLUTIONS_QUEUED)throw new CircularDependencyError(id)},Injector2.prototype.markResolutionCompleted=function(){this.resolutionOngoing-=1},Injector2.prototype._ensureInjectorNotDisposed=function(){if(this.disposed)throw new InjectorAlreadyDisposedError},Injector2}();function setDependencies(registerTarget,deps,startIndex){startIndex===void 0&&(startIndex=0);var normalizedDescriptors=normalizeFactoryDeps(deps,startIndex);normalizedDescriptors.forEach(function(descriptor){setDependency(registerTarget,descriptor.identifier,descriptor.paramIndex,descriptor.quantity,descriptor.lookUp)})}__name(setDependencies,"setDependencies");var globalObject$1=typeof globalThis<"u"&&globalThis||typeof window<"u"&&window||typeof global<"u"&&global,__REDI_GLOBAL_LOCK__="REDI_GLOBAL_LOCK",isNode$1=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;globalObject$1[__REDI_GLOBAL_LOCK__]?isNode$1||console.error(`[redi]: You are loading scripts of redi more than once! This may cause undesired behavior in your application.
5
5
  Maybe your dependencies added redi as its dependency and bundled redi to its dist files. Or you import different versions of redi.
6
- For more info please visit our website: https://redi.wendell.fun/en-US/docs/debug#import-scripts-of-redi-more-than-once`):Es[Rs]=!0;var Cs="REDI_CONTEXT_LOCK",Vu=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,Is=typeof globalThis<"u"&&globalThis||typeof window<"u"&&window||typeof global<"u"&&global;Is[Cs]?Vu||console.error(`[redi]: "RediContext" is already created. You may import "RediContext" from different paths. Use "import { RediContext } from '@wendellhu/redi/react-bindings'; instead."`):Is[Cs]=!0;var un=st.createContext({injector:null});un.displayName="RediContext";var Fr=un.Provider,hi=un.Consumer,Ku=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),zu=function(e){Ku(n,e);function n(){return e.call(this,"Using dependency injection outside of a RediContext.")||this}return n}(Le);function di(){var e=st.useContext(un);if(!e.injector)throw new zu;return e.injector}function Yu(e,n,t){var r=di();return st.useMemo(function(){return r.get(e,n,t)},[e,n,t])}var xn=function(){return xn=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++){n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},xn.apply(this,arguments)};function Xu(e){var n=e.children,t=e.dependencies,r=st.useRef(null);return st.useEffect(function(){return function(){var s;return(s=r.current)===null||s===void 0?void 0:s.dispose()}},[]),st.createElement(hi,null,function(s){var o;return r.current?o=r.current:(o=s.injector?s.injector.createChild(t):new pt(t),r.current=o),st.createElement(Fr,{value:{injector:o}},n)})}function Qu(e,n){return function(r){return st.createElement(Fr,{value:{injector:n}},st.createElement(e,xn({},r)))}}function qu(e,n){return function(r){return st.createElement(Xu,{dependencies:n},st.createElement(e,xn({},r)))}}var Zu=function(){var e=function(n,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},e(n,t)};return function(n,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(n,t);function r(){this.constructor=n}n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ju=function(e){Zu(n,e);function n(t){return e.call(this,'You should make "RediContext" as '.concat(t.constructor.name,"'s default context type. ")+"If you want to use multiple context, please check this on React doc site. https://reactjs.org/docs/context.html#classcontexttype")||this}return n}(Le);function ec(e,n,t){return function(){return{get:function(){var r=this,s=r.context;if(!s||!s.injector)throw new Ju(r);var o=s.injector,i=o.get(e,n||exports.Quantity.REQUIRED,t);return i}}}}var tc=function(e,n,t){if(t||arguments.length===2)for(var r=0,s=n.length,o;r<s;r++)(o||!(r in n))&&(o||(o=Array.prototype.slice.call(n,0,r)),o[r]=n[r]);return e.concat(o||Array.prototype.slice.call(n))};function fi(e,n){var t=e instanceof Y.BehaviorSubject&&typeof n>"u"?e.getValue():n,r=Pe.useState(t),s=r[0],o=r[1];return Pe.useEffect(function(){var i=e.subscribe(function(a){return o(a)});return function(){return i.unsubscribe()}},[e]),s}function vs(e){return typeof e=="function"?e():e}function nc(e,n,t,r){if(typeof e=="function"&&!r)throw new Le("Expected deps to be provided when observable is a function!");var s=Pe.useRef(null),o=Pe.useRef(!1),i=Pe.useMemo(function(){return e},tc([],typeof r<"u"?r:[e],!0)),a=Pe.useState(0);a[0];var l=a[1],h=Pe.useRef(function(){var c;if(i){var u=vs(i).subscribe(function(d){o.current=!0,c=d});u.unsubscribe()}return c!=null?c:n}());if(Pe.useEffect(function(){var c=null;return i&&(s.current=vs(i),c=s.current.subscribe(function(u){h.current=u,l(function(d){return d+1})})),function(){return c==null?void 0:c.unsubscribe()}},[i]),t&&!o.current)throw new Error("Expect `shouldHaveSyncValue` but not getting a sync value!");return h.current}function rc(e){var n=Pe.useState(0),t=n[1];Pe.useEffect(function(){var r=e.subscribe(function(){return t(function(s){return s+1})});return function(){return r.unsubscribe()}},[])}var vr=new WeakMap;function sc(e,n){var t=Pe.useRef(void 0),r=fi(e,n),s=Pe.useMemo(function(){return Pe.createContext(r)},[e]),o=Pe.useCallback(function(i){return Pe.createElement(s.Provider,{value:r},i.children)},[e,r]);return t.current!==e&&(t.current&&vr.delete(t.current),t.current=e,vr.set(e,s)),{Provider:o,value:r}}function oc(e){var n=vr.get(e);if(!n)throw new Le("try to read context value but no ancestor component subscribed it.");return Pe.useContext(n)}async function _i(e){for(const[n,t]of e.entries())try{if(!await t())return{index:n,result:!1}}catch(r){return{index:n,result:!1,error:r}}return{result:!0,index:-1}}function gi(e){for(const[n,t]of e.entries())try{if(!t())return{index:n,result:!1}}catch(r){return{index:n,result:!1,error:r}}return{result:!0,index:-1}}const cn=Ve("univer.context-service");class pi extends Ae{constructor(){super(...arguments);_(this,"_contextChanged$",new Y.Subject);_(this,"contextChanged$",this._contextChanged$.asObservable());_(this,"_contextMap",new Map)}dispose(){super.dispose(),this._contextChanged$.complete()}getContextValue(t){var r;return(r=this._contextMap.get(t))!=null?r:!1}setContextValue(t,r){this._contextMap.set(t,r),this._contextChanged$.next({[t]:r})}subscribeContextValue$(t){return new Y.Observable(r=>{const s=this._contextChanged$.pipe(Y.filter(o=>typeof o[t]<"u")).subscribe(o=>r.next(o[t]));return this._contextMap.has(t)&&r.next(this._contextMap.get(t)),()=>s.unsubscribe()})}}var mi=(e=>(e[e.SILENT=0]="SILENT",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.VERBOSE=4]="VERBOSE",e))(mi||{});const St=Ve("univer.log");class Ei extends Ae{constructor(){super(...arguments);_(this,"_logLevel",3)}debug(...t){this._logLevel>=4&&this._log(console.debug,...t)}log(...t){this._logLevel>=3&&this._log(console.log,...t)}warn(...t){this._logLevel>=2&&this._log(console.warn,...t)}error(...t){this._logLevel>=1&&this._log(console.error,...t)}setLogLevel(t){this._logLevel=t}_log(t,...r){const s=r[0];/^\[(.*?)\]/g.test(s)?t(`\x1B[97;104m${s}\x1B[0m`,...r.slice(1)):t(...r)}}var ic=Object.defineProperty,ac=Object.getOwnPropertyDescriptor,lc=(e,n,t,r)=>{for(var s=r>1?void 0:r?ac(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&ic(n,t,s),s},Os=(e,n)=>(t,r)=>n(t,r,e),hn=(e=>(e[e.COMMAND=0]="COMMAND",e[e.OPERATION=1]="OPERATION",e[e.MUTATION=2]="MUTATION",e))(hn||{});const dn=Ve("anywhere.command-service");class uc{constructor(){_(this,"_commands",new Map);_(this,"_commandTypes",new Map)}registerCommand(n){if(this._commands.has(n.id))throw new Error(`[CommandRegistry]: command "${n.id}" has been registered before.`);return this._commands.set(n.id,n),this._commandTypes.set(n.id,n.type),Ne(()=>{var t;this._commands.delete(n.id),this._commandTypes.delete(n.id),(t=n.onDispose)==null||t.call(n)})}hasCommand(n){return this._commands.has(n)}getCommand(n){return this._commands.has(n)?[this._commands.get(n)]:null}getCommandType(n){return this._commandTypes.get(n)}}const Ri={id:"nil",type:0,handler:()=>!0};exports.CommandService=class extends Ae{constructor(t,r){super();_(this,"_commandRegistry");_(this,"_beforeCommandExecutionListeners",[]);_(this,"_commandExecutedListeners",[]);_(this,"_multiCommandDisposables",new Map);_(this,"_commandExecutingLevel",0);_(this,"_commandExecutionStack",[]);this._injector=t,this._logService=r,this._commandRegistry=new uc,this._registerCommand(Ri)}dispose(){super.dispose(),this._commandExecutedListeners.length=0,this._beforeCommandExecutionListeners.length=0}hasCommand(t){return this._commandRegistry.hasCommand(t)}registerCommand(t){return this._registerCommand(t)}registerMultipleCommand(t){return this._registerMultiCommand(t)}beforeCommandExecuted(t){if(this._beforeCommandExecutionListeners.indexOf(t)===-1)return this._beforeCommandExecutionListeners.push(t),Ne(()=>{const r=this._beforeCommandExecutionListeners.indexOf(t);this._beforeCommandExecutionListeners.splice(r,1)});throw new Error("[CommandService]: could not add a listener twice.")}onCommandExecuted(t){if(this._commandExecutedListeners.indexOf(t)===-1)return this._commandExecutedListeners.push(t),Ne(()=>{const r=this._commandExecutedListeners.indexOf(t);this._commandExecutedListeners.splice(r,1)});throw new Error("[CommandService]: could not add a listener twice.")}async executeCommand(t,r,s){try{const o=this._commandRegistry.getCommand(t);if(o){const[i]=o,a={id:i.id,type:i.type,params:r},l=this._pushCommandExecutionStack(a);this._beforeCommandExecutionListeners.forEach(c=>c(a,s));const h=await this._execute(i,r,s);return this._commandExecutedListeners.forEach(c=>c(a,s)),l.dispose(),h}throw new Error(`[CommandService]: command "${t}" is not registered.`)}catch(o){throw this._logService.error(o),o}}syncExecuteCommand(t,r,s){var i;const o=this._commandRegistry.getCommand(t);if(o){const[a]=o,l={id:a.id,type:a.type,params:r};if(a.type===2){const u=Kl(this._commandExecutionStack,d=>d.type===0);u&&(l.params=(i=l.params)!=null?i:{},l.params.trigger=u.id)}const h=this._pushCommandExecutionStack(l);this._beforeCommandExecutionListeners.forEach(u=>u(l,s));const c=this._syncExecute(a,r,s);return this._commandExecutedListeners.forEach(u=>u(l,s)),h.dispose(),c}throw new Error(`[CommandService]: command "${t}" is not registered.`)}_pushCommandExecutionStack(t){return this._commandExecutionStack.push(t),Ne(()=>Bn(this._commandExecutionStack,t))}_registerCommand(t){return this._commandRegistry.registerCommand(t)}_registerMultiCommand(t){const r=this._commandRegistry.getCommand(t.id);let s;if(r){if(r[0].multi!==!0)throw new Error("Command has registered as a single command.");s=r[0]}else{const i=new Mr;s=new cc(t.id),i.add(this._commandRegistry.registerCommand(s)),i.add(Ne(()=>{this._multiCommandDisposables.delete(t.id)})),this._multiCommandDisposables.set(t.id,i)}const o=s.registerImplementation(t);return Ne(()=>{var i;o.dispose(),s.hasImplementations()||(i=this._multiCommandDisposables.get(t.id))==null||i.dispose()})}async _execute(t,r,s){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(this._commandExecutingLevel,0))}executing command "${t.id}"`),this._commandExecutingLevel++;let o;try{o=await this._injector.invoke(t.handler,r,s),this._commandExecutingLevel--}catch(i){throw o=!1,this._commandExecutingLevel=0,i}return o}_syncExecute(t,r,s){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(0,this._commandExecutingLevel))}executing command "${t.id}".`),this._commandExecutingLevel++;let o;try{if(o=this._injector.invoke(t.handler,r,s),o instanceof Promise)throw new TypeError("[CommandService]: Command handler should not return a promise.");this._commandExecutingLevel--}catch(i){throw o=!1,this._commandExecutingLevel=0,i}return o}};exports.CommandService=lc([Os(0,it(pt)),Os(1,St)],exports.CommandService);class cc{constructor(n){_(this,"name");_(this,"multi",!0);_(this,"type",0);_(this,"priority",0);_(this,"_implementations",[]);_(this,"handler",async(n,t)=>{if(!this._implementations.length)return!1;const r=n.get(St),s=n.get(cn),o=n.get(pt);for(const i of this._implementations){const a=i.command.preconditions;if((!a||a&&a(s))&&(r.debug("[MultiCommand]",`executing implementation "${i.command.name}".`),await o.invoke(i.command.handler,t)))return!0}return!1});this.id=n,this.name=n}registerImplementation(n){const t={command:n};return this._implementations.push(t),this._implementations.sort((r,s)=>s.command.priority-r.command.priority),Ne(()=>{var s;const r=this._implementations.indexOf(t);this._implementations.splice(r,1),(s=n.onDispose)==null||s.call(n)})}hasImplementations(){return this._implementations.length>0}}function Hr(e,n,t){const r=e.map(s=>()=>n.syncExecuteCommand(s.id,s.params,t));return gi(r)}function hc(e,n,t){const r=e.map(s=>()=>n.executeCommand(s.id,s.params,t));return _i(r)}function Ci(e){return new Y.Observable(n=>{const t=e((...r)=>n.next(r));return()=>t==null?void 0:t.dispose()})}function Ii(e){return function(t){return new Y.Observable(r=>(t.subscribe({next:s=>{r.next(s),e(s)&&r.complete()},complete:()=>r.complete(),error:s=>r.error(s)}),()=>r.unsubscribe()))}}const dc=e=>new Promise(n=>{Y.merge(Ci(e.onCommandExecuted.bind(e)).pipe(Cn.filter(([t])=>t.type===hn.MUTATION)),Y.timer(300)).pipe(Cn.debounceTime(16),Cn.first()).subscribe(()=>{n()})});var Ze=(e=>(e[e.UNDEFINED=0]="UNDEFINED",e[e.OK=1]="OK",e[e.INTERNAL_ERROR=2]="INTERNAL_ERROR",e[e.PERMISSION_DENIED=3]="PERMISSION_DENIED",e[e.NOT_FOUND=4]="NOT_FOUND",e[e.UNAUTHENTICATED=5]="UNAUTHENTICATED",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.INVALID_ARGUMENT=7]="INVALID_ARGUMENT",e[e.TOO_MANY_REQUESTS=8]="TOO_MANY_REQUESTS",e[e.COMPLETION_FINISHED=9]="COMPLETION_FINISHED",e[e.CHANGESET_REVISION_CONFILICT=5001]="CHANGESET_REVISION_CONFILICT",e[e.SNAPSHOT_INVALID_SNAPSHOT=6001]="SNAPSHOT_INVALID_SNAPSHOT",e[e.SNAPSHOT_HAS_BEEN_REMOVED=6002]="SNAPSHOT_HAS_BEEN_REMOVED",e[e.APPLY_REJECT=7001]="APPLY_REJECT",e[e.APPLY_NON_SEQUENTIAL_REVISION=7002]="APPLY_NON_SEQUENTIAL_REVISION",e[e.APPLY_REVISION_CONFILICT=7003]="APPLY_REVISION_CONFILICT",e[e.APPLY_PERMISSION_DENIED=7004]="APPLY_PERMISSION_DENIED",e[e.CONNECTOR_DATA_TOO_LARGE=8001]="CONNECTOR_DATA_TOO_LARGE",e[e.LICENSE_MAX_UNITS_EXCEEDED=9001]="LICENSE_MAX_UNITS_EXCEEDED",e[e.LICENSE_MAX_MEMBERS_PER_UNIT_EXCEEDED=9002]="LICENSE_MAX_MEMBERS_PER_UNIT_EXCEEDED",e[e.LICENSE_IMPORT_SIZE_EXCEEDED=9003]="LICENSE_IMPORT_SIZE_EXCEEDED",e[e.LICENSE_EXPORT_SIZE_EXCEEDED=9004]="LICENSE_EXPORT_SIZE_EXCEEDED",e[e.LICENSE_DISTRO_REJECTED=9005]="LICENSE_DISTRO_REJECTED",e[e.YUUMI_UNABLE_LOAD_URL=10001]="YUUMI_UNABLE_LOAD_URL",e[e.YUUMI_URL_COL_OUT_OF_RANGE=10002]="YUUMI_URL_COL_OUT_OF_RANGE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e))(Ze||{});function vi(e){return!!(e&&e.code&&e.code!==Ze.OK&&e.code!=="OK")}var J=(e=>(e[e.UNIVER_UNKNOWN=0]="UNIVER_UNKNOWN",e[e.UNIVER_DOC=1]="UNIVER_DOC",e[e.UNIVER_SHEET=2]="UNIVER_SHEET",e[e.UNIVER_SLIDE=3]="UNIVER_SLIDE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e))(J||{}),Oi=(e=>(e[e.SomeCollaborator=0]="SomeCollaborator",e[e.AllCollaborator=1]="AllCollaborator",e[e.OneSelf=2]="OneSelf",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e))(Oi||{}),je=(e=>(e[e.Reader=0]="Reader",e[e.Editor=1]="Editor",e[e.Owner=2]="Owner",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e))(je||{}),Nn=(e=>(e[e.Unkonwn=0]="Unkonwn",e[e.Workbook=1]="Workbook",e[e.Worksheet=2]="Worksheet",e[e.SelectRange=3]="SelectRange",e[e.Document=4]="Document",e[e.Slide=5]="Slide",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED",e))(Nn||{});class Vn extends Ae{}class jr{constructor(){_(this,"_data",[])}static create(){return new jr}add(n){this._data.indexOf(n)>-1||this._data.push(n)}delete(n){const t=this._data.indexOf(n);this._data.splice(t,1)}getData(){return this._data}}class $r{constructor(){_(this,"_data",new Map)}static create(){return new $r}add(n,t){this._data.has(n)||this._data.set(n,t)}delete(n){this._data.delete(n)}getData(){return this._data}}var Si=(e=>(e[e.PARAGRAPH=0]="PARAGRAPH",e[e.SECTION_BREAK=1]="SECTION_BREAK",e[e.TABLE=2]="TABLE",e[e.TABLE_ROW=3]="TABLE_ROW",e[e.TABLE_CELL=4]="TABLE_CELL",e[e.CUSTOM_BLOCK=5]="CUSTOM_BLOCK",e))(Si||{}),gt=(e=>(e.PARAGRAPH="\r",e.SECTION_BREAK=`
7
- `,e.TABLE_START="",e.TABLE_ROW_START="\x1B",e.TABLE_CELL_START="",e.TABLE_CELL_END="",e.TABLE_ROW_END="",e.TABLE_END="",e.CUSTOM_RANGE_START="",e.CUSTOM_RANGE_END="",e.COLUMN_BREAK="\v",e.PAGE_BREAK="\f",e.DOCS_END="\0",e.TAB=" ",e.CUSTOM_BLOCK="\b",e.LETTER="",e.SPACE=" ",e))(gt||{}),Pn=(e=>(e.BULLET_LIST="BULLET_LIST",e.ORDER_LIST="ORDER_LIST",e))(Pn||{});const fc={BULLET_LIST:{listType:"BULLET_LIST",nestingLevel:[{bulletAlignment:Rt.START,glyphFormat:" %0",textStyle:{fs:12},startNumber:0,glyphSymbol:"●",hanging:{v:21},indentStart:{v:21}},{bulletAlignment:Rt.START,glyphFormat:" %1",textStyle:{fs:12},startNumber:0,glyphSymbol:"■",hanging:{v:21},indentStart:{v:42}},{bulletAlignment:Rt.START,glyphFormat:" %1",textStyle:{fs:12},startNumber:0,glyphSymbol:"◆",hanging:{v:21},indentStart:{v:63}}]},ORDER_LIST:{listType:"ORDER_LIST",nestingLevel:[{bulletAlignment:Rt.START,glyphFormat:" %1.",textStyle:{fs:12},startNumber:0,glyphType:Jt.DECIMAL,hanging:{v:21},indentStart:{v:21}},{bulletAlignment:Rt.START,glyphFormat:" %1.%2)",textStyle:{fs:12},startNumber:0,glyphType:Jt.DECIMAL,hanging:{v:21},indentStart:{v:42}},{bulletAlignment:Rt.START,glyphFormat:" %1.%2.%3.",textStyle:{fs:12},startNumber:0,glyphType:Jt.DECIMAL,hanging:{v:21},indentStart:{v:63}}]}};function Wr(e){const n=[];for(const t of e){const{ed:r,ts:s}=t;if(t.sId===void 0&&delete t.sId,x.isEmptyObject(s)&&t.sId==null)continue;if(n.length===0){n.push(t);continue}const o=n.pop();Ho(t,o)&&x.hasIntersectionBetweenTwoRanges(o.st,o.ed,t.st,t.ed)?n.push({...t,st:o.st,ed:r}):n.push(o,t)}return n}function Ni(e,n,t,r){var h;const{textRuns:s}=e;if(s==null)return;const o=[],i=s.length;let a=!1;const l=(h=n.textRuns)!=null?h:[];if(l.length)for(const c of l)c.st+=r,c.ed+=r;for(let c=0;c<i;c++){const u=s[c],d=s[c+1],{st:f,ed:p}=u;if(p<r)o.push(u);else if(r>=f&&r<=p){if(d&&d.st===d.ed&&r===d.st){o.push(u);continue}if(a)u.st+=t,u.ed+=t,o.push(u);else{a=!0,u.ed+=t;const m=[];if(l.length){const S={...u,st:f,ed:l[0].st};S.ed>S.st&&m.push(S),m.push(...l);const y=l[l.length-1],ee={...u,st:y.ed,ed:p+t};ee.ed>ee.st&&m.push(ee)}else m.push(u);o.push(...m)}}else u.st+=t,u.ed+=t,a||(a=!0,o.push(...l)),o.push(u)}a||(a=!0,o.push(...l)),e.textRuns=Wr(o)}function Br(e,n,t,r){const{paragraphs:s}=e;if(s==null)return;const{paragraphs:o,dataStream:i}=n,a=[];let l=-1;for(let c=0,u=s.length;c<u;c++){const d=s[c],{startIndex:f}=d;f>=r&&(d.startIndex+=t),l===-1&&f>=r&&(l=c),a.push(d.startIndex)}let h=-1;if(o){for(let c=0,u=o.length;c<u;c++){const d=o[c];d.startIndex+=r;const f=d.startIndex;h=a.indexOf(f)}if(i===gt.PARAGRAPH&&o.length===1){const c=s[l],u=o[0],d=c.paragraphStyle,f=c.bullet;c.paragraphStyle=u.paragraphStyle,c.bullet=u.bullet,u.paragraphStyle=d,u.bullet=f}h!==-1&&s.splice(h,1),s.push(...o),s.sort(kt("startIndex"))}}function _c(e,n,t,r){const{sectionBreaks:s}=e;if(s==null)return;for(let i=0,a=s.length;i<a;i++){const l=s[i],{startIndex:h}=l;h>=r&&(l.startIndex+=t)}const o=n.sectionBreaks;if(o){for(let i=0,a=o.length;i<a;i++){const l=o[i];l.startIndex+=r}s.push(...o),s.sort(kt("startIndex"))}}function wi(e,n,t,r){const{customBlocks:s}=e;if(s==null)return;for(let i=0,a=s.length;i<a;i++){const l=s[i],{startIndex:h}=l;h>=r&&(l.startIndex+=t)}const o=n.customBlocks;if(o){for(let i=0,a=o.length;i<a;i++){const l=o[i];l.startIndex+=r}s.push(...o),s.sort(kt("startIndex"))}}function bi(e,n,t,r){const{tables:s}=e;if(s==null)return;for(let i=0,a=s.length;i<a;i++){const l=s[i],{startIndex:h,endIndex:c}=l;h>r?(l.startIndex+=t,l.endIndex+=t):c>=r-1&&(l.endIndex+=t)}const o=n.tables;if(o){for(let i=0,a=o.length;i<a;i++){const l=o[i];l.startIndex+=r,l.endIndex+=r}s.push(...o),s.sort(kt("startIndex"))}}function Ai(e,n,t,r){e.customRanges||(e.customRanges=[]);const{customRanges:s}=e,o={};for(let l=0,h=s.length;l<h;l++){const c=s[l];o[c.rangeId]=c;const{startIndex:u,endIndex:d}=c;u>=r?(c.startIndex+=t,c.endIndex+=t):d>r-1&&(c.endIndex+=t)}if(s.find(l=>l.startIndex>r&&l.endIndex<r))return;const a=[];if(n.customRanges){for(let l=0,h=n.customRanges.length;l<h;l++){const c=n.customRanges[l],u=o[c.rangeId];if(c.startIndex+=r,c.endIndex+=r,u){if(u.startIndex<=c.startIndex&&u.endIndex>=c.endIndex||e.dataStream[u.startIndex]===gt.CUSTOM_RANGE_START&&e.dataStream[u.endIndex]===gt.CUSTOM_RANGE_END)continue;if(e.dataStream[u.startIndex]===gt.CUSTOM_RANGE_START){u.endIndex=c.endIndex;continue}if(e.dataStream[u.endIndex]===gt.CUSTOM_RANGE_END){u.startIndex=c.startIndex;continue}}a.push(c)}s.push(...a),s.sort(kt("startIndex"))}}function gc(e){e.sort((r,s)=>r.startIndex-s.startIndex);const n=[];let t=e[0];for(let r=1;r<e.length;r++)t.endIndex+1>=e[r].startIndex?t.endIndex=Math.max(t.endIndex,e[r].endIndex):(n.push(t),t=e[r]);return n.push(t),n}function pc(e){const n={};for(let t=0,r=e.length;t<r;t++){const s=e[t],o=n[s.id];n[s.id]=[...o!=null?o:[],s]}return Object.keys(n).forEach(t=>{const r=n[t],s=gc(r);n[t]=s}),Object.values(n).flat()}function Ti(e,n,t,r){e.customDecorations||(e.customDecorations=[]);const{customDecorations:s}=e;if(t>0)for(let o=0,i=s.length;o<i;o++){const a=s[o],{startIndex:l,endIndex:h}=a;l>=r?(a.startIndex+=t,a.endIndex+=t):h>r-1&&(a.endIndex+=t)}if(n.customDecorations){const o=[];for(let i=0,a=n.customDecorations.length;i<a;i++){const l=n.customDecorations[i];o.push(l),l.startIndex+=r,l.endIndex+=r}s.push(...o),e.customDecorations=pc(s),e.customDecorations.sort(kt("startIndex"))}}function yi(e,n,t){var a;const{textRuns:r}=e,s=t,o=t+n,i=[];if(s===o&&(r!=null&&r.find(l=>l.st===t&&l.ed===t))){const l=r.find(h=>h.st===t&&h.ed===t);return i.push({...l,st:l.st-t,ed:l.ed-t}),e.textRuns=(a=e.textRuns)==null?void 0:a.filter(h=>h!==l),i}if(r){const l=[];for(let h=0,c=r.length;h<c;h++){const u=r[h],{st:d,ed:f}=u;if(s<=d&&o>=f){i.push({...u,st:d-s,ed:f-s});continue}else d<=s&&f>=o?(i.push({...u,st:s-s,ed:o-s}),u.ed-=n):s>=d&&s<f?(i.push({...u,st:s-s,ed:f-s}),u.ed=s):o>d&&o<=f?(i.push({...u,st:d-s,ed:o-s}),u.st=o-n,u.ed-=n):d>=o&&(u.st-=n,u.ed-=n);l.push(u)}e.textRuns=l}return i.length===0&&i.push({st:0,ed:n,ts:{}}),i}function Di(e,n,t){const{paragraphs:r}=e,s=t,o=t+n,i=[];if(r){const a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l],{startIndex:u}=c;if(u>=s&&u<o){i.push({...c,startIndex:u-t});continue}else u>=o&&(c.startIndex-=n);a.push(c)}e.paragraphs=a}return i}function Mi(e,n,t){const{sectionBreaks:r}=e,s=t,o=t+n-1,i=[];if(r){const a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l],{startIndex:u}=c;if(u>=s&&u<=o){i.push({...c,startIndex:u-t});continue}else u>o&&(c.startIndex-=n);a.push(c)}e.sectionBreaks=a}return i}function Ui(e,n,t){const{customBlocks:r}=e,s=t,o=t+n-1,i=[];if(r){const a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l],{startIndex:u}=c;if(u>=s&&u<=o){i.push({...c,startIndex:u-t});continue}else u>o&&(c.startIndex-=n);a.push(c)}e.customBlocks=a}return i}function Li(e,n,t){const{tables:r}=e,s=t,o=t+n-1,i=[];if(r){const a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l],{startIndex:u,endIndex:d}=c;if(s<=u&&o>=d){i.push({...c,startIndex:u-t,endIndex:d-t});continue}else if(u<=s&&d>=o){const f=Wn(u,d,s,o);c.startIndex=f[0],c.endIndex=f[1]}else o<u&&(c.startIndex-=n,c.endIndex-=n);a.push(c)}e.tables=a}return i}function xi(e,n,t){const{customRanges:r}=e,s=t,o=t+n-1,i=[];if(r){const a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l],{startIndex:u,endIndex:d}=c;if(s<=u&&o>=u){i.push({...c,startIndex:u-t,endIndex:d-t});continue}else if(u<=s&&d>=o){const f=Wn(u,d,s,o);c.startIndex=f[0],c.endIndex=f[1]}else o<u&&(c.startIndex-=n,c.endIndex-=n);a.push(c)}e.customRanges=a}return i}function Pi(e,n,t,r=!0){const{customDecorations:s}=e,o=t,i=t+n-1,a=[];if(s){const l=[];for(let h=0,c=s.length;h<c;h++){const u=s[h],{startIndex:d,endIndex:f}=u;if(d>=o&&f<=i){a.push(u);continue}else if(Math.max(o,d)<=Math.min(i,f)){const p=Wn(d,f,o,i);u.startIndex=p[0],u.endIndex=p[1]}else i<d&&r&&(u.startIndex-=n,u.endIndex-=n);l.push(u)}e.customDecorations=l}return a}function mc(e,n,t,r,s){const o=Ec(e,n,t,r,s),i=Rc(e,n,t,r,s),a=Cc(e,n,t,r,s),l=Ic(e,n,t,r,s),h=vc(e,n,t,r,s),c=Oc(e,n,t,r,s),u=Sc(e,n,t,r,s);return{dataStream:"",textRuns:o,paragraphs:i,sectionBreaks:a,customBlocks:l,tables:h,customRanges:c,customDecorations:u}}function Ec(e,n,t,r,s){const{textRuns:o}=e,{textRuns:i}=n;if(o==null||i==null)return;const a=yi(e,t,r);if(s!==ke.REPLACE){const l=ki(i,a,s);n.textRuns=l}return Ni(e,n,t,r),a}function ki(e,n,t){if(n.length===0)return e;e=x.deepClone(e),n=x.deepClone(n);const r=[],s=e.length,o=n.length;let i=0,a=0,l=null;function h(){return l?(r.push(l),l=null,!0):!1}for(;i<s&&a<o;){const{st:f,ed:p,ts:m}=e[i],{st:S,ed:y,ts:ee,sId:ge}=n[a];let ce;if(t===ke.COVER?ce={...ee,...m}:ce={...m,...ee},p<S)h()||r.push(e[i]),i++;else if(y<f)h()||r.push(n[a]),a++;else{const E={st:Math.min(f,S),ed:Math.max(f,S),ts:f<S?{...m}:{...ee},sId:f<S?void 0:ge};E.ed>E.st&&r.push(E),r.push({st:Math.max(f,S),ed:Math.min(p,y),ts:ce,sId:ge}),p<y?(i++,n[a].st=p,n[a].st===n[a].ed&&a++):(a++,e[i].st=y,e[i].st===e[i].ed&&i++);const v={st:Math.min(p,y),ed:Math.max(p,y),ts:p<y?{...ee}:{...m},sId:p<y?ge:void 0};l=v.ed>v.st?v:null}}h();const c=r[r.length-1],u=e[s-1],d=n[o-1];return c.ed!==Math.max(u.ed,d.ed)&&(u.ed>d.ed?r.push(u):r.push(d)),Wr(r)}function Rc(e,n,t,r,s){const{paragraphs:o}=e,{paragraphs:i}=n;if(o==null||i==null)return;const a=Di(e,t,r);if(s!==ke.REPLACE){const l=[];for(const h of i){const{startIndex:c,paragraphStyle:u,bullet:d}=h;let f=[];for(const p of a){const{startIndex:m,paragraphStyle:S,bullet:y}=p;let ee,ge;if(s===ke.COVER?(ee={...S,...u},ge={listId:"",listType:Pn.BULLET_LIST,nestingLevel:0,textStyle:{},...y,...d}):(ee={...u,...S},ge={listId:"",listType:Pn.BULLET_LIST,nestingLevel:0,textStyle:{},...d,...y}),c===m){f.push({startIndex:c,paragraphStyle:ee,bullet:ge});break}}l.push(...f),f=[]}n.paragraphs=l}return Br(e,n,t,r),a}function Cc(e,n,t,r,s){const{sectionBreaks:o}=e,{sectionBreaks:i}=n;if(o==null||i==null)return;const a=Mi(e,t,r);if(s!==ke.REPLACE){const l=[];for(const h of i){const{startIndex:c}=h;let u=[];for(const d of a){const{startIndex:f}=d;if(c===f){s===ke.COVER?u.push({...d,...h}):u.push({...h,...d});break}}l.push(...u),u=[]}n.sectionBreaks=l}return Br(e,n,t,r),a}function Ic(e,n,t,r,s){const{customBlocks:o}=e,{customBlocks:i}=n;if(o==null||i==null)return;const a=Ui(e,t,r);if(s!==ke.REPLACE){const l=[];for(const h of i){const{startIndex:c}=h;let u=[];for(const d of a){const{startIndex:f}=d;if(c===f){s===ke.COVER?u.push({...d,...h}):u.push({...h,...d});break}}l.push(...u),u=[]}n.customBlocks=l}return wi(e,n,t,r),a}function vc(e,n,t,r,s){const{tables:o}=e,{tables:i}=n;if(o==null||i==null)return;const a=Li(e,t,r);if(s!==ke.REPLACE){const l=[];for(const h of i){const{startIndex:c,endIndex:u}=h;let d=[];for(const f of a){const{startIndex:p,endIndex:m}=f;if(p>=c&&m<=u){s===ke.COVER?d.push({...f,...h}):d.push({...h,...f});break}}l.push(...d),d=[]}n.tables=l}return bi(e,n,t,r),a}function Oc(e,n,t,r,s){e.customRanges||(e.customRanges=[]);const{customRanges:o}=e,{customRanges:i}=n;if(o==null||i==null)return;let a=[];return s===ke.REPLACE&&(a=xi(e,t,r)),Ai(e,n,0,r),a}function Sc(e,n,t,r,s){e.customDecorations||(e.customDecorations=[]);let o=[];return s===ke.REPLACE&&(o=Pi(e,t,r,!1)),Ti(e,n,0,r),o}var Gr=(e=>(e[e.copy=0]="copy",e[e.cut=1]="cut",e))(Gr||{});function an(e,n,t,r=!1,s=1){const{dataStream:o,textRuns:i=[],paragraphs:a=[],customBlocks:l=[]}=e,h={dataStream:o.slice(n,t)},c=[];for(const p of i){const m=x.deepClone(p),{st:S,ed:y}=m;x.hasIntersectionBetweenTwoRanges(S,y,n,t)&&(n>=S&&n<=y?c.push({...m,st:n,ed:Math.min(t,y)}):t>=S&&t<=y?c.push({...m,st:Math.max(n,S),ed:t}):c.push(m))}c.length?h.textRuns=c.map(p=>{const{st:m,ed:S}=p;return{...p,st:m-n,ed:S-n}}):r&&(h.textRuns=[{st:0,ed:t-n,ts:{}}]);const u=[];for(const p of a){const{startIndex:m}=p;m>=n&&m<=t&&u.push(x.deepClone(p))}u.length&&(h.paragraphs=u.map(p=>({...p,startIndex:p.startIndex-n}))),s===1&&(h.customDecorations=Hi(e,n,t));const{customRanges:d}=Fi(e,n,t);h.customRanges=d;const f=[];for(const p of l){const{startIndex:m}=p;m>=n&&m<=t&&f.push(x.deepClone(p))}return f.length&&(h.customBlocks=f.map(p=>({...p,startIndex:p.startIndex-n}))),h}function Nc(e){const{dataStream:n,textRuns:t,paragraphs:r,customRanges:s,customDecorations:o}=e;let i=0,a=0;s==null||s.forEach(h=>{h.startIndex<0&&(i=Math.max(i,-h.startIndex)),h.endIndex>n.length-1&&(a=Math.max(a,h.endIndex-n.length+1))});const l=`${gt.CUSTOM_RANGE_START.repeat(i)}${n}${gt.CUSTOM_RANGE_END.repeat(a)}`;return t&&(t[0]&&(t[0].st=t[0].st-i),t[t.length-1]&&(t[t.length-1].ed=t[t.length-1].ed+a)),t==null||t.forEach(h=>{h.st+=i,h.ed+=i}),r==null||r.forEach(h=>{h.startIndex+=i}),s==null||s.forEach(h=>{h.startIndex+=i,h.endIndex+=i}),o==null||o.forEach(h=>{h.startIndex+=i,h.endIndex+=a}),{...e,dataStream:l,textRuns:t,paragraphs:r,customRanges:s,customDecorations:o}}function Fi(e,n,t){const{customRanges:r=[]}=e;let s=0,o=0;const i=r.filter(a=>Math.max(a.startIndex,n)<=Math.min(a.endIndex,t-1)).map(a=>({...a,startIndex:a.startIndex,endIndex:a.endIndex}));if(i.length){i.forEach(a=>{a.startIndex<n&&(s+=1),a.endIndex>t-1&&(o+=1)});for(let a=0;a<s;a++){const l=i[a];l.startIndex=n-s+a}if(o){const a=[...i].sort((l,h)=>h.endIndex-l.endIndex);for(let l=0;l<o;l++){const h=a[l];h.endIndex=t+o-l-1}}}return{customRanges:i.map(a=>({...a,startIndex:a.startIndex-n,endIndex:a.endIndex-n})),leftOffset:s,rightOffset:o}}function Hi(e,n,t){const{customDecorations:r=[]}=e,s=[];return r.forEach(o=>{if(Math.max(o.startIndex,n)<=Math.min(o.endIndex,t-1)){const i=x.deepClone(o);s.push({...i,startIndex:Math.max(i.startIndex-n,0),endIndex:Math.min(i.endIndex,t)-n})}}),s}function Or(e,n,t=ke.COVER){if(n.dataStream!=="")throw new Error("Cannot compose other body with non-empty dataStream");const r={dataStream:e.dataStream},{textRuns:s=[],paragraphs:o=[]}=e,{textRuns:i=[],paragraphs:a=[]}=n,l=ki(i,s,t);l.length&&(r.textRuns=l);const h=[];let c=0,u=0;for(;c<o.length&&u<a.length;){const d=o[c],f=a[u],{startIndex:p}=d,{startIndex:m}=f;p===m?(h.push(x.deepMerge(d,f)),c++,u++):p<m?(h.push(x.deepClone(d)),c++):(h.push(x.deepClone(f)),u++)}return c<o.length&&h.push(...o.slice(c)),u<a.length&&h.push(...a.slice(u)),h.length&&(r.paragraphs=h),r}function wc(e){const{body:n}=e;if(n==null)return!0;const{textRuns:t=[],paragraphs:r=[]}=n;return t.length===0&&r.length===0}function bc(e=x.generateRandomId(6),n=Pt.EN_US,t=""){return{id:e,locale:n,title:t,body:{dataStream:`\r
8
- `,textRuns:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:5},lineSpacing:1,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]},documentStyle:{pageSize:{width:793.3333333333334,height:1122.6666666666667},marginTop:50,marginBottom:50,marginRight:40,marginLeft:40,renderConfig:{vertexAngle:0,centerAngle:0}},settings:{}}}var We=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ac(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $e={},ji={},Vr={};Object.defineProperty(Vr,"__esModule",{value:!0});function Tc(e,n){if(Array.isArray(n))return!1;for(let t in e)if(!Kr(e[t],n[t]))return!1;for(let t in n)if(e[t]===void 0)return!1;return!0}function yc(e,n){if(!Array.isArray(n)||e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!Kr(e[t],n[t]))return!1;return!0}function Kr(e,n){return e===n?!0:e===null||n===null||typeof e!="object"||typeof n!="object"?!1:Array.isArray(e)?yc(e,n):Tc(e,n)}Vr.default=Kr;var zr={};Object.defineProperty(zr,"__esModule",{value:!0});function Sr(e){if(e===null)return null;if(Array.isArray(e))return e.map(Sr);if(typeof e=="object"){const n={};for(let t in e)n[t]=Sr(e[t]);return n}else return e}zr.default=Sr;var Yr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.eachChildOf=e.advancer=e.readCursor=e.writeCursor=e.WriteCursor=e.ReadCursor=e.isValidPathItem=void 0;function n(c,u){if(!c)throw new Error(u)}const t=c=>c!=null&&typeof c=="object"&&!Array.isArray(c),r=(c,u)=>typeof c==typeof u?c>u:typeof c=="string"&&typeof u=="number";function s(c,u){for(let d in c){const f=d;u.write(f,c[f])}}e.isValidPathItem=c=>typeof c=="number"||typeof c=="string"&&c!=="__proto__";class o{constructor(u=null){this.parents=[],this.indexes=[],this.lcIdx=-1,this.idx=-1,this.container=u}ascend(){n(this.parents.length===this.indexes.length/2),this.idx===0?this.parents.length?(this.lcIdx=this.indexes.pop(),this.container=this.parents.pop(),this.idx=this.indexes.pop()):(this.lcIdx=0,this.idx=-1):(n(this.idx>0),this.idx--,t(this.container[this.idx])&&this.idx--)}getPath(){const u=[];let d=this.container,f=this.parents.length-1,p=this.idx;for(;p>=0;)u.unshift(d[p]),p===0?(p=this.indexes[f*2],d=this.parents[f--]):p-=t(d[p-1])?2:1;return u}}class i extends o{get(){return this.container?this.container.slice(this.idx+1):null}getKey(){return n(this.container!=null,"Invalid call to getKey before cursor descended"),this.container[this.idx]}getComponent(){let u;return this.container&&this.container.length>this.idx+1&&t(u=this.container[this.idx+1])?u:null}descendFirst(){let u=this.idx+1;if(!this.container||u>=this.container.length||t(this.container[u])&&u+1>=this.container.length)return!1;t(this.container[u])&&u++;const d=this.container[u];return Array.isArray(d)?(this.indexes.push(this.idx),this.parents.push(this.container),this.indexes.push(u),this.idx=0,this.container=d):this.idx=u,!0}nextSibling(){if(n(this.parents.length===this.indexes.length/2),this.idx>0||this.parents.length===0)return!1;const u=this.indexes[this.indexes.length-1]+1,d=this.parents[this.parents.length-1];return u>=d.length?!1:(n(!isNaN(u)),this.indexes[this.indexes.length-1]=u,this.container=d[u],!0)}_init(u,d,f,p){this.container=u,this.idx=d,this.parents=f.slice(),this.indexes=p.slice()}clone(){const u=new i;return u._init(this.container,this.idx,this.parents,this.indexes),u}*[Symbol.iterator](){if(this.descendFirst()){do yield this.getKey();while(this.nextSibling());this.ascend()}}traverse(u,d){const f=this.getComponent();f&&d(f,u);for(const p of this)u&&u.descend(p),this.traverse(u,d),u&&u.ascend()}eachPick(u,d){this.traverse(u,(f,p)=>{f.p!=null&&d(f.p,p)})}eachDrop(u,d){this.traverse(u,(f,p)=>{f.d!=null&&d(f.d,p)})}}e.ReadCursor=i;class a extends o{constructor(u=null){super(u),this.pendingDescent=[],this._op=u}flushDescent(){n(this.parents.length===this.indexes.length/2),this.container===null&&(this._op=this.container=[]);for(let u=0;u<this.pendingDescent.length;u++){const d=this.pendingDescent[u];let f=this.idx+1;if(f<this.container.length&&t(this.container[f])&&f++,n(f===this.container.length||!t(this.container[f])),f===this.container.length)this.container.push(d),this.idx=f;else if(this.container[f]===d)this.idx=f;else{if(!Array.isArray(this.container[f])){const p=this.container.splice(f,this.container.length-f);this.container.push(p),this.lcIdx>-1&&(this.lcIdx=f)}for(this.indexes.push(this.idx),this.parents.push(this.container),this.lcIdx!==-1&&(n(r(d,this.container[this.lcIdx][0])),f=this.lcIdx+1,this.lcIdx=-1);f<this.container.length&&r(d,this.container[f][0]);)f++;if(this.indexes.push(f),this.idx=0,f<this.container.length&&this.container[f][0]===d)this.container=this.container[f];else{const p=[d];this.container.splice(f,0,p),this.container=p}}}this.pendingDescent.length=0}reset(){this.lcIdx=-1}getComponent(){this.flushDescent();const u=this.idx+1;if(u<this.container.length&&t(this.container[u]))return this.container[u];{const d={};return this.container.splice(u,0,d),d}}write(u,d){const f=this.getComponent();n(f[u]==null||f[u]===d,"Internal consistency error: Overwritten component. File a bug"),f[u]=d}get(){return this._op}descend(u){if(!e.isValidPathItem(u))throw Error("Invalid JSON key");this.pendingDescent.push(u)}descendPath(u){return this.pendingDescent.push(...u),this}ascend(){this.pendingDescent.length?this.pendingDescent.pop():super.ascend()}mergeTree(u,d=s){if(u===null)return;if(n(Array.isArray(u)),u===this._op)throw Error("Cannot merge into my own tree");const f=this.lcIdx,p=this.parents.length;let m=0;for(let S=0;S<u.length;S++){const y=u[S];typeof y=="string"||typeof y=="number"?(m++,this.descend(y)):Array.isArray(y)?this.mergeTree(y,d):typeof y=="object"&&d(y,this)}for(;m--;)this.ascend();this.lcIdx=this.parents.length===p?f:-1}at(u,d){this.descendPath(u),d(this);for(let f=0;f<u.length;f++)this.ascend();return this}writeAtPath(u,d,f){return this.at(u,()=>this.write(d,f)),this.reset(),this}writeMove(u,d,f=0){return this.writeAtPath(u,"p",f).writeAtPath(d,"d",f)}getPath(){const u=super.getPath();return u.push(...this.pendingDescent),u}}e.WriteCursor=a,e.writeCursor=()=>new a,e.readCursor=c=>new i(c);function l(c,u,d){let f,p;p=f=c?c.descendFirst():!1;function m(S){let y;for(;p;){const ee=y=c.getKey();if(S!=null){let ge=!1;if(u&&typeof ee=="number"&&(y=u(ee,c.getComponent()),y<0&&(y=~y,ge=!0)),r(y,S))return null;if(y===S&&!ge)return c}d&&typeof y=="number"&&d(y,c.getComponent()),p=c.nextSibling()}return null}return m.end=()=>{f&&c.ascend()},m}e.advancer=l;function h(c,u,d){let f,p,m,S;for(f=p=c&&c.descendFirst(),m=S=u&&u.descendFirst();f||m;){let y=f?c.getKey():null,ee=m?u.getKey():null;y!==null&&ee!==null&&(r(ee,y)?ee=null:y!==ee&&(y=null)),d(y==null?ee:y,y!=null?c:null,ee!=null?u:null),y!=null&&f&&(f=c.nextSibling()),ee!=null&&m&&(m=u.nextSibling())}p&&c.ascend(),S&&u.ascend()}e.eachChildOf=h})(Yr);var Xr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConflictType=void 0,function(n){n[n.RM_UNEXPECTED_CONTENT=1]="RM_UNEXPECTED_CONTENT",n[n.DROP_COLLISION=2]="DROP_COLLISION",n[n.BLACKHOLE=3]="BLACKHOLE"}(e.ConflictType||(e.ConflictType={}))})(Xr);var rr={},yt={},Ss;function Qr(){return Ss||(Ss=1,Object.defineProperty(yt,"__esModule",{value:!0}),yt.uniToStrPos=yt.strPosToUni=void 0,yt.strPosToUni=(e,n=e.length)=>{let t=0,r=0;for(;r<n;r++){const s=e.charCodeAt(r);s>=55296&&s<=57343&&(t++,r++)}if(r!==n)throw Error("Invalid offset - splits unicode bytes");return r-t},yt.uniToStrPos=(e,n)=>{let t=0;for(;n>0;n--){const r=e.charCodeAt(t);t+=r>=55296&&r<=57343?2:1}return t}),yt}var sr={},Ns;function Nr(){return Ns||(Ns=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.uniSlice=e.dlen=e.eachOp=void 0;const n=Qr(),t=E=>{if(!Array.isArray(E))throw Error("Op must be an array of components");let v=null;for(let A=0;A<E.length;A++){const X=E[A];switch(typeof X){case"object":if(typeof X.d!="number"&&typeof X.d!="string")throw Error("Delete must be number or string");if(e.dlen(X.d)<=0)throw Error("Deletes must not be empty");break;case"string":if(!(X.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(X>0))throw Error("Skip components must be >0");if(typeof v=="number")throw Error("Adjacent skip components should be combined");break}v=X}if(typeof v=="number")throw Error("Op has a trailing skip")};function r(E,v){let A=0,X=0;for(let ne=0;ne<E.length;ne++){const Q=E[ne];switch(v(Q,A,X),typeof Q){case"object":A+=e.dlen(Q.d);break;case"string":X+=n.strPosToUni(Q);break;case"number":A+=Q,X+=Q;break}}}e.eachOp=r;function s(E,v){const A=[],X=a(A);return r(E,(ne,Q,Ke)=>{X(v(ne,Q,Ke))}),u(A)}const o=E=>E,i=E=>s(E,o);e.dlen=E=>typeof E=="number"?E:n.strPosToUni(E);const a=E=>v=>{if(!(!v||v.d===0||v.d===""))if(E.length===0)E.push(v);else if(typeof v==typeof E[E.length-1])if(typeof v=="object"){const A=E[E.length-1];A.d=typeof A.d=="string"&&typeof v.d=="string"?A.d+v.d:e.dlen(A.d)+e.dlen(v.d)}else E[E.length-1]+=v;else E.push(v)},l=E=>typeof E=="number"?E:typeof E=="string"?n.strPosToUni(E):typeof E.d=="number"?E.d:n.strPosToUni(E.d);e.uniSlice=(E,v,A)=>{const X=n.uniToStrPos(E,v),ne=A==null?1/0:n.uniToStrPos(E,A);return E.slice(X,ne)};const h=(E,v,A)=>typeof E=="number"?A==null?E-v:Math.min(E,A)-v:e.uniSlice(E,v,A),c=E=>{let v=0,A=0;return{take:(Q,Ke)=>{if(v===E.length)return Q===-1?null:Q;const ve=E[v];let fe;if(typeof ve=="number")return Q===-1||ve-A<=Q?(fe=ve-A,++v,A=0,fe):(A+=Q,Q);if(typeof ve=="string"){if(Q===-1||Ke==="i"||n.strPosToUni(ve.slice(A))<=Q)return fe=ve.slice(A),++v,A=0,fe;{const Ce=A+n.uniToStrPos(ve.slice(A),Q);return fe=ve.slice(A,Ce),A=Ce,fe}}else{if(Q===-1||Ke==="d"||e.dlen(ve.d)-A<=Q)return fe={d:h(ve.d,A)},++v,A=0,fe;{let Ce=h(ve.d,A,A+Q);return A+=Q,{d:Ce}}}},peek:()=>E[v]}},u=E=>(E.length>0&&typeof E[E.length-1]=="number"&&E.pop(),E);function d(E,v,A){if(A!=="left"&&A!=="right")throw Error("side ("+A+") must be 'left' or 'right'");t(E),t(v);const X=[],ne=a(X),{take:Q,peek:Ke}=c(E);for(let fe=0;fe<v.length;fe++){const Ce=v[fe];let Te,ze;switch(typeof Ce){case"number":for(Te=Ce;Te>0;)ze=Q(Te,"i"),ne(ze),typeof ze!="string"&&(Te-=l(ze));break;case"string":A==="left"&&typeof Ke()=="string"&&ne(Q(-1)),ne(n.strPosToUni(Ce));break;case"object":for(Te=e.dlen(Ce.d);Te>0;)switch(ze=Q(Te,"i"),typeof ze){case"number":Te-=ze;break;case"string":ne(ze);break;case"object":Te-=e.dlen(ze.d)}break}}let ve;for(;ve=Q(-1);)ne(ve);return u(X)}function f(E,v){t(E),t(v);const A=[],X=a(A),{take:ne}=c(E);for(let Ke=0;Ke<v.length;Ke++){const ve=v[Ke];let fe,Ce;switch(typeof ve){case"number":for(fe=ve;fe>0;)Ce=ne(fe,"d"),X(Ce),typeof Ce!="object"&&(fe-=l(Ce));break;case"string":X(ve);break;case"object":fe=e.dlen(ve.d);let Te=0;for(;Te<fe;)switch(Ce=ne(fe-Te,"d"),typeof Ce){case"number":X({d:h(ve.d,Te,Te+Ce)}),Te+=Ce;break;case"string":Te+=n.strPosToUni(Ce);break;case"object":X(Ce)}break}}let Q;for(;Q=ne(-1);)X(Q);return u(A)}const p=(E,v)=>{let A=0;for(let X=0;X<v.length&&E>A;X++){const ne=v[X];switch(typeof ne){case"number":{A+=ne;break}case"string":const Q=n.strPosToUni(ne);A+=Q,E+=Q;break;case"object":E-=Math.min(e.dlen(ne.d),E-A);break}}return E},m=(E,v)=>typeof E=="number"?p(E,v):E.map(A=>p(A,v));function S(E,v,A){return s(E,(X,ne)=>typeof X=="object"&&typeof X.d=="number"?{d:A.slice(v,ne,ne+X.d)}:X)}function y(E){return s(E,v=>{switch(typeof v){case"object":if(typeof v.d=="number")throw Error("Cannot invert text op: Deleted characters missing from operation. makeInvertible must be called first.");return v.d;case"string":return{d:v};case"number":return v}})}function ee(E){return s(E,v=>typeof v=="object"&&typeof v.d=="string"?{d:n.strPosToUni(v.d)}:v)}function ge(E){let v=!0;return r(E,A=>{typeof A=="object"&&typeof A.d=="number"&&(v=!1)}),v}function ce(E){return{name:"text-unicode",uri:"http://sharejs.org/types/text-unicode",trim:u,normalize:i,checkOp:t,create(v=""){if(typeof v!="string")throw Error("Initial data must be a string");return E.create(v)},apply(v,A){t(A);const X=E.builder(v);for(let ne=0;ne<A.length;ne++){const Q=A[ne];switch(typeof Q){case"number":X.skip(Q);break;case"string":X.append(Q);break;case"object":X.del(e.dlen(Q.d));break}}return X.build()},transform:d,compose:f,transformPosition:p,transformSelection:m,isInvertible:ge,makeInvertible(v,A){return S(v,A,E)},stripInvertible:ee,invert:y,invertWithDoc(v,A){return y(S(v,A,E))},isNoop:v=>v.length===0}}e.default=ce}(sr)),sr}var Rn={},ws;function Dc(){if(ws)return Rn;ws=1,Object.defineProperty(Rn,"__esModule",{value:!0});const e=Nr(),n=Qr();function t(r,s){return{get:r,getLength(){return r().length},insert(o,i,a){const l=n.strPosToUni(r(),o);return s([l,i],a)},remove(o,i,a){const l=n.strPosToUni(r(),o);return s([l,{d:i}],a)},_onOp(o){e.eachOp(o,(i,a,l)=>{switch(typeof i){case"string":this.onInsert&&this.onInsert(l,i);break;case"object":const h=e.dlen(i.d);this.onRemove&&this.onRemove(l,h)}})},onInsert:null,onRemove:null}}return Rn.default=t,t.provides={text:!0},Rn}var bs;function Mc(){return bs||(bs=1,function(e){var n=We&&We.__createBinding||(Object.create?function(d,f,p,m){m===void 0&&(m=p),Object.defineProperty(d,m,{enumerable:!0,get:function(){return f[p]}})}:function(d,f,p,m){m===void 0&&(m=p),d[m]=f[p]}),t=We&&We.__setModuleDefault||(Object.create?function(d,f){Object.defineProperty(d,"default",{enumerable:!0,value:f})}:function(d,f){d.default=f}),r=We&&We.__importStar||function(d){if(d&&d.__esModule)return d;var f={};if(d!=null)for(var p in d)Object.hasOwnProperty.call(d,p)&&n(f,d,p);return t(f,d),f},s=We&&We.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(e,"__esModule",{value:!0}),e.type=e.remove=e.insert=void 0;const o=Qr(),i=r(Nr()),a=s(Dc()),l={create(d){return d},toString(d){return d},builder(d){if(typeof d!="string")throw Error("Invalid document snapshot: "+d);const f=[];return{skip(p){let m=o.uniToStrPos(d,p);if(m>d.length)throw Error("The op is too long for this document");f.push(d.slice(0,m)),d=d.slice(m)},append(p){f.push(p)},del(p){d=d.slice(o.uniToStrPos(d,p))},build(){return f.join("")+d}}},slice:i.uniSlice},h=i.default(l),c=Object.assign(Object.assign({},h),{api:a.default});e.type=c,e.insert=(d,f)=>f.length===0?[]:d===0?[f]:[d,f],e.remove=(d,f)=>i.dlen(f)===0?[]:d===0?[{d:f}]:[d,{d:f}];var u=Nr();Object.defineProperty(e,"makeType",{enumerable:!0,get:function(){return u.default}})}(rr)),rr}(function(e){var n=We&&We.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(e,"__esModule",{value:!0}),e.editOp=e.replaceOp=e.insertOp=e.moveOp=e.removeOp=e.type=void 0;const t=n(Vr),r=n(zr),s=Yr,o=Xr;function i(g,R){if(!g)throw new Error(R)}e.type={name:"json1",uri:"http://sharejs.org/types/JSONv1",readCursor:s.readCursor,writeCursor:s.writeCursor,create:g=>g,isNoop:g=>g==null,setDebug(g){},registerSubtype:y,checkValidOp:ne,normalize:Q,apply:Ke,transformPosition:ve,compose:fe,tryTransform:Zn,transform:La,makeInvertible:ze,invert:Ce,invertWithDoc:Ua,RM_UNEXPECTED_CONTENT:o.ConflictType.RM_UNEXPECTED_CONTENT,DROP_COLLISION:o.ConflictType.DROP_COLLISION,BLACKHOLE:o.ConflictType.BLACKHOLE,transformNoConflict:(g,R,N)=>os(()=>!0,g,R,N),typeAllowingConflictsPred:g=>Object.assign(Object.assign({},e.type),{transform:(R,N,M)=>os(g,R,N,M)})};const a=g=>g?g.getComponent():null;function l(g){return g&&typeof g=="object"&&!Array.isArray(g)}const h=g=>Array.isArray(g)?g.slice():g!==null&&typeof g=="object"?Object.assign({},g):g,c=g=>g&&(g.p!=null||g.r!==void 0),u=g=>g&&(g.d!=null||g.i!==void 0);function d(g,R){return i(g!=null),typeof R=="number"?(i(Array.isArray(g),"Invalid key - child is not an array"),(g=g.slice()).splice(R,1)):(i(l(g),"Invalid key - child is not an object"),delete(g=Object.assign({},g))[R]),g}function f(g,R,N){return typeof R=="number"?(i(g!=null,"Container is missing for key"),i(Array.isArray(g),"Cannot use numerical key for object container"),i(g.length>=R,"Cannot insert into out of bounds index"),g.splice(R,0,N)):(i(l(g),"Cannot insert into missing item"),i(g[R]===void 0,"Trying to overwrite value at key. Your op needs to remove it first"),g[R]=N),N}e.removeOp=(g,R=!0)=>s.writeCursor().writeAtPath(g,"r",R).get(),e.moveOp=(g,R)=>s.writeCursor().writeMove(g,R).get(),e.insertOp=(g,R)=>s.writeCursor().writeAtPath(g,"i",R).get(),e.replaceOp=(g,R,N)=>s.writeCursor().at(g,M=>{M.write("r",R),M.write("i",N)}).get(),e.editOp=(g,R,N,M=!1)=>s.writeCursor().at(g,w=>v(w,R,N,M)).get();const p=(g,R)=>g!=null&&(typeof R=="number"?Array.isArray(g):typeof g=="object"),m=(g,R)=>p(g,R)?g[R]:void 0,S={};function y(g){let R=g.type?g.type:g;R.name&&(S[R.name]=R),R.uri&&(S[R.uri]=R)}const ee=g=>{const R=S[g];if(R)return R;throw Error("Missing type: "+g)};y(Mc());const ge=(g,R)=>g+R;y({name:"number",apply:ge,compose:ge,invert:g=>-g,transform:g=>g});const ce=g=>g==null?null:g.et?ee(g.et):g.es?S["text-unicode"]:g.ena!=null?S.number:null,E=g=>g.es?g.es:g.ena!=null?g.ena:g.e,v=(g,R,N,M=!1)=>{const[w,D]=typeof R=="string"?[ee(R),R]:[R,R.name];!M&&w.isNoop&&w.isNoop(N)||(D==="number"?g.write("ena",N):D==="text-unicode"?g.write("es",N):(g.write("et",D),g.write("e",N)))};function A(g){i(typeof g=="number"),i(g>=0),i(g===(0|g))}function X(g){typeof g=="number"?A(g):i(typeof g=="string")}function ne(g){if(g===null)return;const R=new Set,N=new Set,M=D=>{let B=!0,$=!1;for(let C in D){const O=D[C];if(B=!1,i(C==="p"||C==="r"||C==="d"||C==="i"||C==="e"||C==="es"||C==="ena"||C==="et","Invalid component item '"+C+"'"),C==="p")A(O),i(!R.has(O)),R.add(O),i(D.r===void 0);else if(C==="d")A(O),i(!N.has(O)),N.add(O),i(D.i===void 0);else if(C==="e"||C==="es"||C==="ena"){i(!$),$=!0;const b=ce(D);i(b,"Missing type in edit"),b.checkValidOp&&b.checkValidOp(E(D))}}i(!B)},w=(D,B,$)=>{if(!Array.isArray(D))throw Error("Op must be null or a list");if(D.length===0)throw Error("Empty descent");B||X(D[0]);let C=1,O=0,b=0;for(let T=0;T<D.length;T++){const W=D[T];if(i(W!=null),Array.isArray(W)){const G=w(W,!1);if(O){const I=typeof b,F=typeof G;I===F?i(b<G,"descent keys are not in order"):i(I==="number"&&F==="string")}b=G,O++,C=3}else typeof W=="object"?(i(C===1,`Prev not scalar - instead ${C}`),M(W),C=2):(i(C!==3),X(W),i(s.isValidPathItem(W),"Invalid path key"),C=1)}return i(O!==1,"Operation makes multiple descents. Remove some []"),i(C===2||C===3),D[0]};w(g,!0),i(R.size===N.size,"Mismatched picks and drops in op");for(let D=0;D<R.size;D++)i(R.has(D)),i(N.has(D))}function Q(g){let R=0,N=[];const M=s.writeCursor();return M.mergeTree(g,(w,D)=>{const B=ce(w);if(B){const C=E(w);v(D,B,B.normalize?B.normalize(C):C)}for(const C of["r","p","i","d"])if(w[C]!==void 0){const O=C==="p"||C==="d"?($=w[C],N[$]==null&&(N[$]=R++),N[$]):w[C];D.write(C,O)}var $}),M.get()}function Ke(g,R){if(ne(R),R===null)return g;const N=[];return function M(w,D){let B=w,$=0,C={root:w},O=0,b=C,T="root";function W(){for(;O<$;O++){let G=D[O];typeof G!="object"&&(i(p(b,T)),b=b[T]=h(b[T]),T=G)}}for(;$<D.length;$++){const G=D[$];if(Array.isArray(G)){const I=M(B,G);I!==B&&I!==void 0&&(W(),B=b[T]=I)}else if(typeof G=="object"){G.d!=null?(W(),B=f(b,T,N[G.d])):G.i!==void 0&&(W(),B=f(b,T,G.i));const I=ce(G);if(I)W(),B=b[T]=I.apply(B,E(G));else if(G.e!==void 0)throw Error("Subtype "+G.et+" undefined")}else B=m(B,G)}return C.root}(g=function M(w,D){const B=[];let $=0;for(;$<D.length;$++){const T=D[$];if(Array.isArray(T))break;typeof T!="object"&&(B.push(w),w=m(w,T))}for(let T=D.length-1;T>=$;T--)w=M(w,D[T]);for(--$;$>=0;$--){const T=D[$];if(typeof T!="object"){const W=B.pop();w=w===m(W,T)?W:w===void 0?d(W,T):(O=T,b=w,(C=h(C=W))[O]=b,C)}else c(T)&&(i(w!==void 0,"Cannot pick up or remove undefined"),T.p!=null&&(N[T.p]=w),w=void 0)}var C,O,b;return w}(g,R),R)}function ve(g,R){g=g.slice(),ne(R);const N=s.readCursor(R);let M,w,D=!1;const B=[];for(let C=0;;C++){const O=g[C],b=N.getComponent();if(b&&(b.r!==void 0?D=!0:b.p!=null&&(D=!1,M=b.p,w=C)),C>=g.length)break;let T=0;const W=s.advancer(N,void 0,(I,F)=>{c(F)&&T++});B.unshift(W);const G=W(O);if(typeof O=="number"&&(g[C]-=T),!G)break}if(B.forEach(C=>C.end()),D)return null;const $=()=>{let C=0;if(M!=null){const O=N.getPath();C=O.length,g=O.concat(g.slice(w))}for(;C<g.length;C++){const O=g[C],b=a(N),T=ce(b);if(T){const I=E(b);T.transformPosition&&(g[C]=T.transformPosition(g[C],I));break}let W=0;const G=s.advancer(N,(I,F)=>u(F)?~(I-W):I-W,(I,F)=>{u(F)&&W++})(O);if(typeof O=="number"&&(g[C]+=W),!G)break}};return M!=null?N.eachDrop(null,C=>{C===M&&$()}):$(),g}function fe(g,R){if(ne(g),ne(R),g==null)return R;if(R==null)return g;let N=0;const M=s.readCursor(g),w=s.readCursor(R),D=s.writeCursor(),B=[],$=[],C=[],O=[],b=[],T=[],W=new Set;M.traverse(null,I=>{I.p!=null&&(C[I.p]=M.clone())}),w.traverse(null,I=>{I.d!=null&&(O[I.d]=w.clone())});const G=s.writeCursor();return function I(F,_e,le,q,me,ct,xe,ye){i(_e||le);const Ee=a(_e),Ye=a(le),Je=!!Ye&&Ye.r!==void 0,Nt=!!Ee&&Ee.i!==void 0,Xe=Ee?Ee.d:null,Be=Ye?Ye.p:null,ht=(ct||Je)&&Be==null;if(Be!=null)q=O[Be],xe=$[Be]=new s.WriteCursor;else if(Ye&&Ye.r!==void 0)q=null;else{const L=a(q);L&&L.d!=null&&(q=null)}const ie=a(q);if(Xe!=null)if(F=C[Xe],ye=B[Xe]=new s.WriteCursor,ht)ct&&!Je&&ye.write("r",!0);else{const L=b[Xe]=N++;xe.write("d",L)}else if(Ee&&Ee.i!==void 0)F=null;else{const L=a(F);L&&L.p!=null&&(F=null)}let P;Nt?(i(me===void 0),P=Ee.i):P=me;const V=(Be==null?!Nt||ct||Je:P===void 0)?null:xe.getComponent();if(Be!=null){if(!(me!==void 0||Nt)){const L=Xe!=null?b[Xe]:N++;T[Be]=L,ye.write("p",L)}}else Je&&(Nt||me!==void 0||(Ye.r,ye.write("r",Ye.r)));const k=ht?null:ce(Ee),U=ce(ie);if((k||U)&&(k&&k.name,U&&U.name),k&&U){i(k===U);const L=E(Ee),z=E(ie),be=k.compose(L,z);v(xe,k,be),W.add(ie)}else k?v(xe,k,E(Ee)):U&&(v(xe,U,E(ie)),W.add(ie));const H=typeof P=="object"&&P!=null;let re=!1,se=0,ae=0,we=0,Oe=0,Re=0;const Ue=s.advancer(q,(L,z)=>u(z)?Oe-L-1:L-Oe,(L,z)=>{u(z)&&Oe++}),te=s.advancer(F,(L,z)=>c(z)?se-L-1:L-se,(L,z)=>{c(z)&&se++});if(s.eachChildOf(_e,le,(L,z,be)=>{let Fe,dt,wt=L,et=L,Yt=L;if(typeof L=="number"){let De=L+we;dt=Ue(De),et=De+Oe;let Ie=L+ae;Fe=te(Ie),u(a(dt))&&(Fe=null),wt=Ie+se,Yt=L+Re,i(wt>=0,"p1PickKey is negative"),i(et>=0,"p2DropKey is negative");const tt=u(a(z)),ft=c(a(be));(tt||ft&&!ht)&&Re--,tt&&ae--,ft&&we--}else Fe=te(L),dt=Ue(L);ye.descend(wt),xe.descend(et);const Ht=H&&!u(a(z))?P[Yt]:void 0,at=I(Fe,z,be,dt,Ht,ht,xe,ye);var lt,j,pe;H&&!ht?Ht!==at&&(re||(P=Array.isArray(P)?P.slice():Object.assign({},P),re=!0),lt=P,pe=at,typeof(j=Yt)=="number"?(i(Array.isArray(lt)),i(j<lt.length)):(i(!Array.isArray(lt)),i(lt[j]!==void 0)),pe===void 0?typeof j=="number"?lt.splice(j,1):delete lt[j]:lt[j]=pe):i(at===void 0),xe.ascend(),ye.ascend()}),te.end(),Ue.end(),V!=null)V.i=P;else if(!ct&&!Je&&Be==null)return P}(M,M.clone(),w,w.clone(),void 0,!1,D,G),D.reset(),D.mergeTree(G.get()),D.reset(),D.get(),B.map(I=>I.get()),$.map(I=>I.get()),M.traverse(D,(I,F)=>{const _e=I.p;if(_e!=null){const le=b[_e];le!=null&&F.write("p",le);const q=B[_e];q&&q.get(),q&&F.mergeTree(q.get())}else I.r!==void 0&&F.write("r",I.r)}),D.reset(),D.get(),w.traverse(D,(I,F)=>{const _e=I.d;if(_e!=null){const q=T[_e];q!=null&&F.write("d",q);const me=$[_e];me&&F.mergeTree(me.get())}else I.i!==void 0&&F.write("i",I.i);const le=ce(I);le&&!W.has(I)&&v(F,le,E(I))}),D.get()}function Ce(g){if(g==null)return null;const R=new s.ReadCursor(g),N=new s.WriteCursor;let M;const w=[],D=[];return function B($,C,O){const b=$.getComponent();let T,W=!1;if(b){b.p!=null&&(C.write("d",b.p),w[b.p]=$.clone()),b.r!==void 0&&C.write("i",b.r),b.d!=null&&(C.write("p",b.d),O=void 0),b.i!==void 0&&(O=T=b.i);const I=ce(b);I&&(O===void 0?(M||(M=new Set),M.add(b)):(E(b),O=I.apply(O,E(b)),W=!0))}let G=0;for(const I of $){C.descend(I);const F=typeof I=="number"?I-G:I,_e=m(O,F);u($.getComponent())&&G++;const le=B($,C,_e);if(O!==void 0&&le!==void 0){if(W||(W=!0,O=h(O)),!p(O,F))throw Error("Cannot modify child - invalid operation");O[F]=le}C.ascend()}if(T===void 0)return W?O:void 0;C.write("r",O)}(R,N,void 0),M&&(N.reset(),function B($,C,O){const b=C.getComponent();if(b){const I=b.d;if(I!=null&&($=w[I],O=D[I]=s.writeCursor()),M.has(b)){const F=ce(b);if(!F.invert)throw Error(`Cannot invert subtype ${F.name}`);v(O,F,F.invert(E(b)))}}let T=0,W=0;const G=s.advancer($,(I,F)=>c(F)?T-I-1:I-T,(I,F)=>{c(F)&&T++});for(const I of C)if(typeof I=="number"){const F=I-W,_e=G(F),le=F+T;O.descend(le),B(_e,C,O),u(C.getComponent())&&W++,O.ascend()}else O.descend(I),B(G(I),C,O),O.ascend();G.end()}(R.clone(),R,N),D.length&&(N.reset(),R.traverse(N,(B,$)=>{const C=B.p;if(C!=null){const O=D[C];O&&O.get(),O&&$.mergeTree(O.get())}}))),N.get()}const Te=(g,R)=>g.some(N=>typeof N=="object"&&(Array.isArray(N)?Te(N,R):R(N)));function ze(g,R){if(g==null||!Te(g,C=>{var O;return C.r!==void 0||((O=ce(C))===null||O===void 0?void 0:O.makeInvertible)!=null}))return g;const N=new s.ReadCursor(g),M=new s.WriteCursor;let w=!1;const D=[],B=[],$=(C,O,b)=>{const T=C.getComponent();let W=!1;if(T){T.d!=null&&O.write("d",T.d),T.i!==void 0&&O.write("i",T.i);const I=T.p;if(I!=null&&(D[I]=C.clone(),i(b!==void 0,"Operation picks up at an invalid key"),B[I]=b,O.write("p",T.p)),T.r!==void 0&&b===void 0)throw Error("Invalid doc / op in makeInvertible: removed item missing from doc");const F=ce(T);F&&(F.makeInvertible?w=!0:v(O,F,E(T),!0))}let G=0;for(const I of C){O.descend(I);const F=typeof I=="number"?I-G:I,_e=m(b,F),le=$(C,O,_e);_e!==le&&(W||(W=!0,b=h(b)),le===void 0?(b=d(b,F),typeof I=="number"&&G++):b[F]=le),O.ascend()}return T&&(T.r!==void 0?(O.write("r",r.default(b)),b=void 0):T.p!=null&&(b=void 0)),b};return $(N,M,R),M.get(),w&&(M.reset(),function C(O,b,T,W,G){const I=b.getComponent();if(I){I.i!==void 0?(W=I.i,G=!0):I.d!=null&&(W=B[I.d],O=D[I.d],G=!1,I.d);let q=ce(I);if(q&&q.makeInvertible){const me=E(I);v(T,q,q.makeInvertible(me,W),!0)}}let F=0,_e=0;const le=s.advancer(O,(q,me)=>c(me)?F-q-1:q-F,(q,me)=>{c(me)&&F++});for(const q of b)if(typeof q=="number"){const me=q-_e,ct=le(me),xe=me+F,ye=m(W,G?me:xe);T.descend(q),C(ct,b,T,ye,G),u(b.getComponent())&&_e++,T.ascend()}else{const me=m(W,q);T.descend(q),C(le(q),b,T,me,G),T.ascend()}le.end()}(N.clone(),N,M,R,!1)),M.get()}function Ua(g,R){return Ce(ze(g,R))}const qn=g=>{if(g==null)return null;const R=g.slice();for(let N=0;N<g.length;N++){const M=R[N];Array.isArray(M)&&(R[N]=qn(M))}return R};function Zn(g,R,N){i(N==="left"||N==="right","Direction must be left or right");const M=N==="left"?0:1;if(R==null)return{ok:!0,result:g};ne(g),ne(R);let w=null;const D=[],B=[],$=[],C=[],O=[],b=[],T=[],W=[],G=[],I=[],F=[],_e=[],le=[],q=[],me=[];let ct=0;const xe=s.readCursor(g),ye=s.readCursor(R),Ee=s.writeCursor();if(function ie(P,V=null,k){const U=a(V);U&&(U.r!==void 0?k=V.clone():U.p!=null&&(k=null,b[U.p]=P.clone()));const H=P.getComponent();let re;H&&(re=H.p)!=null&&(O[re]=V?V.clone():null,$[re]=P.clone(),k&&(I[re]=!0,G[re]=k),U&&U.p!=null&&(q[re]=U.p));const se=s.advancer(V);for(const ae of P)ie(P,se(ae),k);se.end()}(ye,xe,null),function ie(P,V,k,U,H){const re=k.getComponent();let se,ae=!1;re&&((se=re.d)!=null?(C[se]=k.clone(),U!=null&&(me[U]==null&&(me[U]=[]),me[U].push(se)),P=O[se]||null,V=$[se]||null,I[se]?(H&&(F[se]=!0),H=G[se]||null):!H||M!==1&&q[se]!=null||w==null&&(w={type:o.ConflictType.RM_UNEXPECTED_CONTENT,op1:e.removeOp(H.getPath()),op2:e.moveOp(V.getPath(),k.getPath())}),ae=!0):re.i!==void 0&&(P=V=null,ae=!0,H&&w==null&&(w={type:o.ConflictType.RM_UNEXPECTED_CONTENT,op1:e.removeOp(H.getPath()),op2:e.insertOp(k.getPath(),re.i)})));const we=a(P);we&&(we.r!==void 0?H=P.clone():we.p!=null&&(we.p,U=we.p,H=null));const Oe=ce(re);Oe&&H&&w==null&&(w={type:o.ConflictType.RM_UNEXPECTED_CONTENT,op1:e.removeOp(H.getPath()),op2:e.editOp(k.getPath(),Oe,E(re),!0)});let Re=0,Ue=0;const te=s.advancer(V,(z,be)=>c(be)?Re-z-1:z-Re,(z,be)=>{c(be)&&Re++}),L=s.advancer(P);for(const z of k)if(typeof z=="number"){const be=z-Ue,Fe=te(be);Ue+=+ie(L(be+Re),Fe,k,U,H)}else{const be=te(z);ie(L(z),be,k,U,H)}return te.end(),L.end(),ae}(xe,ye,ye.clone(),null,null),C.map(ie=>ie&&ie.get()),w)return{ok:!1,conflict:w};F.map(ie=>!!ie);const Ye=[];let Je=null;(function ie(P,V,k,U,H){let re=!1;const se=a(V);if(c(se)){const te=se.p;te!=null?(k=C[te],U=_e[te]=s.writeCursor(),re=!0,H=null):(k=null,H=V.clone())}else u(a(k))&&(k=null);const ae=P.getComponent();if(ae){const te=ae.p;te!=null?(H&&(W[te]=H),Ye[te]=H||M===1&&re?null:U.getComponent(),D[te]=P.clone(),k&&(T[te]=k.clone())):ae.r!==void 0&&(H||U.write("r",!0),(H||re)&&(Je==null&&(Je=new Set),Je.add(ae)))}let we=0,Oe=0;const Re=s.advancer(V,void 0,(te,L)=>{c(L)&&we++}),Ue=s.advancer(k,(te,L)=>u(L)?~(te-Oe):te-Oe,(te,L)=>{u(L)&&Oe++});if(P)for(const te of P)if(typeof te=="string"){const L=Re(te),z=Ue(te);U.descend(te),ie(P,L,z,U,H),U.ascend()}else{const L=Re(te),z=te-we,be=c(a(L))?null:Ue(z),Fe=z+Oe;i(Fe>=0),U.descend(Fe),ie(P,L,be,U,H),U.ascend()}Re.end(),Ue.end()})(xe,ye,ye.clone(),Ee,null),Ee.reset();let Nt=[];if(function ie(P,V,k,U,H,re){i(V);const se=V.getComponent();let ae=a(U),we=!1;const Oe=(j,pe,De)=>j?e.moveOp(j.getPath(),pe.getPath()):e.insertOp(pe.getPath(),De.i);if(u(se)){const j=se.d;j!=null&&(B[j]=V.clone());const pe=j!=null?Ye[j]:null;let De=!1;if(se.i!==void 0||j!=null&&pe){let Ie;ae&&(ae.i!==void 0||(Ie=ae.d)!=null&&!I[Ie])&&(De=Ie!=null?j!=null&&j===q[Ie]:t.default(ae.i,se.i),De||Ie!=null&&M!==1&&q[Ie]!=null||w==null&&(w={type:o.ConflictType.DROP_COLLISION,op1:Oe(j!=null?D[j]:null,V,se),op2:Oe(Ie!=null?$[Ie]:null,U,ae)})),De||(re?w==null&&(w={type:o.ConflictType.RM_UNEXPECTED_CONTENT,op1:Oe(j!=null?D[j]:null,V,se),op2:e.removeOp(re.getPath())}):(j!=null?(Nt[ct]=j,H.write("d",pe.p=ct++)):H.write("i",r.default(se.i)),we=!0))}else if(j!=null&&!pe){const Ie=W[j];Ie&&(re=Ie.clone())}j!=null?(P=D[j],k=b[j],U=T[j]):se.i!==void 0&&(P=k=null,De||(U=null))}else c(a(P))&&(P=k=U=null);const Re=a(P),Ue=a(k);if(c(Ue)){const j=Ue.p;Ue.r!==void 0&&(!Re||Re.r===void 0)||I[j]?(U=null,re=k.clone()):j!=null&&(U=C[j],M!==1&&q[j]!=null||((H=le[j])||(H=le[j]=s.writeCursor()),H.reset(),re=null))}else!u(se)&&u(ae)&&(U=null);ae=U!=null?U.getComponent():null;const te=ce(se);if(te){const j=E(se);if(re)w==null&&(w={type:o.ConflictType.RM_UNEXPECTED_CONTENT,op1:e.editOp(V.getPath(),te,j,!0),op2:e.removeOp(re.getPath())});else{const pe=ce(ae);let De;if(pe){if(te!==pe)throw Error("Transforming incompatible types");const Ie=E(ae);De=te.transform(j,Ie,N)}else De=r.default(j);v(H,te,De)}}let L=0,z=0,be=0,Fe=0,dt=0,wt=0,et=P!=null&&P.descendFirst(),Yt=et;const Ht=s.advancer(k,void 0,(j,pe)=>{c(pe)&&be++});let at=U!=null&&U.descendFirst(),lt=at;for(const j of V)if(typeof j=="number"){let pe;const De=u(V.getComponent()),Ie=j-z;{let mt;for(;et&&typeof(mt=P.getKey())=="number";){mt+=L;const nt=P.getComponent(),jt=c(nt);if(mt>Ie||mt===Ie&&(!jt||M===0&&De))break;if(jt){L--;const bt=nt.p;q.includes(bt),nt.d,a(le[nt.d]),c(a(le[nt.d])),(nt.r===void 0||Je&&Je.has(nt))&&(bt==null||!Ye[bt]||M!==1&&q.includes(bt))||dt--}et=P.nextSibling()}pe=et&&mt===Ie?P:null}const tt=Ie-L;let ft=Ht(tt);const Jn=tt-be;let _n=null;{let mt,nt;for(;at&&typeof(mt=U.getKey())=="number";){nt=mt-Fe;const jt=U.getComponent(),bt=u(jt);if(nt>Jn)break;if(nt===Jn){if(!bt){_n=U;break}{if(M===0&&De){_n=U;break}const At=ft&&c(ft.getComponent());if(M===0&&At)break}}if(bt){const At=jt.d;q[At],jt.i===void 0&&(I[At]||q[At]!=null&&M!==1)?(I[At]||q[At]!=null&&M===0)&&(Fe++,wt--):Fe++}at=U.nextSibling()}}const is=Jn+Fe+dt+wt;i(is>=0,"trying to descend to a negative index"),H.descend(is),De&&(pe=ft=_n=null,z++),ie(pe,V,ft,_n,H,re)&&wt++,H.ascend()}else{let pe;for(;et&&(pe=P.getKey(),typeof pe!="string"||!(pe>j||pe===j));)et=P.nextSibling();const De=et&&pe===j?P:null,Ie=Ht(j);let tt;for(;at&&(tt=U.getKey(),typeof tt!="string"||!(tt>j||tt===j));)at=U.nextSibling();const ft=at&&tt===j?U:null;H.descend(j),ie(De,V,Ie,ft,H,re),H.ascend()}return Ht.end(),Yt&&P.ascend(),lt&&U.ascend(),we}(xe,xe.clone(),ye,ye.clone(),Ee,null),w)return{ok:!1,conflict:w};Ee.reset();const Xe=(ie,P,V)=>ie.traverse(P,(k,U)=>{k.d!=null&&V(k.d,ie,U)});(I.length||_e.length)&&(Xe(ye,Ee,(ie,P,V)=>{I[ie]&&!F[ie]&&V.write("r",!0),_e[ie]&&V.mergeTree(_e[ie].get())}),Ee.reset());const Be=[],ht=[];if((le.length||I.length)&&!w){const ie=s.readCursor(qn(Ee.get()));if(Xe(ie,null,(P,V)=>{Be[P]=V.clone()}),le.forEach(P=>{P&&Xe(s.readCursor(P.get()),null,(V,k)=>{Be[V]=k.clone()})}),function P(V,k,U,H,re,se){const ae=a(k);if(ae&&c(ae))if(ae.p!=null){const L=ae.p;Be[L].getPath(),U=Be[L],H=ht[L]=s.writeCursor()}else ae.r!==void 0&&(U=null);else u(a(U))&&(U=null);const we=V.getComponent();if(we){let L;if((L=we.d)!=null){const z=le[L];z&&(z.get(),H.mergeTree(z.get()),U=s.readCursor(z.get()))}}let Oe=0,Re=0;const Ue=s.advancer(k,void 0,(L,z)=>{c(z)&&Oe--}),te=s.advancer(U,(L,z)=>u(z)?-(L-Re)-1:L-Re,(L,z)=>{u(z)&&Re++});for(const L of V)if(typeof L=="number"){const z=Ue(L),be=L+Oe,Fe=te(be),dt=be+Re;H.descend(dt),P(V,z,Fe,H),H.ascend()}else H.descend(L),P(V,Ue(L),te(L),H),H.ascend();Ue.end(),te.end()}(ye,ie,ie.clone(),Ee),Ee.reset(),w)return{ok:!1,conflict:w};if(Ee.get(),ht.length){const P=ht.map(k=>k?k.get():null),V=s.readCursor(qn(Ee.get()));if(Xe(V,Ee,(k,U,H)=>{const re=P[k];re&&(H.mergeTree(re),P[k]=null)}),P.find(k=>k)){const k=s.writeCursor(),U=s.writeCursor();let H=0,re=0;P.forEach(se=>{se!=null&&Xe(s.readCursor(se),null,ae=>{const we=Nt[ae];k.writeMove(D[we].getPath(),B[we].getPath(),H++);const Oe=me[we];Oe&&Oe.forEach(Re=>{I[Re]||M!==1&&q[Re]!=null||U.writeMove($[Re].getPath(),C[Re].getPath(),re++)})})}),w={type:o.ConflictType.BLACKHOLE,op1:k.get(),op2:U.get()}}}}return w?{ok:!1,conflict:w}:{ok:!0,result:Ee.get()}}const ss=g=>{const R=new Error("Transform detected write conflict");throw R.conflict=g,R.type=R.name="writeConflict",R};function La(g,R,N){const M=Zn(g,R,N);if(M.ok)return M.result;ss(M.conflict)}const Ft=g=>{const R=s.writeCursor();return s.readCursor(g).traverse(R,(N,M)=>{(u(N)||ce(N))&&M.write("r",!0)}),R.get()},xa=(g,R)=>{const{type:N,op1:M,op2:w}=g;switch(N){case o.ConflictType.DROP_COLLISION:return R==="left"?[null,Ft(w)]:[Ft(M),null];case o.ConflictType.RM_UNEXPECTED_CONTENT:let D=!1;return s.readCursor(M).traverse(null,B=>{B.r!==void 0&&(D=!0)}),D?[null,Ft(w)]:[Ft(M),null];case o.ConflictType.BLACKHOLE:return[Ft(M),Ft(w)];default:throw Error("Unrecognised conflict: "+N)}};function os(g,R,N,M){let w=null;for(;;){const D=Zn(R,N,M);if(D.ok)return fe(w,D.result);{const{conflict:B}=D;g(B)||ss(B);const[$,C]=xa(B,M);R=fe(Q(R),$),N=fe(Q(N),C),w=fe(w,C)}}}})(ji);(function(e){var n=We&&We.__createBinding||(Object.create?function(o,i,a,l){l===void 0&&(l=a),Object.defineProperty(o,l,{enumerable:!0,get:function(){return i[a]}})}:function(o,i,a,l){l===void 0&&(l=a),o[l]=i[a]}),t=We&&We.__exportStar||function(o,i){for(var a in o)a!=="default"&&!i.hasOwnProperty(a)&&n(i,o,a)};Object.defineProperty(e,"__esModule",{value:!0}),t(ji,e);var r=Yr;Object.defineProperty(e,"ReadCursor",{enumerable:!0,get:function(){return r.ReadCursor}}),Object.defineProperty(e,"WriteCursor",{enumerable:!0,get:function(){return r.WriteCursor}});var s=Xr;Object.defineProperty(e,"ConflictType",{enumerable:!0,get:function(){return s.ConflictType}})})($e);const Uc=Ac($e),Lc=Ha({__proto__:null,default:Uc},[$e]);var Z=(e=>(e.RETAIN="r",e.INSERT="i",e.DELETE="d",e))(Z||{});class wr{constructor(n){_(this,"_index",0);_(this,"_offset",0);this._actions=n}hasNext(){return this.peekLength()<Number.POSITIVE_INFINITY}next(n){n||(n=Number.POSITIVE_INFINITY);const t=this._actions[this._index];if(t){const r=this._offset,s=t.len;return n>=s-r?(n=s-r,this._index+=1,this._offset=0):this._offset+=n,t.t===Z.DELETE||t.t===Z.RETAIN&&t.body==null?x.deepClone({...t,len:n}):x.deepClone({...t,len:n,body:an(t.body,r,r+n)})}else return{t:Z.RETAIN,len:Number.POSITIVE_INFINITY}}peek(){return this._actions[this._index]}peekLength(){return this._actions[this._index]?this._actions[this._index].len-this._offset:Number.POSITIVE_INFINITY}peekType(){const n=this._actions[this._index];return n?n.t:Z.RETAIN}rest(){if(this.hasNext()){if(this._offset===0)return this._actions.slice(this._index);{const n=this._offset,t=this._index,r=this.next(),s=this._actions.slice(this._index);return this._offset=n,this._index=t,[r].concat(s)}}else return[]}}class $i{constructor(){_(this,"cursor",0)}reset(){return this.cursor=0,this}moveCursor(n){this.cursor+=n}moveCursorTo(n){this.cursor=n}}function Wi(e,n,t){const{dataStream:r}=e,s=t,o=t+n,i=yi(e,n,t),a=Di(e,n,t),l=Mi(e,n,t),h=Ui(e,n,t),c=Li(e,n,t),u=xi(e,n,t),d=Pi(e,n,t);let f="";return r&&(e.dataStream=Wo(r,s,o),f=r.slice(s,o)),{dataStream:f,textRuns:i,paragraphs:a,sectionBreaks:l,customBlocks:h,tables:c,customRanges:u,customDecorations:d}}function Bi(e,n,t,r){e.dataStream=$o(e.dataStream,r,n.dataStream),Ni(e,n,t,r),Br(e,n,t,r),_c(e,n,t,r),wi(e,n,t,r),bi(e,n,t,r),Ai(e,n,t,r),Ti(e,n,t,r)}function xc(e,n,t,r,s=ke.COVER){return mc(e,n,t,r,s)}function Pc(e,n,t){return n<=0?{dataStream:""}:Wi(e,n,t)}function kc(e,n,t,r){t!==0&&Bi(e,n,t,r)}function Fc(e,n){const t=new $i;return t.reset(),n.forEach(r=>{switch(r=x.deepClone(r),r.t){case Z.RETAIN:{const{coverType:s,body:o,len:i}=r;o!=null&&xc(e,o,i,t.cursor,s),t.moveCursor(i);break}case Z.INSERT:{const{body:s,len:o}=r;kc(e,s,o,t.cursor),t.moveCursor(o);break}case Z.DELETE:{const{len:s}=r;Pc(e,s,t.cursor);break}default:throw new Error(`Unknown action type for action: ${r}.`)}}),e}function As(e){return Object.keys(e).length===1}const sn=class sn{constructor(){_(this,"_actions",[])}static apply(n,t){return Fc(n,t)}static compose(n,t){const r=new wr(n),s=new wr(t),o=new sn;for(;r.hasNext()||s.hasNext();)if(s.peekType()===Z.INSERT)o.push(s.next());else if(r.peekType()===Z.DELETE)o.push(r.next());else{const i=Math.min(r.peekLength(),s.peekLength()),a=r.next(i),l=s.next(i);a.t===Z.INSERT&&l.t===Z.RETAIN?l.body==null?o.push(a):o.push({...a,body:Or(a.body,l.body,l.coverType)}):a.t===Z.RETAIN&&l.t===Z.RETAIN?a.body==null&&l.body==null?o.push(a.len!==Number.POSITIVE_INFINITY?a:l):a.body&&l.body?o.push({...a,body:Or(a.body,l.body,l.coverType)}):o.push(a.body?a:l):a.t===Z.RETAIN&&l.t===Z.DELETE?o.push(l):a.t===Z.INSERT&&(l.t,Z.DELETE)}return o.trimEndUselessRetainAction(),o.serialize()}static transform(n,t,r){throw new Error("transform is not implemented in TextX")}static isNoop(n){return n.length===0}static invert(n){const t=[];for(const r of n)if(r.t===Z.INSERT)t.push({t:Z.DELETE,len:r.len,line:0,body:r.body,segmentId:r.segmentId});else if(r.t===Z.DELETE){if(r.body==null)throw new Error("Can not invert DELETE action without body property, makeInvertible must be called first.");t.push({t:Z.INSERT,body:r.body,len:r.len,line:0,segmentId:r.segmentId})}else if(r.body!=null){if(r.oldBody==null)throw new Error("Can not invert RETAIN action without oldBody property, makeInvertible must be called first.");t.push({t:Z.RETAIN,body:r.oldBody,oldBody:r.body,len:r.len,coverType:ke.REPLACE,segmentId:r.segmentId})}else t.push(r);return t}static makeInvertible(n,t){const r=[];let s=0;for(const o of n){if(o.t===Z.DELETE&&o.body==null){const i=an(t,s,s+o.len,!1);o.len=i.dataStream.length,o.body=i}if(o.t===Z.RETAIN&&o.body!=null){const i=an(t,s,s+o.len,!0);o.oldBody={...i,dataStream:""},o.len=i.dataStream.length}r.push(o),o.t!==Z.INSERT&&(s+=o.len)}return r}insert(n,t,r=""){const s={t:Z.INSERT,body:t,len:n,line:0,segmentId:r};return this.push(s),this}retain(n,t="",r,s){const o={t:Z.RETAIN,len:n,segmentId:t};return r!=null&&(o.body=r),s!=null&&(o.coverType=s),this.push(o),this}delete(n,t=""){const r={t:Z.DELETE,len:n,line:0,segmentId:t};return this.push(r),this}empty(){return this._actions=[],this}serialize(){return this._actions}push(...n){if(n.length>1){for(const o of n)this.push(o);return this}let t=this._actions.length,r=this._actions[t-1];const s=x.deepClone(n[0]);if(s.t===Z.RETAIN&&s.len===0&&s.body==null)return this;if(typeof r=="object"){if(r.t===Z.DELETE&&s.t===Z.DELETE)return r.len+=s.len,this;if(r.t===Z.DELETE&&s.t===Z.INSERT&&(t-=1,r=this._actions[t-1],r==null))return this._actions.unshift(s),this;if(r.t===Z.RETAIN&&s.t===Z.RETAIN&&r.body==null&&s.body==null)return r.len+=s.len,this;if(r.t===Z.INSERT&&As(r.body)&&s.t===Z.INSERT&&As(s.body))return r.len+=s.len,r.body.dataStream+=s.body.dataStream,this}return t===this._actions.length?this._actions.push(s):this._actions.splice(t,0,s),this}trimEndUselessRetainAction(){let n=this._actions[this._actions.length-1];for(;n&&n.t===Z.RETAIN&&wc(n);)this._actions.pop(),n=this._actions[this._actions.length-1];return this}};_(sn,"id","text-x"),_(sn,"uri","https://github.com/dream-num/univer#text-x");let Ot=sn;Object.defineProperty(Ot,"name",{value:"text-x"});const $t=class $t{static registerSubtype(n){var t;this._subTypes.has(n.name)&&((t=this._subTypes.get(n.name))==null?void 0:t.id)!==Ot.id||(this._subTypes.set(n.name,n),$e.type.registerSubtype(n))}static apply(n,t){if(!$e.type.isNoop(t))return $e.type.apply(n,t)}static compose(n,t){return $e.type.compose(n,t)}static transform(n,t,r){throw new Error("transform is not implemented in JsonX")}static invertWithDoc(n,t){return $e.type.invertWithDoc(n,t)}static isNoop(n){return $e.type.isNoop(n)}static getInstance(){return this._instance==null&&(this._instance=new $t),this._instance}removeOp(n,t){return $e.removeOp(n,t)}moveOp(n,t){return $e.moveOp(n,t)}insertOp(n,t){return $e.insertOp(n,t)}replaceOp(n,t,r){return $e.replaceOp(n,t,r)}editOp(n,t=["body"]){return $e.editOp(t,Ot.name,n)}};_($t,"uri","https://github.com/dream-num/univer#json-x"),_($t,"_subTypes",new Map),_($t,"_instance",null);let Lt=$t;Lt.registerSubtype(Ot);const qr={id:"default_doc",documentStyle:{}};class Hc extends Vn{constructor(t){super();_(this,"type",J.UNIVER_DOC);_(this,"snapshot");this.snapshot={...qr,...t}}getUnitId(){throw new Error("Method not implemented.")}get drawings(){return this.snapshot.drawings}get documentStyle(){return this.snapshot.documentStyle}get lists(){return this.snapshot.lists}get zoomRatio(){var t;return((t=this.snapshot.settings)==null?void 0:t.zoomRatio)||1}resetDrawing(t,r){this.snapshot.drawings=t,this.snapshot.drawingsOrder=r}getBody(){return this.snapshot.body}getShouldRenderLoopImmediately(){return this.snapshot.shouldStartRenderingImmediately!==!1}getContainer(){return this.snapshot.container}getSnapshot(){return this.snapshot}updateDocumentId(t){this.snapshot.id=t}updateDocumentRenderConfig(t){const{documentStyle:r}=this.snapshot;r.renderConfig==null?r.renderConfig=t:r.renderConfig={...r.renderConfig,...t}}updateDocumentStyle(t){this.snapshot.documentStyle==null?this.snapshot.documentStyle=t:this.snapshot.documentStyle={...this.snapshot.documentStyle,...t}}updateDocumentDataMargin(t){const{t:r,l:s,b:o,r:i}=t,{documentStyle:a}=this.snapshot;r!=null&&(a.marginTop=r),s!=null&&(a.marginLeft=s),o!=null&&(a.marginBottom=o),i!=null&&(a.marginRight=i)}updateDocumentDataPageSize(t,r){const{documentStyle:s}=this.snapshot;if(!s.pageSize){t=t!=null?t:Number.POSITIVE_INFINITY,r=r!=null?r:Number.POSITIVE_INFINITY,s.pageSize={width:t,height:r};return}t!==void 0&&(s.pageSize.width=t),r!==void 0&&(s.pageSize.height=r)}updateDrawing(t,r){const{drawings:s}=this,{width:o,height:i,left:a,top:l}=r,h=s==null?void 0:s[t];if(!h)return;const c=h.docTransform;c.size.width=o,c.size.height=i,c.positionH.posOffset=a,c.positionV.posOffset=l}setZoomRatio(t=1){this.snapshot.settings==null?this.snapshot.settings={zoomRatio:t}:this.snapshot.settings.zoomRatio=1}}class xt extends Hc{constructor(t){var s;super(x.isEmptyObject(t)?bc():t);_(this,"_unitId");_(this,"headerModelMap",new Map);_(this,"footerModelMap",new Map);const r=6;this._unitId=(s=this.snapshot.id)!=null?s:x.generateRandomId(r),this._initializeHeaderFooterModel()}dispose(){this.headerModelMap.forEach(t=>{t.dispose()}),this.footerModelMap.forEach(t=>{t.dispose()})}getDrawings(){return this.snapshot.drawings}getDrawingsOrder(){return this.snapshot.drawingsOrder}getCustomRanges(){var t;return(t=this.snapshot.body)==null?void 0:t.customRanges}getCustomDecorations(){var t;return(t=this.snapshot.body)==null?void 0:t.customDecorations}getRev(){var t;return(t=this.snapshot.rev)!=null?t:1}incrementRev(){this.snapshot.rev=this.getRev()+1}getSettings(){return this.snapshot.settings}reset(t){if(t.id&&t.id!==this._unitId)throw new Error("Cannot reset a document model with a different unit id!");this.snapshot={...qr,...t},this._initializeHeaderFooterModel()}getSelfOrHeaderFooterModel(t){if(t!=null){if(this.headerModelMap.has(t))return this.headerModelMap.get(t);if(this.footerModelMap.has(t))return this.footerModelMap.get(t)}return this}getUnitId(){return this._unitId}apply(t){if(!Lt.isNoop(t))return this.snapshot=Lt.apply(this.snapshot,t),t!=null&&t.some(r=>Array.isArray(r)&&((r==null?void 0:r[0])==="headers"||(r==null?void 0:r[0])==="footers"))&&(this.headerModelMap.clear(),this.footerModelMap.clear(),this._initializeHeaderFooterModel()),this.snapshot}sliceBody(t,r,s=Gr.copy){const o=this.getBody();if(o!=null)return an(o,t,r,!1,s)}_initializeHeaderFooterModel(){const{headers:t,footers:r}=this.getSnapshot();if(t)for(const s in t){const o=t[s];this.headerModelMap.set(s,new xt(o))}if(r)for(const s in r){const o=r[s];this.footerModelMap.set(s,new xt(o))}}updateDocumentId(t){super.updateDocumentId(t),this._unitId=t}}const Gi=Ve("univer.config-service");class Vi{constructor(){_(this,"_config",new Map)}getConfig(n){return this._config.get(n)}setConfig(n,t){this._config.set(n,t)}deleteConfig(n){this._config.delete(n)}}class Ki extends Ae{constructor(){super(...arguments);_(this,"_error$",new Y.Subject);_(this,"error$",this._error$.asObservable())}dispose(){this._error$.complete()}emit(t){this._error$.next({errorKey:t})}}class zi{constructor(n={}){_(this,"_styles");_(this,"_cacheMap",new zo(1e5));this._styles=n,this._generateCacheMap()}each(n){return Object.entries(this._styles).forEach(n),this}search(n,t){if(this._cacheMap.has(t))return this._cacheMap.get(t);const r=this._getExistingStyleId(n);return r||"-1"}get(n){return typeof n!="string"?n:(n=String(n),this._styles[n])}add(n,t){const r=x.generateRandomId(6);return this._styles[r]=n,this._cacheMap.set(t,r),r}setValue(n){if(n==null)return;const t=JSON.stringify(n),r=this.search(n,t);return r!=="-1"?r:this.add(n,t)}toJSON(){return this._styles}getStyleByCell(n){let t;n&&x.isObject(n.s)?t=n.s:t=(n==null?void 0:n.s)&&this.get(n.s);const r=n==null?void 0:n.interceptorStyle;return r?{...t,...r}:t}_generateCacheMap(){const{_styles:n,_cacheMap:t}=this;for(const r in n){const s=JSON.stringify(n[r]);t.set(s,r)}}_getExistingStyleId(n){const{_styles:t}=this;for(const r in t)if(x.diffValue(t[r],n))return r;return null}}class jc{constructor(n,t){_(this,"_columnData",{});this._config=n,this._columnData=t}getColumnData(){return this._columnData}getColVisible(n){const{_columnData:t}=this,r=t[n];return r?r.hd!==K.TRUE:!0}getHiddenCols(n=0,t=this.getSize()-1){const r=[];let s=!1,o=-1;for(let i=n;i<=t;i++){const a=this.getColVisible(i);s&&a?(s=!1,r.push({rangeType:oe.COLUMN,startColumn:o,endColumn:i-1,startRow:0,endRow:0})):!s&&!a&&(s=!0,o=i)}return s&&r.push({startRow:0,endRow:0,startColumn:o,endColumn:t,rangeType:oe.COLUMN}),r}getVisibleCols(n=0,t=this.getSize()-1){const r=[];let s=!1,o=-1;for(let i=n;i<=t;i++){const a=this.getColVisible(i);s&&!a?(s=!1,r.push({rangeType:oe.COLUMN,startColumn:o,endColumn:i-1,startRow:0,endRow:0})):!s&&a&&(s=!0,o=i)}return s&&r.push({startRow:0,endRow:0,startColumn:o,endColumn:t,rangeType:oe.COLUMN}),r}getColumnDatas(n,t){const r={};let s=0;for(let o=n;o<n+t;o++){const i=this.getColumnOrCreate(o);r[s]=i,s++}return r}getSize(){return It(this._columnData)}getColumnWidth(n){const{_columnData:t}=this,r=this._config;let s=0;return s=(t[n]||{hd:K.FALSE,w:r.defaultColumnWidth}).w||r.defaultColumnWidth,s}getColumn(n){const t=this._columnData[n];if(t)return t}getColumnOrCreate(n){const{_columnData:t}=this,r=this._config,s=t[n];if(s)return s;const o={w:r.defaultColumnWidth,hd:K.FALSE};return this._columnData[n]=o,o}}class $c{constructor(n,t,r){_(this,"_rowData");this._config=n,this._viewModel=t,this._rowData=r}getRowData(){return this._rowData}getRowDatas(n,t){const r={};let s=0;for(let o=n;o<n+t;o++){const i=this.getRowOrCreate(o);r[s]=i,s++}return r}getRowHeight(n,t=1){const{_rowData:r}=this,s=this._config;let o=0;for(let i=0;i<t;i++){const a=r[i+n]||{hd:K.FALSE,h:s.defaultRowHeight},{ia:l,ah:h,h:c=s.defaultRowHeight}=a;o+=(l==null||l===K.TRUE)&&typeof h=="number"?h:c}return o}getRow(n){return this._rowData[n]}getRowOrCreate(n){const{_rowData:t}=this,r=t[n];if(r)return r;const s=this._config,o={hd:K.FALSE,h:s.defaultRowHeight};return t[n]=o,o}getHiddenRows(n=0,t=this.getSize()-1){const r=[];let s=!1,o=-1;for(let i=n;i<=t;i++){const a=this.getRowRawVisible(i);s&&a?(s=!1,r.push({startRow:o,endRow:i-1,startColumn:0,endColumn:0,rangeType:oe.ROW})):!s&&!a&&(s=!0,o=i)}return s&&r.push({startRow:o,endRow:t,startColumn:0,endColumn:0,rangeType:oe.ROW}),r}getVisibleRows(n=0,t=this.getSize()-1){const r=[];let s=!1,o=-1;for(let i=n;i<=t;i++){const a=this.getRowRawVisible(i);s&&!a?(s=!1,r.push({startRow:o,endRow:i-1,startColumn:0,endColumn:0,rangeType:oe.ROW})):!s&&a&&(s=!0,o=i)}return s&&r.push({startRow:o,endRow:t,startColumn:0,endColumn:0,rangeType:oe.ROW}),r}getRowRawVisible(n){const t=this.getRow(n);return t?t.hd!==K.TRUE:!0}getSize(){return It(this._rowData)}}const Wc="DEFAULT_WORKSHEET_ROW_COUNT",Yi=1e3,Bc="DEFAULT_WORKSHEET_COLUMN_COUNT",Xi=20,Gc="DEFAULT_WORKSHEET_ROW_HEIGHT",Qi=24,Vc="DEFAULT_WORKSHEET_COLUMN_WIDTH",qi=88,Kc="DEFAULT_WORKSHEET_ROW_TITLE_WIDTH",Zi=46,zc="DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT",Ji=20;function ea(e){const n={name:"Sheet1",id:"sheet-01",tabColor:"",hidden:K.FALSE,rowCount:Yi,columnCount:Xi,zoomRatio:1,freeze:{xSplit:0,ySplit:0,startRow:-1,startColumn:-1},scrollTop:0,scrollLeft:0,defaultColumnWidth:qi,defaultRowHeight:Qi,mergeData:[],cellData:{},rowData:{},columnData:{},showGridlines:K.TRUE,rowHeader:{width:Zi,hidden:K.FALSE},columnHeader:{height:Ji,hidden:K.FALSE},selections:["A1"],rightToLeft:K.FALSE};return Object.keys(n).forEach(t=>{const r=t;typeof e[r]>"u"&&(e[r]=n[r])}),e}class ta extends Ae{constructor(t){super();_(this,"_cellContentInterceptor",null);_(this,"_rowFilteredInterceptor",null);this.getRawCell=t}dispose(){super.dispose(),this._cellContentInterceptor=null,this._rowFilteredInterceptor=null}getCell(t,r){return this._cellContentInterceptor?this._cellContentInterceptor.getCell(t,r):this.getRawCell(t,r)}getRowFiltered(t){var r,s;return(s=(r=this._rowFilteredInterceptor)==null?void 0:r.getRowFiltered(t))!=null?s:!1}registerCellContentInterceptor(t){if(this._cellContentInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._cellContentInterceptor=t,Ne(()=>this._cellContentInterceptor=null)}registerRowFilteredInterceptor(t){if(this._rowFilteredInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._rowFilteredInterceptor=t,Ne(()=>this._rowFilteredInterceptor=null)}}class ln{constructor(n,t,r){_(this,"_sheetId");_(this,"_snapshot");_(this,"_cellData");_(this,"_rowManager");_(this,"_columnManager");_(this,"_viewModel");var a;this.unitId=n,this._styles=r,this._snapshot=ea(t);const{columnData:s,rowData:o,cellData:i}=this._snapshot;this._sheetId=(a=this._snapshot.id)!=null?a:x.generateRandomId(6),this._cellData=new ot(i),this._viewModel=new ta((l,h)=>this.getCellRaw(l,h)),this._rowManager=new $c(this._snapshot,this._viewModel,o),this._columnManager=new jc(this._snapshot,s)}__interceptViewModel(n){n(this._viewModel)}getSnapshot(){return this._snapshot}getCellMatrix(){return this._cellData}getCellMatrixPrintRange(){const n=this.getCellMatrix(),t=this.getMergeData();let r=-1,s=-1,o=-1,i=-1,a=!1,l=!1;return n.forEach((h,c)=>{Object.keys(c).forEach(u=>{const d=+u,f=n.getValue(h,d),p=f!=null&&f.s?this._styles.get(f.s):null,m=(p==null?void 0:p.bd)&&(p.bd.b||p.bd.l||p.bd.r||p.bd.t||p.bd.bc_tr||p.bd.bl_tr||p.bd.ml_tr||p.bd.tl_bc||p.bd.tl_br||p.bd.tl_mr);(f&&(f.v||f.p)||p!=null&&p.bg||m)&&(a?r=Math.min(r,h):(r=h,a=!0),s=Math.max(s,h),l?o=Math.min(o,d):(l=!0,o=d),i=Math.max(i,d))})}),t.forEach(h=>{a?r=Math.min(r,h.startRow):(r=h.startRow,a=!0),s=Math.max(s,h.endRow),l?o=Math.min(o,h.startColumn):(o=h.startColumn,a=!0),i=Math.max(i,h.endColumn)}),!a||!l?null:{startColumn:o,startRow:r,endColumn:i,endRow:s}}getRowManager(){return this._rowManager}getUnitId(){return this.unitId}getSheetId(){return this._sheetId}getColumnManager(){return this._columnManager}getName(){return this._snapshot.name}clone(){const{_snapshot:n}=this,t=x.deepClone(n);return new ln(this.unitId,t,this._styles)}getMergeData(){return this._snapshot.mergeData}getMergedCell(n,t){const r=this._snapshot.mergeData;for(let s=0;s<r.length;s++){const o=r[s];if(vt.intersects({startRow:n,startColumn:t,endRow:n,endColumn:t},o))return o}return null}getCell(n,t){return n<0||t<0?null:this._viewModel.getCell(n,t)}getCellRaw(n,t){return this.getCellMatrix().getValue(n,t)}getRowFiltered(n){return this._viewModel.getRowFiltered(n)}getMatrixWithMergedCells(n,t,r,s,o=!1){const i=this.getCellMatrix(),a=this._snapshot.mergeData.filter(h=>vt.intersects({startRow:n,startColumn:t,endRow:r,endColumn:s},h)),l=new ot;return fr(n,r,t,s).forEach((h,c)=>{const u=o?this.getCellRaw(h,c):this.getCell(h,c);u&&l.setValue(h,c,u)}),a.forEach(h=>{const{startColumn:c,startRow:u,endColumn:d,endRow:f}=h;fr(u,f,c,d).forEach((p,m)=>{p===u&&m===c&&l.setValue(p,m,{...i.getValue(p,m),rowSpan:f-u+1,colSpan:d-c+1}),(p!==u||m!==c)&&l.realDeleteValue(p,m)})}),l}getRange(n,t,r,s){return typeof n=="object"?new Vt(this,n,{getStyles:()=>this._styles}):new Vt(this,{startRow:n,startColumn:t,endColumn:s||t,endRow:r||n},{getStyles:()=>this._styles})}getScrollLeftTopFromSnapshot(){return{scrollLeft:this._snapshot.scrollLeft,scrollTop:this._snapshot.scrollTop}}getZoomRatio(){return this._snapshot.zoomRatio||1}getConfig(){return this._snapshot}getFreeze(){return this._snapshot.freeze}getMaxColumns(){const{_snapshot:n}=this,{columnCount:t}=n;return t}getMaxRows(){const{_snapshot:n}=this,{rowCount:t}=n;return t}getRowCount(){return this._snapshot.rowCount}setRowCount(n){this._snapshot.rowCount=n}getColumnCount(){return this._snapshot.columnCount}setColumnCount(n){this._snapshot.columnCount=n}isSheetHidden(){return this._snapshot.hidden}hasHiddenGridlines(){const{_snapshot:n}=this,{showGridlines:t}=n;return t===0}getTabColor(){const{_snapshot:n}=this,{tabColor:t}=n;return t}getColumnWidth(n){return this.getColumnManager().getColumnWidth(n)}getRowHeight(n){return this._viewModel.getRowFiltered(n)?0:this.getRowManager().getRowHeight(n)}getRowVisible(n){return this._viewModel.getRowFiltered(n)?!1:this.getRowRawVisible(n)}getRowRawVisible(n){return this.getRowManager().getRowRawVisible(n)}getHiddenRows(n,t){const r=this.getMaxColumns()-1,s=this._rowManager.getHiddenRows(n,t);return s.forEach(o=>o.endColumn=r),s}getColVisible(n){return this._columnManager.getColVisible(n)}getHiddenCols(n,t){const r=this.getMaxRows()-1,s=this._columnManager.getHiddenCols(n,t);return s.forEach(o=>o.endRow=r),s}getVisibleRows(){const n=this.getRowCount();return this._rowManager.getVisibleRows(0,n-1)}getVisibleCols(){const n=this.getColumnCount();return this._columnManager.getVisibleCols(0,n-1)}isRightToLeft(){const{_snapshot:n}=this,{rightToLeft:t}=n;return t}getLastRowWithContent(){return this._cellData.getLength()-1}getLastColumnWithContent(){return this._cellData.getRange().endColumn}cellHasValue(n){return n&&(n.v!==void 0||n.f!==void 0||n.p!==void 0)}iterateByRow(n,t=!0){const{startRow:r,startColumn:s,endRow:o,endColumn:i}=n,a=this;return{[Symbol.iterator]:()=>{let l=r,h=s;return{next(){for(;;){if(h>i&&(l+=1,h=s),l>o)return{done:!0,value:void 0};const c=a.getCell(l,h),u=!c,d=a.getMergedCell(l,h);if(d){if(l!==d.startRow||h!==d.startColumn){h=d.endColumn+1;continue}if(u&&t){h=d.endColumn+1;continue}const p={row:l,col:h,value:c};return p.colSpan=d.endColumn-d.startColumn+1,p.rowSpan=d.endRow-d.startRow+1,h=d.endColumn+1,{done:!1,value:p}}if(u&&t)h+=1;else{const f={row:l,col:h,value:c};return h+=1,{done:!1,value:f}}}}}}}}iterateByColumn(n,t=!0,r=!0){const{startRow:s,startColumn:o,endRow:i,endColumn:a}=n,l=this;return{[Symbol.iterator]:()=>{let h=s,c=o;return{next(){for(;;){if(h>i&&(c+=1,h=s),c>a)return{done:!0,value:void 0};const u=l.getMergedCell(h,c);if(u){const p=h!==u.startRow,m=p||c!==u.startColumn;if(r&&m||!r&&p){h=u.endRow+1;continue}const S=l.getCell(u.startRow,u.startColumn);if(!S&&t){h=u.endRow+1;continue}const ee={row:h,col:u.startColumn,value:S};return ee.colSpan=u.endColumn-u.startColumn+1,ee.rowSpan=u.endRow-u.startRow+1,h=u.endRow+1,{done:!1,value:ee}}const d=l.getCell(h,c);if(!d&&t)h+=1;else{const p={row:h,col:c,value:d};return h+=1,{done:!1,value:p}}}}}}}}}function Yc(e){var r,s;if(!e)return"";const n=(s=(r=e.p)==null?void 0:r.body)==null?void 0:s.dataStream;if(n)return n;const t=e.v;return typeof t=="string"?e.t===Mt.BOOLEAN?t.toUpperCase():t.replace(/[\r\n]/g,""):typeof t=="number"?e.t===Mt.BOOLEAN?t?"TRUE":"FALSE":t.toString():typeof t=="boolean"?t?"TRUE":"FALSE":""}const Xc="0.2.5";function Qc(e="",n=Pt.ZH_CN,t=""){return{id:e,sheetOrder:[],name:t,appVersion:Xc,locale:n,styles:{},sheets:{},resources:[]}}var qc=Object.defineProperty,Zc=Object.getOwnPropertyDescriptor,Jc=(e,n,t,r)=>{for(var s=r>1?void 0:r?Zc(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&qc(n,t,s),s},eh=(e,n)=>(t,r)=>n(t,r,e);function th(e,n){return`${e.getUnitId()}|${n.getSheetId()}`}exports.Workbook=class extends Vn{constructor(t={},r){super();_(this,"type",J.UNIVER_SHEET);_(this,"_sheetCreated$",new Y.Subject);_(this,"sheetCreated$",this._sheetCreated$.asObservable());_(this,"_sheetDisposed$",new Y.Subject);_(this,"sheetDisposed$",this._sheetDisposed$.asObservable());_(this,"_activeSheet$",new Y.BehaviorSubject(null));_(this,"activeSheet$",this._activeSheet$.asObservable());_(this,"_worksheets");_(this,"_styles");_(this,"_snapshot");_(this,"_unitId");_(this,"_count");_(this,"_name$");_(this,"name$");this._logService=r;const s=Qc();x.isEmptyObject(t)?this._snapshot=s:this._snapshot=x.commonExtend(s,t);const{styles:o}=this._snapshot;(this._snapshot.id==null||this._snapshot.id.length===0)&&(this._snapshot.id=x.generateRandomId(6)),this._unitId=this._snapshot.id,this._styles=new zi(o),this._count=1,this._worksheets=new Map,this._name$=new Y.BehaviorSubject(t.name||""),this.name$=this._name$.asObservable(),this._parseWorksheetSnapshots()}get _activeSheet(){return this._activeSheet$.getValue()}get name(){return this._name$.getValue()}dispose(){super.dispose(),this._sheetCreated$.complete(),this._sheetDisposed$.complete(),this._activeSheet$.complete(),this._name$.complete()}save(){return x.deepClone(this._snapshot)}static isIRangeType(t){return typeof t=="string"||"startRow"in t||"row"in t}getSnapshot(){return this._snapshot}getName(){return this._snapshot.name}setName(t){this._name$.next(t),this._snapshot.name=t}getUnitId(){return this._unitId}getRev(){var t;return(t=this._snapshot.rev)!=null?t:1}incrementRev(){this._snapshot.rev=this.getRev()+1}getShouldRenderLoopImmediately(){return this._snapshot.shouldStartRenderingImmediately!==!1}getContainer(){return this._snapshot.container}addWorksheet(t,r,s){const{sheets:o,sheetOrder:i}=this._snapshot;if(o[t])return!1;o[t]=s,i.splice(r,0,t);const a=new ln(this._unitId,s,this._styles);return this._worksheets.set(t,a),this._sheetCreated$.next(a),!0}getSheetOrders(){return this._snapshot.sheetOrder}getWorksheets(){return this._worksheets}getActiveSpreadsheet(){return this}getStyles(){return this._styles}getConfig(){return this._snapshot}getIndexBySheetId(t){const{sheetOrder:r}=this._snapshot;return r.findIndex(s=>s===t)}getActiveSheet(t){if(!this._activeSheet&&typeof t>"u")throw new Error(`[Workbook]: no active Worksheet on Workbook ${this._unitId}!`);return this._activeSheet}ensureActiveSheet(){const t=this._activeSheet;if(t)return t;const r=this._snapshot.sheetOrder;for(let o=0,i=r.length;o<i;o++){const a=this._worksheets.get(r[o]);if(a&&a.isSheetHidden()!==K.TRUE)return this.setActiveSheet(a),a}const s=this._worksheets.get(r[0]);return this.setActiveSheet(s),s}setActiveSheet(t){this._activeSheet$.next(t)}removeSheet(t){const r=this._worksheets.get(t);return r?(this._worksheets.delete(t),this._snapshot.sheetOrder.splice(this._snapshot.sheetOrder.indexOf(t),1),delete this._snapshot.sheets[t],this._sheetDisposed$.next(r),!0):!1}getActiveSheetIndex(){const{sheetOrder:t}=this._snapshot;return t.findIndex(r=>this._worksheets.get(r)===this._activeSheet)}getSheetSize(){return this._snapshot.sheetOrder.length}getSheets(){const{sheetOrder:t}=this._snapshot;return t.map(r=>this._worksheets.get(r))}getSheetsName(){const{sheetOrder:t}=this._snapshot,r=[];return t.forEach(s=>{const o=this._worksheets.get(s);o&&r.push(o.getName())}),r}getSheetIndex(t){const{sheetOrder:r}=this._snapshot;return r.findIndex(s=>t.getSheetId()===s)}getSheetBySheetName(t){const{sheetOrder:r}=this._snapshot,s=r.find(o=>this._worksheets.get(o).getName()===t);return this._worksheets.get(s)}getSheetBySheetId(t){return this._worksheets.get(t)}getSheetByIndex(t){const{sheetOrder:r}=this._snapshot;return this._worksheets.get(r[t])}getHiddenWorksheets(){return this.getSheets().filter(t=>t.getConfig().hidden===K.TRUE).map(t=>t.getConfig().id)}getUnhiddenWorksheets(){return this.getSheets().filter(t=>t.getConfig().hidden!==K.TRUE).map(t=>t.getConfig().id)}load(t){this._snapshot=t}checkSheetName(t){return this.getSheetsName().includes(t)}uniqueSheetName(t="Sheet1"){let r=t;for(;this.checkSheetName(r);)r=t+this._count,this._count++;return r}generateNewSheetName(t){let r=t+this._count;for(;this.checkSheetName(r);)r=t+this._count,this._count++;return r}_parseWorksheetSnapshots(){const{_snapshot:t,_worksheets:r}=this,{sheets:s,sheetOrder:o}=t;if(x.isEmptyObject(s)){const i=x.generateRandomId();s[i]={id:i}}for(const i in s){const a=s[i],{name:l}=a;a.name=this.uniqueSheetName(l),a.name!==l&&this._logService.debug("[Workbook]",`The worksheet name ${l} is duplicated, we changed it to ${a.name}. Please fix the problem in your snapshot.`);const h=new ln(this._unitId,a,this._styles);r.set(i,h),o.includes(i)||o.push(i)}this.ensureActiveSheet()}};exports.Workbook=Jc([eh(1,St)],exports.Workbook);class Zr extends Vn{constructor(t){var r;super();_(this,"type",J.UNIVER_SLIDE);_(this,"_snapshot");_(this,"_unitId");this._snapshot={...Qo,...t},this._unitId=(r=this._snapshot.id)!=null?r:x.generateRandomId(6)}getContainer(){return this._snapshot.container}getSnapshot(){return this._snapshot}getUnitId(){return this._unitId}getPages(){var t;return(t=this._snapshot.body)==null?void 0:t.pages}getPageOrder(){var t;return(t=this._snapshot.body)==null?void 0:t.pageOrder}getPage(t){const r=this.getPages();return r==null?void 0:r[t]}getElementsByPage(t){var r;return(r=this.getPage(t))==null?void 0:r.pageElements}getElement(t,r){var s;return(s=this.getElementsByPage(t))==null?void 0:s[r]}getPageSize(){return this._snapshot.pageSize}addPage(){return{id:"cover_1",pageType:yr.SLIDE,zIndex:1,title:"cover",description:"this is first page, cover",pageBackgroundFill:{rgb:"rgb(255,255,255)"},pageElements:{}}}}const tn="FOCUSING_SHEET",wn="FOCUSING_DOC",bn="FOCUSING_SLIDE",nh="FOCUSING_EDITOR_BUT_HIDDEN",na="EDITOR_ACTIVATED",rh="FOCUSING_EDITOR_INPUT_FORMULA",ra="FOCUSING_FORMULA_EDITOR",sh="FOCUSING_UNIVER_EDITOR",oh="FOCUSING_EDITOR_INPUT_FORMULA",ih="FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE",ah="FOCUSING_COMMON_DRAWINGS";var lh=Object.defineProperty,uh=Object.getOwnPropertyDescriptor,ch=(e,n,t,r)=>{for(var s=r>1?void 0:r?uh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&lh(n,t,s),s},Ts=(e,n)=>(t,r)=>n(t,r,e);const Kt=Ve("univer.current");exports.UniverInstanceService=class extends Ae{constructor(t,r){super();_(this,"_unitsByType",new Map);_(this,"_createHandler");_(this,"_ctorByType",new Map);_(this,"_currentUnits",new Map);_(this,"_currentUnits$",new Y.BehaviorSubject(this._currentUnits));_(this,"currentUnits$",this._currentUnits$.asObservable());_(this,"_unitAdded$",new Y.Subject);_(this,"unitAdded$",this._unitAdded$.asObservable());_(this,"_unitDisposed$",new Y.Subject);_(this,"unitDisposed$",this._unitDisposed$.asObservable());_(this,"_focused$",new Y.BehaviorSubject(null));_(this,"focused$",this._focused$.asObservable());this._injector=t,this._contextService=r}dispose(){super.dispose(),this._focused$.complete()}__setCreateHandler(t){this._createHandler=t}createUnit(t,r){return this._createHandler(t,r,this._ctorByType.get(t))}registerCtorForType(t,r){return this._ctorByType.set(t,r),{dispose:()=>{this._ctorByType.delete(t)}}}getCurrentTypeOfUnit$(t){return this.currentUnits$.pipe(Y.map(r=>{var s;return(s=r.get(t))!=null?s:null}),Y.distinctUntilChanged())}getCurrentUnitForType(t){return this._currentUnits.get(t)}setCurrentUnitForType(t){const r=this._getUnitById(t);if(!r)throw new Error(`[UniverInstanceService]: no document with unitId ${t}!`);this._currentUnits.set(r[1],r[0]),this._currentUnits$.next(this._currentUnits)}_removeCurrentUnitForType(t){this._currentUnits.set(t,null),this._currentUnits$.next(this._currentUnits)}getTypeOfUnitAdded$(t){return this._unitAdded$.pipe(Y.filter(r=>r.type===t))}__addUnit(t){const r=t.type;this._unitsByType.has(r)||this._unitsByType.set(r,[]),this._unitsByType.get(r).push(t),this._unitAdded$.next(t),this.setCurrentUnitForType(t.getUnitId())}getTypeOfUnitDisposed$(t){return this.unitDisposed$.pipe(Y.filter(r=>r.type===t))}getUnit(t,r){var o;const s=(o=this._getUnitById(t))==null?void 0:o[0];return r&&(s==null?void 0:s.type)!==r?null:s}getCurrentUniverDocInstance(){return this.getCurrentUnitForType(J.UNIVER_DOC)}getUniverDocInstance(t){return this.getUnit(t,J.UNIVER_DOC)}getUniverSheetInstance(t){return this.getUnit(t,J.UNIVER_SHEET)}getAllUnitsForType(t){var r;return(r=this._unitsByType.get(t))!=null?r:[]}changeDoc(t,r){const s=this.getAllUnitsForType(J.UNIVER_DOC),o=s.find(i=>i.getUnitId()===t);if(o!=null){const i=s.indexOf(o);s.splice(i,1)}this.__addUnit(r)}get focused(){var r;const t=this._focused$.getValue();return t?(r=this._getUnitById(t))==null?void 0:r[0]:null}focusUnit(t){this._focused$.next(t),this.focused instanceof exports.Workbook?(this._contextService.setContextValue(wn,!1),this._contextService.setContextValue(tn,!0),this._contextService.setContextValue(bn,!1)):this.focused instanceof xt?(this._contextService.setContextValue(wn,!0),this._contextService.setContextValue(tn,!1),this._contextService.setContextValue(bn,!1)):this.focused instanceof Zr&&(this._contextService.setContextValue(wn,!1),this._contextService.setContextValue(tn,!1),this._contextService.setContextValue(bn,!0))}getFocusedUnit(){return this.focused}getUnitType(t){const r=this._getUnitById(t);if(!r)throw new Error(`[UniverInstanceService]: No document with unitId ${t}`);return r[1]}disposeUnit(t){const r=this._getUnitById(t);if(!r)return!1;const[s,o]=r,i=this._unitsByType.get(o),a=i.indexOf(s);return i.splice(a,1),this._removeCurrentUnitForType(o),this._focused$.next(null),this._unitDisposed$.next(s),!0}_getUnitById(t){for(const[r,s]of this._unitsByType){const o=s.find(i=>i.getUnitId()===t);if(o)return[o,r]}}};exports.UniverInstanceService=ch([Ts(0,it(pt)),Ts(1,cn)],exports.UniverInstanceService);var de=(e=>(e[e.Starting=0]="Starting",e[e.Ready=1]="Ready",e[e.Rendered=2]="Rendered",e[e.Steady=3]="Steady",e))(de||{});const hh={0:"Starting",1:"Ready",2:"Rendered",3:"Steady"},An=new Map;function sa(e,n){return function(s){Kn(e,n)}}function Kn(e,n){An.has(e)||An.set(e,[]),An.get(e).push(n)}var dh=Object.defineProperty,fh=Object.getOwnPropertyDescriptor,oa=(e,n,t,r)=>{for(var s=r>1?void 0:r?fh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&dh(n,t,s),s},ia=(e,n)=>(t,r)=>n(t,r,e);exports.LifecycleService=class extends Ae{constructor(t){super();_(this,"_lifecycle$",new Y.BehaviorSubject(de.Starting));_(this,"lifecycle$",this._lifecycle$.asObservable());_(this,"_lock",!1);this._logService=t,this._reportProgress(de.Starting)}get stage(){return this._lifecycle$.getValue()}set stage(t){if(t<this.stage)throw new Error("[LifecycleService]: lifecycle stage cannot go backward!");if(t!==this.stage){if(this._lock)throw new Error("[LifecycleService]: cannot set new stage when related logic is all handled!");this._lock=!0,this._reportProgress(t),this._lifecycle$.next(t),this._lock=!1}}dispose(){this._lifecycle$.complete(),super.dispose()}subscribeWithPrevious(){return Y.merge(aa(this.stage),this._lifecycle$.pipe(Y.skip(1))).pipe(Ii(t=>t===de.Steady))}_reportProgress(t){this._logService.debug("[LifecycleService]",`lifecycle progressed to "${hh[t]}".`)}};exports.LifecycleService=oa([ia(0,St)],exports.LifecycleService);exports.LifecycleInitializerService=class extends Ae{constructor(t){super();_(this,"_seenTokens",new Set);this._injector=t}initModulesOnStage(t){var r;(r=An.get(t))==null||r.forEach(s=>{this._injector.has(s)&&!this._seenTokens.has(s)&&(this._injector.get(s),this._seenTokens.add(s))})}};exports.LifecycleInitializerService=oa([ia(0,it(pt))],exports.LifecycleInitializerService);function aa(e){switch(e){case de.Starting:return Y.of(de.Starting);case de.Ready:return Y.of(de.Starting,de.Ready);case de.Rendered:return Y.of(de.Starting,de.Ready,de.Rendered);default:return Y.of(de.Starting,de.Ready,de.Rendered,de.Steady)}}class nn extends Ae{constructor(){super();_(this,"_currentLocale$",new Y.BehaviorSubject(Pt.ZH_CN));_(this,"currentLocale$",this._currentLocale$.asObservable());_(this,"_locales",null);_(this,"localeChanged$",new Y.Subject);_(this,"t",(t,...r)=>{if(!this._locales)throw new Error("[LocaleService]: Locale not initialized");const s=t.split("."),o=this.resolveKeyPath(this._locales[this._currentLocale],s);if(typeof o=="string"){let i=o;return r.forEach((a,l)=>{i=i.replace(`{${l}}`,a)}),i}else return t});this.disposeWithMe(Ne(()=>this.localeChanged$.complete()))}get _currentLocale(){return this._currentLocale$.value}load(t){var r;this._locales=x.deepMerge((r=this._locales)!=null?r:{},t)}setLocale(t){this._currentLocale$.next(t),this.localeChanged$.next()}getLocales(){var t;return(t=this._locales)==null?void 0:t[this._currentLocale]}getCurrentLocale(){return this._currentLocale}resolveKeyPath(t,r){const s=r.shift();if(s&&t&&s in t){const o=t[s];return r.length>0&&(typeof o=="object"||Array.isArray(o))?this.resolveKeyPath(o,r):o}return null}}var Jr=(e=>(e.INIT="init",e.FETCHING="fetching",e.DONE="done",e))(Jr||{});const es=Ve("univer.permission-service");Kn(de.Starting,es);class la extends Ae{constructor(){super(...arguments);_(this,"_permissionPointMap",new Map);_(this,"_permissionPointUpdate$",new Y.Subject);_(this,"permissionPointUpdate$",this._permissionPointUpdate$.asObservable())}deletePermissionPoint(t){const r=this._permissionPointMap.get(t);r&&(r.complete(),this._permissionPointMap.delete(t))}addPermissionPoint(t){const r=t instanceof Y.BehaviorSubject,s=r?t.getValue():t;if(!s.id)return!1;if(this._permissionPointMap.get(s.id))throw new Error(`${s.id} PermissionPoint already exists`);return this._permissionPointMap.set(s.id,r?t:new Y.BehaviorSubject(s)),this._permissionPointUpdate$.next(s),!0}updatePermissionPoint(t,r){const s=this._permissionPointMap.get(t);if(!s)return;const o=s.getValue();o.value=r,o.status=Jr.DONE,s.next({...o}),this._permissionPointUpdate$.next(o)}clearPermissionMap(){this._permissionPointMap.clear()}getPermissionPoint(t){const r=this._permissionPointMap.get(t);if(r)return r.getValue()}getPermissionPoint$(t){const r=this._permissionPointMap.get(t);if(r)return r}composePermission$(t){const r=t.map(s=>{var i;const o=(i=this._permissionPointMap)==null?void 0:i.get(s);if(!o)throw new Error(`[PermissionService]: ${s} permissionPoint does not exist!`);return o.asObservable()});return Y.combineLatest(r).pipe(Cn.map(s=>s))}composePermission(t){return t.map(s=>{var i;const o=(i=this._permissionPointMap)==null?void 0:i.get(s);if(!o)throw new Error(`[PermissionService]: ${s} permissionPoint does not exist!`);return o.getValue()})}getAllPermissionPoint(){const t=new Map;return this._permissionPointMap.forEach((r,s)=>{t.set(s,r)}),t}}class ua extends Ae{constructor(){super(...arguments);_(this,"_resourceMap",new Map);_(this,"_register$",new Y.Subject);_(this,"register$",this._register$.asObservable())}getAllResourceHooks(){return[...this._resourceMap.values()]}getResources(t){return this.getAllResourceHooks().map(o=>{const i=o.toJson(t);return{name:o.pluginName,data:i}})}getResourcesByType(t,r){return this.getAllResourceHooks().filter(i=>i.businesses.includes(r)).map(i=>{const a=i.toJson(t);return{name:i.pluginName,data:a}})}registerPluginResource(t){const r=t.pluginName;if(this._resourceMap.has(r))throw new Error(`the pluginName is registered {${r}}`);return this._resourceMap.set(r,t),this._register$.next(t),Ne(()=>this._resourceMap.delete(r))}disposePluginResource(t){this._resourceMap.delete(t)}loadResources(t,r){this.getAllResourceHooks().forEach(s=>{var i;const o=(i=r==null?void 0:r.find(a=>a.name===s.pluginName))==null?void 0:i.data;if(o)try{const a=s.parseJson(o);s.onLoad(t,a)}catch{console.error("LoadResources Error!")}})}unloadResources(t){this.getAllResourceHooks().forEach(r=>{r.onUnLoad(t)})}dispose(){this._register$.complete(),this._resourceMap.clear()}}const zn=Ve("resource-manager-service");var _h=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,ph=(e,n,t,r)=>{for(var s=r>1?void 0:r?gh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&_h(n,t,s),s},ys=(e,n)=>(t,r)=>n(t,r,e);let br=class extends Ae{constructor(n,t){super();_(this,"saveWorkbook",n=>{const t=n.getUnitId(),r=this._resourceManagerService.getResources(t)||[],s=n.getSnapshot();return s.resources=r,s});this._resourceManagerService=n,this._univerInstanceService=t,this._init()}_init(){const n=r=>{r.businesses.forEach(s=>{switch(s){case J.UNRECOGNIZED:case J.UNIVER_UNKNOWN:case J.UNIVER_SLIDE:case J.UNIVER_DOC:{this._univerInstanceService.getAllUnitsForType(J.UNIVER_DOC).forEach(o=>{const a=(o.getSnapshot().resources||[]).find(l=>l.name===r.pluginName);if(a)try{const l=r.parseJson(a.data);r.onLoad(o.getUnitId(),l)}catch{console.error(`Load Document{${o.getUnitId()}} Resources{${r.pluginName}} Data Error.`)}});break}case J.UNIVER_SHEET:this._univerInstanceService.getAllUnitsForType(J.UNIVER_SHEET).forEach(o=>{const a=(o.getSnapshot().resources||[]).find(l=>l.name===r.pluginName);if(a)try{const l=r.parseJson(a.data);r.onLoad(o.getUnitId(),l)}catch{console.error(`Load Workbook{${o.getUnitId()}} Resources{${r.pluginName}} Data Error.`)}})}})};this._resourceManagerService.getAllResourceHooks().forEach(r=>{n(r)}),this.disposeWithMe(this._resourceManagerService.register$.subscribe(r=>{n(r)})),this.disposeWithMe(Ne(this._univerInstanceService.getTypeOfUnitAdded$(J.UNIVER_SHEET).subscribe(r=>{this._resourceManagerService.loadResources(r.getUnitId(),r.getSnapshot().resources)}))),this.disposeWithMe(Ne(this._univerInstanceService.getTypeOfUnitDisposed$(J.UNIVER_SHEET).subscribe(r=>{this._resourceManagerService.unloadResources(r.getUnitId())})))}saveDoc(n){const t=n.getUnitId(),r=this._resourceManagerService.getResourcesByType(t,J.UNIVER_DOC)||[],s=n.getSnapshot();return s.resources=r,s}};br=ph([ys(0,it(zn)),ys(1,it(Kt))],br);const ts=Ve("resource-loader-service");Kn(de.Ready,ts);class ns extends Ae{constructor(){super();_(this,"_currentTheme");_(this,"_currentTheme$",new Y.BehaviorSubject({}));_(this,"currentTheme$",this._currentTheme$.asObservable());this.disposeWithMe(Ne(()=>this._currentTheme$.complete()))}getCurrentTheme(){if(!this._currentTheme)throw new Error("[ThemeService]: current theme is not set!");return this._currentTheme}setTheme(t){this._currentTheme=t,this._currentTheme$.next(t)}}const Yn="__INTERNAL_EDITOR__",ca=`${Yn}DOCS_NORMAL`,ha=`${Yn}DOCS_FORMULA_BAR`,mh="__defaultDocumentZenEditorSpecialUnitId_20231218__",Eh=`\r
9
- `;function Rh(e){return`${Yn}${e}`}function Ch(e){return e.startsWith(Yn)}var Ih=Object.defineProperty,vh=Object.getOwnPropertyDescriptor,Oh=(e,n,t,r)=>{for(var s=r>1?void 0:r?vh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&Ih(n,t,s),s},or=(e,n)=>(t,r)=>n(t,r,e);const Xn=Ve("univer.undo-redo.service"),Sh=20;class da{dispose(){}async dispatchToHandlers(){return!1}}const fa="univer.command.redo",_a="univer.command.undo",ga=new class extends da{constructor(){super(...arguments);_(this,"type",hn.COMMAND);_(this,"id",_a)}async handler(n){const t=n.get(Xn),r=t.pitchTopUndoElement();if(!r)return!1;const s=n.get(dn);return Hr(r.undoMutations,s)?(t.popUndoToRedo(),!0):!1}},pa=new class extends da{constructor(){super(...arguments);_(this,"type",hn.COMMAND);_(this,"id",fa)}async handler(n){const t=n.get(Xn),r=t.pitchTopRedoElement();if(!r)return!1;const s=n.get(dn);return Hr(r.redoMutations,s)?(t.popRedoToUndo(),!0):!1}};exports.LocalUndoRedoService=class extends Ae{constructor(t,r,s){super();_(this,"undoRedoStatus$");_(this,"_undoRedoStatus$",new Y.BehaviorSubject({undos:0,redos:0}));_(this,"_undoStacks",new Map);_(this,"_redoStacks",new Map);_(this,"_batchingStatus",new Map);this._univerInstanceService=t,this._commandService=r,this._contextService=s,this.undoRedoStatus$=this._undoRedoStatus$.asObservable(),this.disposeWithMe(this._commandService.registerCommand(ga)),this.disposeWithMe(this._commandService.registerCommand(pa)),this.disposeWithMe(Ne(()=>this._undoRedoStatus$.complete())),this.disposeWithMe(Ne(this._univerInstanceService.focused$.subscribe(()=>this._updateStatus())))}pushUndoRedo(t){const{unitID:r}=t,s=this._getRedoStack(r,!0),o=this._getUndoStack(r,!0);if(s.length=0,this._batchingStatus.has(t.unitID)){const a=this._batchingStatus.get(t.unitID),l=this._pitchUndoElement(t.unitID);a===0||!l?(i(t),this._batchingStatus.set(t.unitID,1)):this._tryBatchingElements(l,t)}else i(t);function i(a){o.push(a),o.length>Sh&&o.splice(0,1)}this._updateStatus()}clearUndoRedo(t){const r=this._getRedoStack(t);r&&(r.length=0);const s=this._getUndoStack(t);s&&(s.length=0),this._updateStatus()}pitchTopUndoElement(){const t=this._getFocusedUnitId();return this._pitchUndoElement(t)}pitchTopRedoElement(){const t=this._getFocusedUnitId();return this._pitchRedoElement(t)}_pitchUndoElement(t){const r=this._getUndoStack(t);return r!=null&&r.length?r[r.length-1]:null}_pitchRedoElement(t){const r=this._getRedoStack(t);return r!=null&&r.length?r[r.length-1]:null}popUndoToRedo(){const r=this._getUndoStackForFocused().pop();r&&(this._getRedoStackForFocused().push(r),this._updateStatus())}popRedoToUndo(){const r=this._getRedoStackForFocused().pop();r&&(this._getUndoStackForFocused().push(r),this._updateStatus())}__tempBatchingUndoRedo(t){if(this._batchingStatus.has(t))throw new Error("[LocalUndoRedoService]: cannot batching undo redo twice at the same time!");return this._batchingStatus.set(t,0),Ne(()=>this._batchingStatus.delete(t))}_updateStatus(){var o,i;const t=this._getFocusedUnitId(),r=t&&((o=this._undoStacks.get(t))==null?void 0:o.length)||0,s=t&&((i=this._redoStacks.get(t))==null?void 0:i.length)||0;this._undoRedoStatus$.next({undos:r,redos:s})}_getUndoStack(t,r=!1){let s=this._undoStacks.get(t);return!s&&r&&(s=[],this._undoStacks.set(t,s)),s||null}_getRedoStack(t,r=!1){let s=this._redoStacks.get(t);return!s&&r&&(s=[],this._redoStacks.set(t,s)),s||null}_getUndoStackForFocused(){const t=this._getFocusedUnitId();if(!t)throw new Error("No focused univer instance!");return this._getUndoStack(t,!0)}_getRedoStackForFocused(){const t=this._getFocusedUnitId();if(!t)throw new Error("No focused univer instance!");return this._getRedoStack(t,!0)}_tryBatchingElements(t,r){t.redoMutations.push(...r.redoMutations),t.undoMutations.push(...r.undoMutations)}_getFocusedUnitId(){var i,a,l,h;let t="";const r=this._contextService.getContextValue(tn),s=this._contextService.getContextValue(ra),o=this._contextService.getContextValue(na);return r?s?t=ha:o?t=ca:t=(a=(i=this._univerInstanceService.getFocusedUnit())==null?void 0:i.getUnitId())!=null?a:"":t=(h=(l=this._univerInstanceService.getFocusedUnit())==null?void 0:l.getUnitId())!=null?h:"",t}};exports.LocalUndoRedoService=Oh([or(0,Kt),or(1,dn),or(2,cn)],exports.LocalUndoRedoService);const ma=Symbol("DependentOn");class Ar extends Ae{onStarting(n){}onReady(){}onRendered(){}onSteady(){}getUniverInstanceType(){return this.constructor.type}getPluginName(){return this.constructor.pluginName}}_(Ar,"pluginName"),_(Ar,"type",J.UNIVER_UNKNOWN);class Nh{constructor(){_(this,"_plugins",[])}addPlugin(n){this._plugins.push(n)}removePlugins(){const n=this._plugins.slice();return this._plugins.length=0,n}forEachPlugin(n){this._plugins.forEach(n)}}class wh{constructor(){_(this,"_pluginsRegistered",[])}registerPlugin(n,t){this._pluginsRegistered.push({plugin:n,options:t})}getRegisterPlugins(){return this._pluginsRegistered.slice()}removePlugins(){this._pluginsRegistered=[]}}var bh=Object.defineProperty,Ah=Object.getOwnPropertyDescriptor,Ea=(e,n,t,r)=>{for(var s=r>1?void 0:r?Ah(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&bh(n,t,s),s},Zt=(e,n)=>(t,r)=>n(t,r,e);const Th=4;function yh(...e){return function(n){n[ma]=e}}exports.PluginService=class{constructor(n){_(this,"_pluginHolderForUniver");_(this,"_pluginHoldersForTypes",new Map);_(this,"_seenPlugins",new Set);_(this,"_flushTimer");this._injector=n,this._pluginHolderForUniver=this._injector.createInstance(kn,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this)),this._pluginHolderForUniver.start()}dispose(){this._clearFlushTimer();for(const n of this._pluginHoldersForTypes.values())n.dispose();this._pluginHolderForUniver.dispose()}registerPlugin(n,t){this._assertPluginValid(n),this._scheduleInitPlugin();const{type:r}=n;r===J.UNIVER_UNKNOWN?(this._pluginHolderForUniver.register(n,t),this._pluginHolderForUniver.flush()):this._ensurePluginHolderForType(r).register(n,t)}startPluginForType(n){this._ensurePluginHolderForType(n).start()}_ensurePluginHolderForType(n){if(!this._pluginHoldersForTypes.has(n)){const t=this._injector.createInstance(kn,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this));return this._pluginHoldersForTypes.set(n,t),t}return this._pluginHoldersForTypes.get(n)}_immediateInitPlugin(n){this._seenPlugins.add(n.pluginName),this._ensurePluginHolderForType(n.type).immediateInitPlugin(n)}_checkPluginSeen(n){return this._seenPlugins.has(n.pluginName)}_assertPluginValid(n){const{type:t,pluginName:r}=n;if(t===J.UNRECOGNIZED)throw new Error(`[PluginService]: invalid plugin type for ${n}. Please assign a "type" to your plugin.`);if(r==="")throw new Error(`[PluginService]: no plugin name for ${n}. Please assign a "pluginName" to your plugin.`);if(this._seenPlugins.has(r))throw new Error(`[PluginService]: duplicated plugin name for "${r}". Maybe a plugin that dependents on "${r} has already registered it. In that case please register "${r}" before the that plugin.`);this._seenPlugins.add(n.pluginName)}_scheduleInitPlugin(){this._flushTimer===void 0&&(this._flushTimer=setTimeout(()=>{this._pluginHolderForUniver.started||this._pluginHolderForUniver.start(),this._flushPlugins(),this._clearFlushTimer()},Th))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_flushPlugins(){this._pluginHolderForUniver.flush();for(const[n,t]of this._pluginHoldersForTypes)t.started&&t.flush()}};exports.PluginService=Ea([Zt(0,it(pt))],exports.PluginService);let kn=class extends Ae{constructor(n,t,r,s,o,i){super();_(this,"_started",!1);_(this,"_pluginRegistry",new wh);_(this,"_pluginStore",new Nh);_(this,"_awaitingPlugins",[]);this._checkPluginRegistered=n,this._registerPlugin=t,this._logService=r,this._injector=s,this._lifecycleService=o,this._lifecycleInitializerService=i,this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(Y.skip(1)).subscribe(a=>{this._awaitingPlugins.forEach(l=>this._runStage(l,a))}))}get started(){return this._started}dispose(){super.dispose(),this._pluginStore.forEachPlugin(n=>n.dispose()),this._pluginStore.removePlugins(),this._pluginRegistry.removePlugins(),this._awaitingPlugins.length=0}register(n,t){this._pluginRegistry.registerPlugin(n,t)}immediateInitPlugin(n){const t=this._initPlugin(n,void 0);this._pluginsRunLifecycle([t])}start(){this._started||(this._started=!0,this.flush())}flush(){if(!this._started)return;const n=this._pluginRegistry.getRegisterPlugins().map(({plugin:t,options:r})=>this._initPlugin(t,r));n.length&&(this._pluginsRunLifecycle(n),this._pluginRegistry.removePlugins())}_initPlugin(n,t){const r=n[ma];if(r){const o=()=>{const i=r.find(a=>!this._checkPluginRegistered(a));return i?(this._logService.warn("[PluginService]",`plugin "${n.pluginName}" depends on "${i.pluginName}" which is not registered. Univer will automatically register it with default configuration.`),this._registerPlugin(i,void 0),!0):!1};for(;o(););}const s=this._injector.createInstance(n,t);return this._pluginStore.addPlugin(s),s}_pluginsRunLifecycle(n){aa(this._lifecycleService.stage).subscribe(t=>this._runStage(n,t)),this._awaitingPlugins.push(n)}_runStage(n,t){n.forEach(r=>{switch(t){case de.Starting:r.onStarting(this._injector);break;case de.Ready:r.onReady();break;case de.Rendered:r.onRendered();break;case de.Steady:r.onSteady();break}}),this._lifecycleInitializerService.initModulesOnStage(t)}};kn=Ea([Zt(2,St),Zt(3,it(pt)),Zt(4,it(exports.LifecycleService)),Zt(5,it(exports.LifecycleInitializerService))],kn);function Ra(e,n){if(!n)return e;const t=[];for(const r of e){const s=n.find(([o])=>o===r[0]);if(s){if(s[1]===null)continue;t.push([r[0],s[1]])}else t.push(r)}return t}const Tr={[je.Editor]:"Editor",[je.Owner]:"Owner",[je.Reader]:"Reader",[je.UNRECOGNIZED]:"UNRECOGNIZED"},Fn=e=>e?{userID:`${Tr[e]}_${x.generateRandomId(8)}`,name:Tr[e],avatar:""}:{userID:"",name:"",avatar:"",anonymous:!0,canBindAnonymous:!1},ir=(e,n)=>e.startsWith(Tr[n]);var Dh=Object.defineProperty,Mh=Object.getOwnPropertyDescriptor,Uh=(e,n,t,r)=>{for(var s=r>1?void 0:r?Mh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&Dh(n,t,s),s};exports.UserManagerService=class{constructor(){_(this,"_model",new Map);_(this,"_userChange$",new Y.Subject);_(this,"userChange$",this._userChange$.asObservable());_(this,"_currentUser$",new Y.BehaviorSubject(Fn()));_(this,"currentUser$",this._currentUser$.asObservable())}getCurrentUser(){return this._currentUser$.getValue()}setCurrentUser(n){this.addUser(n),this._currentUser$.next(n)}addUser(n){this._model.set(n.userID,n),this._userChange$.next({type:"add",user:n})}getUser(n,t){const r=this._model.get(n);if(r)return r;t&&t()}delete(n){const t=this.getUser(n);this._model.delete(n),t&&this._userChange$.next({type:"delete",user:t})}clear(){this._model.clear(),this._userChange$.next({type:"clear"})}list(){return Array.from(this._model.values())}};exports.UserManagerService=Uh([sa(de.Starting,exports.UserManagerService)],exports.UserManagerService);var Lh=Object.defineProperty,xh=Object.getOwnPropertyDescriptor,Ph=(e,n,t,r)=>{for(var s=r>1?void 0:r?xh(n,t):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&Lh(n,t,s),s},Ds=(e,n)=>(t,r)=>n(t,r,e);exports.AuthzIoLocalService=class{constructor(n,t){_(this,"_permissionMap",new Map([]));this._resourceManagerService=n,this._userManagerService=t,this._initSnapshot(),this._initDefaultUser()}_initDefaultUser(){const n=this._userManagerService.getCurrentUser();n&&n.userID||this._userManagerService.setCurrentUser(Fn(je.Owner))}_getRole(n){const t=this._userManagerService.getCurrentUser();return t?ir(t.userID,n):!1}_initSnapshot(){this._resourceManagerService.registerPluginResource({toJson:n=>{const t=[...this._permissionMap.keys()].reduce((r,s)=>{const o=this._permissionMap.get(s);return r[s]=o,r},{});return JSON.stringify(t)},parseJson:n=>JSON.parse(n),pluginName:"SHEET_AuthzIoMockService_PLUGIN",businesses:[J.UNIVER_SHEET,J.UNIVER_DOC,J.UNIVER_SLIDE],onLoad:(n,t)=>{for(const r in t)this._permissionMap.set(r,t[r])},onUnLoad:()=>{this._permissionMap.clear()}})}async create(n){const t=x.generateRandomId(8);switch(n.objectType){case Nn.SelectRange:{const r=n.selectRangeObject;this._permissionMap.set(t,{...r,objectType:n.objectType});break}case Nn.Worksheet:{const r=n.worksheetObject;this._permissionMap.set(t,{...r,objectType:n.objectType,readScope:Oi.SomeCollaborator})}}return t}async allowed(n){var t;if(this._permissionMap.has(n.objectID)){const r=this._permissionMap.get(n.objectID);if(r&&r.objectType===Nn.Worksheet)return(t=r==null?void 0:r.strategies)==null?void 0:t.map(s=>({action:s.action,allowed:s.role===je.Editor}))}return n.actions.map(r=>({action:r,allowed:this._getRole(je.Owner)||this._getRole(je.Editor)}))}async batchAllowed(n){const t=this._userManagerService.getCurrentUser(),r=n.map(s=>({unitID:s.unitID,objectID:s.objectID,actions:s.actions.map(o=>({action:o,allowed:!1}))}));return t&&(ir(t.userID,je.Owner)||ir(t.userID,je.Editor))?n.map(s=>({unitID:s.unitID,objectID:s.objectID,actions:s.actions.map(o=>({action:o,allowed:!0}))})):r}async list(n){const t=[];return n.objectIDs.forEach(r=>{const s=this._permissionMap.get(r);if(s){const o={objectID:r,unitID:n.unitID,objectType:s.objectType,name:s.name,shareOn:!1,shareRole:je.Owner,shareScope:-1,creator:Fn(je.Owner),strategies:[],actions:n.actions.map(i=>({action:i,allowed:this._getRole(je.Owner)||this._getRole(je.Editor)}))};t.push(o)}}),t}async listCollaborators(){return[]}async listRoles(){return{roles:[],actions:[]}}async deleteCollaborator(){}async update(n){}async updateCollaborator(){}async createCollaborator(){}async putCollaborators(n){}};exports.AuthzIoLocalService=Ph([Ds(0,zn),Ds(1,it(exports.UserManagerService))],exports.AuthzIoLocalService);const Ca=Ve("IAuthzIoIoService");class kh{constructor(n={},t){_(this,"_startedTypes",new Set);_(this,"_injector");const r=this._injector=Fh(t,n==null?void 0:n.override),{theme:s,locale:o,locales:i,logLevel:a}=n;s&&this._injector.get(ns).setTheme(s),i&&this._injector.get(nn).load(i),o&&this._injector.get(nn).setLocale(o),a&&this._injector.get(St).setLogLevel(a),this._init(r)}get _univerInstanceService(){return this._injector.get(Kt)}get _pluginService(){return this._injector.get(exports.PluginService)}__getInjector(){return this._injector}dispose(){this._injector.dispose()}setLocale(n){this._injector.get(nn).setLocale(n)}createUnit(n,t){return this._univerInstanceService.createUnit(n,t)}createUniverSheet(n){return this._univerInstanceService.createUnit(J.UNIVER_SHEET,n)}createUniverDoc(n){return this._univerInstanceService.createUnit(J.UNIVER_DOC,n)}createUniverSlide(n){return this._univerInstanceService.createUnit(J.UNIVER_SLIDE,n)}_init(n){this._univerInstanceService.registerCtorForType(J.UNIVER_SHEET,exports.Workbook),this._univerInstanceService.registerCtorForType(J.UNIVER_DOC,xt),this._univerInstanceService.registerCtorForType(J.UNIVER_SLIDE,Zr);const t=n.get(Kt);t.__setCreateHandler((r,s,o)=>{if(!this._startedTypes.has(r)){this._pluginService.startPluginForType(r),this._startedTypes.add(r);const a=n.createInstance(o,s);return t.__addUnit(a),this._tryProgressToReady(),a}const i=n.createInstance(o,s);return t.__addUnit(i),i})}_tryProgressToReady(){this._injector.get(exports.LifecycleService).stage<de.Ready&&(this._injector.get(exports.LifecycleService).stage=de.Ready)}registerPlugin(n,t){this._pluginService.registerPlugin(n,t)}}function Fh(e,n){const t=Ra([[Ki],[nn],[ns],[exports.LifecycleService],[exports.LifecycleInitializerService],[exports.PluginService],[exports.UserManagerService],[Kt,{useClass:exports.UniverInstanceService}],[es,{useClass:la}],[St,{useClass:Ei,lazy:!0}],[dn,{useClass:exports.CommandService}],[Xn,{useClass:exports.LocalUndoRedoService,lazy:!0}],[Gi,{useClass:Vi}],[cn,{useClass:pi}],[zn,{useClass:ua,lazy:!0}],[ts,{useClass:br,lazy:!0}],[Ca,{useClass:exports.AuthzIoLocalService,lazy:!0}]],n);return e?e.createChild(t):new pt(t)}const Hh=(e,n)=>n.length===e.length&&!e.some(t=>n.some(r=>!vt.equals(r,t))),jh=(e,n)=>n.length===e.length&&e.every((t,r)=>{const s=n[r];return s.unitId===t.unitId&&s.sheetId===t.sheetId&&vt.equals(t.range,s.range)});function $h(e,n){if(Object.is(e,n))return!0;if(typeof e!="object"||!e||typeof n!="object"||!n)return!1;const t=Object.keys(e),r=Object.keys(n);if(t.length!==r.length)return!1;const s=Object.prototype.hasOwnProperty.bind(n);for(let o=0;o<t.length;o++){const i=t[o];if(!s(i))return!1;const a=e[i],l=n[i];if(a!==l)return!1}return!0}function Ia(e){return/^-?\d+(\.\d+)?$/.test(e)}function Wh(e){return Ia(e)?Number(e)<=Number.MAX_SAFE_INTEGER:!1}function Bh(e){return["true","false"].includes(e.toLowerCase())}function Gh(e,n){return n.forEach(t=>e.add(t)),e}function Vh(e,n=16){let t=0,r=null;return function(...o){const i=Date.now();i-t<n?(r&&clearTimeout(r),r=setTimeout(()=>{t=i,e.apply(this,o)},n)):(t=i,e.apply(this,o))}}function Kh(e){const n=new MessageChannel;let t=!1;const r=()=>{t||e()};return n.port1.onmessage=r,n.port2.postMessage(null),()=>{t=!0,n.port1.close(),n.port2.close()}}var va=(e=>(e[e.TEXT=0]="TEXT",e[e.ARROW=1]="ARROW",e[e.CUSTOM=2]="CUSTOM",e))(va||{});function zh(e,n,t){if(n==="")return e;const r={id:"mock-id",body:e,documentStyle:{}},s=new xt(r),o=n.length;let i;for(;(i=s.getBody().dataStream.indexOf(n))>=0;){const l=new Ot,h=Lt.getInstance();if(i>0&&l.retain(i),t.length>0){const c=s.sliceBody(i,i+o),u={dataStream:t};Array.isArray(c==null?void 0:c.textRuns)&&c.textRuns.length&&(u.textRuns=[{...c.textRuns[0],st:0,ed:t.length}]),l.insert(t.length,u)}l.delete(o),s.apply(h.editOp(l.serialize()))}const a=s.getBody();return s.dispose(),a}class Oa{constructor(){_(this,"skipNextObservers",!1);_(this,"lastReturnValue");_(this,"isStopPropagation",!1)}stopPropagation(){this.isStopPropagation=!0}}class Yh extends Y.Subject{constructor(){super(...arguments);_(this,"_sortedObservers",[])}subscribe(){throw new Error("[EventSubject]: please use `subscribeEvent` instead of `subscribe` method for `EventSubject`.")}next(){throw new Error("[EventSubject]: please use `emitEvent` instead of `next` method for `EventSubject`.")}unsubscribe(){super.unsubscribe(),this._sortedObservers.length=0}complete(){super.complete(),this._sortedObservers.length=0}subscribeEvent(t){let r;typeof t=="function"?r={next:([o,i])=>t(o,i)}:r=t;const s=super.subscribe(r);return this._sortedObservers.push(r),this._sortedObservers.sort((o,i)=>{var a,l;return((a=o.priority)!=null?a:0)-((l=i.priority)!=null?l:0)}),s.add(()=>this._sortedObservers=this._sortedObservers.filter(o=>o!==r)),s}clearObservers(){this._sortedObservers.forEach(t=>{var r;return(r=t.complete)==null?void 0:r.call(t)}),this._sortedObservers.length=0}emitEvent(t){var r;if(!this.closed){const s=new Oa;s.lastReturnValue=t;for(const o of this._sortedObservers){const i=(r=o.next)==null?void 0:r.call(o,[t,s]);if(s.lastReturnValue=i,s.skipNextObservers)return{handled:!0,lastReturnValue:s.lastReturnValue,stopPropagation:s.isStopPropagation}}return{handled:this._sortedObservers.length>0,lastReturnValue:s.lastReturnValue,stopPropagation:s.isStopPropagation}}throw new Error("[EventSubject]: cannot emit event on a closed subject.")}}function Xh(e){return new Y.Observable(n=>{const t=e.subscribeEvent(r=>{n.next(r)});return()=>t.unsubscribe()})}const Qh=Ve("ILocalStorageService");function qh(e){return`sheet_interceptor_${e}`}const Sa=e=>function(n,t){let r=-1;function s(o,i){if(o<=r)throw new Error("[SheetInterceptorService]: next() called multiple times!");return r=o,o===e.length?i:e[o].handler(i,t,s.bind(null,o+1))}return s(0,n)};class Zh{constructor(n){_(this,"_interceptorsByName",new Map);_(this,"_interceptorPoints");this._interceptorPoints=n}fetchThroughInterceptors(n){const t=n,r=this._interceptorsByName.get(t);return Sa(r||[])}intercept(n,t){const r=n;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);const s=this._interceptorsByName.get(r);return s.push(t),this._interceptorsByName.set(r,s.sort((o,i)=>{var a,l;return((a=i.priority)!=null?a:0)-((l=o.priority)!=null?l:0)})),()=>Bn(this._interceptorsByName.get(r),t)}getInterceptPoints(){return this._interceptorPoints}}const Jh=Ve("univer.snapshot-server-service");class ed{constructor(){_(this,"_sheetBlockCache",new Map)}getUnitOnRev(n,t){return Promise.resolve({snapshot:{unitID:"",type:J.UNIVER_SHEET,rev:0,workbook:void 0,doc:void 0},changesets:[],error:{code:Ze.OK,message:""}})}getSheetBlock(n,t){const r=this._sheetBlockCache.get(t.blockID);return Promise.resolve({block:r,error:{code:Ze.OK,message:""}})}fetchMissingChangesets(n,t){return Promise.resolve({changesets:[],error:{code:Ze.OK,message:""}})}getResourcesRequest(n,t){return Promise.resolve({resources:{},error:{code:Ze.OK,message:""}})}saveSnapshot(n,t){return Promise.resolve({error:{code:Ze.OK,message:""}})}saveSheetBlock(n,t){const{block:r}=t;return r?(this._sheetBlockCache.set(r.id,r),Promise.resolve({error:{code:Ze.OK,message:""},blockID:r.id})):Promise.resolve({error:{code:Ze.UNDEFINED,message:"block is required"},blockID:""})}saveChangeset(n,t){return Promise.resolve({error:{code:Ze.OK,message:""},concurrent:[]})}}function td(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(n,t)=>String.fromCharCode(Number.parseInt(t,16))))}function rs(e){return decodeURIComponent(Array.prototype.map.call(atob(e),n=>`%${`00${n.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}const fn=new TextEncoder,Qn=new TextDecoder;function Na(e){const n=x.deepClone(e);return delete n.id,delete n.name,delete n.rowCount,delete n.columnCount,delete n.cellData,fn.encode(JSON.stringify(n))}function wa(e){const n=x.deepClone(e);return delete n.id,delete n.rev,delete n.name,delete n.sheetOrder,delete n.sheets,fn.encode(JSON.stringify(n))}function nd(e){const n=x.deepClone(e);return delete n.id,delete n.rev,delete n.title,delete n.resources,fn.encode(JSON.stringify(n))}function Ms(e){return JSON.parse(Qn.decode(e))}function rd(e){return JSON.parse(typeof e=="string"?rs(e):Qn.decode(e))}function sd(e){return JSON.parse(typeof e=="string"?rs(e):Qn.decode(e))}const ar=256*20;function ba(e,n){const t=new ot(e),r=t.getLength(),s=[];let o=0;for(;o<r;){const i=Math.min(o+ar,r-1),a=t.getSlice(o,Math.min(o+ar,r-1),0,n),l=od(a);s.push({id:x.generateRandomId(19,"0123456789"),startRow:o,endRow:i,data:l}),o+=ar}return s}function od(e){const n=e.getData();return fn.encode(JSON.stringify(n))}async function id(e,n,t,r,s){const o={},i={};if(!await Promise.all(Object.entries(n.sheets).map(async([u,d])=>{const f={id:d.id,type:Hn.GRID,name:d.name,rowCount:d.rowCount,columnCount:d.columnCount,originalMeta:Na(d)};if(i[u]=f,d.cellData){const p=ba(d.cellData,d.rowCount),m=await Promise.all(p.map(S=>s.saveSheetBlock(e,{unitID:t,type:J.UNIVER_SHEET,block:S})));if(m.some(S=>{var y;return((y=S.error)==null?void 0:y.code)!==Ze.OK}))return!1;o[u]={sheetID:u,blocks:m.map(S=>S.blockID)}}return!0})))throw new Error("[transformWorkbookDataToSnapshot()]: Failed to save sheet blocks.");const l=wa(n),h={unitID:n.id,rev:r,creator:"",name:n.name,sheetOrder:n.sheetOrder,sheets:i,blockMeta:o,resources:n.resources||[],originalMeta:l};return{snapshotRes:{unitID:t,rev:h.rev,type:J.UNIVER_SHEET,workbook:h,doc:void 0}}}async function ad(e,n,t,r,s){var d,f;const o={},i={};if(!await Promise.all(Object.entries(n.sheets).map(async([p,m])=>{const S={id:m.id,type:Hn.GRID,name:m.name,rowCount:m.rowCount,columnCount:m.columnCount,originalMeta:Na(m)};if(i[p]=S,m.cellData){const y=ba(m.cellData,m.rowCount),ee=await Promise.all(y.map(ge=>s.saveSheetBlock(e,{unitID:t,type:J.UNIVER_SHEET,block:ge})));if(ee.some(ge=>{var ce;return((ce=ge.error)==null?void 0:ce.code)!==Ze.OK}))return!1;o[p]={sheetID:p,blocks:ee.map(ge=>ge.blockID)}}return!0})))throw new Error("[transformWorkbookDataToSnapshot()]: Failed to save sheet blocks.");const l=wa(n),h={unitID:n.id,rev:r,creator:"",name:n.name,sheetOrder:n.sheetOrder,sheets:i,blockMeta:o,resources:n.resources||[],originalMeta:l},c={unitID:t,rev:h.rev,type:J.UNIVER_SHEET,workbook:h,doc:void 0},u=await s.saveSnapshot(e,{unitID:t,type:J.UNIVER_SHEET,snapshot:c});if(vi(u.error))throw new Error(`transformWorkbookDataToSnapshot(): Failed to save snapshot.
10
- ErrorCode: ${(d=u.error)==null?void 0:d.code}:${(f=u.error)==null?void 0:f.message}`);return{snapshot:c}}function ld(e,n,t){const r=e.workbook;if(!r)throw new Error("");const s={};Object.entries(r.sheets).forEach(([l,h])=>{const c=Ms(h.originalMeta);s[l]={id:h.id,name:h.name,rowCount:h.rowCount,columnCount:h.columnCount,...c}});const o=new Map;n.forEach(l=>{o.set(l.id,l)}),r.blockMeta&&Object.entries(r.blockMeta).forEach(([l,h])=>{var d;const c=s[l];c.cellData={};const u=[];(d=h.blocks)==null||d.forEach(f=>{const p=o.get(f);if(p)u.push(p);else throw new Error("")}),u.forEach(f=>{const p=rd(f.data);Object.entries(p).forEach(([m,S])=>{const y=c.cellData[+m]={};Object.entries(S).forEach(([ee,ge])=>{y[+ee]=ge})})})});const i=Ms(r.originalMeta);return{id:e.unitID,rev:r.rev,name:r.name,sheetOrder:r.sheetOrder,appVersion:"",locale:Pt.EN_US,sheets:s,styles:{},resources:r.resources||[],...i}}function ud(e){const n=e.doc;if(n==null)throw new Error("transformSnapshotToDocumentData(): snapshot.doc is undefined.");const{unitID:t,rev:r,name:s,originalMeta:o,resources:i=[]}=n,{body:a,documentStyle:l={},settings:h={},drawings:c={},drawingsOrder:u=[]}=sd(o);return{id:t,rev:r,locale:Pt.EN_US,title:s,body:a,documentStyle:l,settings:h,drawings:c,drawingsOrder:u,resources:i}}async function cd(e,n,t,r,s){var l,h,c;const o={unitID:n.id,rev:r,creator:"",name:(l=n.title)!=null?l:"",resources:n.resources||[],originalMeta:nd(n)},i={unitID:t,rev:o.rev,type:J.UNIVER_DOC,workbook:void 0,doc:o},a=await s.saveSnapshot(e,{unitID:t,type:J.UNIVER_DOC,snapshot:i});if(vi(a.error))throw new Error(`transformDocumentDataToSnapshot(): Failed to save snapshot.
11
- ErrorCode: ${(h=a.error)==null?void 0:h.code}:${(c=a.error)==null?void 0:c.message}`);return{snapshot:i}}async function hd(e,n){const t=e.workbook;if(!t)throw new Error("Workbook metadata is not available");const r=[],s=[];return Object.entries(t.blockMeta).forEach(([o,i])=>{const a=i.blocks.map(async l=>{const h={unitID:t.unitID,type:J.UNIVER_SHEET,blockID:l},{block:c}=await n.getSheetBlock({},h);if(c)r.push(c);else throw new Error("Block not found")});s.push(...a)}),await Promise.all(s),r}var Aa=(e=>(e[e.INFO=0]="INFO",e[e.STOP=1]="STOP",e[e.WARNING=2]="WARNING",e))(Aa||{}),Ta=(e=>(e[e.DISABLED=0]="DISABLED",e[e.FULL_ALPHA=1]="FULL_ALPHA",e[e.FULL_HANGUL=2]="FULL_HANGUL",e[e.FULL_KATAKANA=3]="FULL_KATAKANA",e[e.HALF_ALPHA=4]="HALF_ALPHA",e[e.HALF_HANGUL=5]="HALF_HANGUL",e[e.HALF_KATAKANA=6]="HALF_KATAKANA",e[e.HIRAGANA=7]="HIRAGANA",e[e.NO_CONTROL=8]="NO_CONTROL",e[e.OFF=9]="OFF",e[e.ON=10]="ON",e))(Ta||{}),ya=(e=>(e.BETWEEN="between",e.EQUAL="equal",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.NOT_BETWEEN="notBetween",e.NOT_EQUAL="notEqual",e))(ya||{}),Da=(e=>(e.CUSTOM="custom",e.LIST="list",e.LIST_MULTIPLE="listMultiple",e.NONE="none",e.TEXT_LENGTH="textLength",e.DATE="date",e.TIME="time",e.WHOLE="whole",e.DECIMAL="decimal",e.CHECKBOX="checkbox",e))(Da||{}),Ma=(e=>(e.VALID="valid",e.INVALID="invalid",e.VALIDATING="validating",e))(Ma||{});const dd=["script","style","meta","comment","link"];function fd(e){return!(e.length===0||e.length>31||e.startsWith("'")||e.endsWith("'")||/[:\\\/\?\*\[\]]/.test(e))}ja();exports.ABCToNumber=tu;exports.AbsoluteRefType=Se;exports.ActionIterator=wr;exports.AlignTypeH=bo;exports.AlignTypeV=Ao;exports.ArrangeTypeEnum=Do;exports.ArrowsAndMarkersShapes=qs;exports.AutoFillSeries=Fs;exports.BaselineOffset=Gt;exports.BasicShapes=Qs;exports.BlockType=ao;exports.BooleanNumber=K;exports.BorderStyleTypes=he;exports.BorderType=Hs;exports.BulletAlignment=Rt;exports.COLORS=lr;exports.CellValueType=Mt;exports.ClientSnapshotServerService=ed;exports.Color=Ut;exports.ColorBuilder=$n;exports.ColorKit=rt;exports.ColorType=qe;exports.ColumnSeparatorType=ho;exports.CommandType=hn;exports.CommonHideTypes=js;exports.ConfigService=Vi;exports.ContentAlignment=vo;exports.ContextService=pi;exports.CopyPasteType=$s;exports.CustomDecorationType=io;exports.CustomRangeType=oo;exports.DEFAULT_CELL=du;exports.DEFAULT_DOC=qr;exports.DEFAULT_DOCUMENT_SUB_COMPONENT_ID=Wa;exports.DEFAULT_EMPTY_DOCUMENT_VALUE=Eh;exports.DEFAULT_RANGE=cu;exports.DEFAULT_RANGE_ARRAY=uu;exports.DEFAULT_SELECTION=hu;exports.DEFAULT_SLIDE=Qo;exports.DEFAULT_STYLES=vn;exports.DEFAULT_WORKSHEET_COLUMN_COUNT=Xi;exports.DEFAULT_WORKSHEET_COLUMN_COUNT_KEY=Bc;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=Ji;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY=zc;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH=qi;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY=Vc;exports.DEFAULT_WORKSHEET_ROW_COUNT=Yi;exports.DEFAULT_WORKSHEET_ROW_COUNT_KEY=Wc;exports.DEFAULT_WORKSHEET_ROW_HEIGHT=Qi;exports.DEFAULT_WORKSHEET_ROW_HEIGHT_KEY=Gc;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=Zi;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY=Kc;exports.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=ha;exports.DOCS_NORMAL_EDITOR_UNIT_ID_KEY=ca;exports.DOCS_ZEN_EDITOR_UNIT_ID_KEY=mh;exports.DashStyleType=Ro;exports.DataStreamTreeNodeType=Si;exports.DataStreamTreeTokenType=gt;exports.DataValidationErrorStyle=Aa;exports.DataValidationImeMode=Ta;exports.DataValidationOperator=ya;exports.DataValidationRenderMode=va;exports.DataValidationStatus=Ma;exports.DataValidationType=Da;exports.DependentOn=yh;exports.DesktopLogService=Ei;exports.DeveloperMetadataVisibility=Ws;exports.Dimension=Bs;exports.Direction=Gs;exports.Disposable=Ae;exports.DisposableCollection=Mr;exports.DocStyleType=ro;exports.DocumentDataModel=xt;exports.DocumentFlavor=lo;exports.DrawingTypeEnum=Mo;exports.EDITOR_ACTIVATED=na;exports.EXTENSION_NAMES=qo;exports.Entry=ur;exports.EntryIterator=Ko;exports.ErrorService=Ki;exports.EventState=Oa;exports.EventSubject=Yh;exports.FOCUSING_COMMON_DRAWINGS=ah;exports.FOCUSING_DOC=wn;exports.FOCUSING_EDITOR_BUT_HIDDEN=nh;exports.FOCUSING_EDITOR_INPUT_FORMULA=rh;exports.FOCUSING_EDITOR_STANDALONE=oh;exports.FOCUSING_FORMULA_EDITOR=ra;exports.FOCUSING_SHEET=tn;exports.FOCUSING_SLIDE=bn;exports.FOCUSING_UNIVER_EDITOR=sh;exports.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE=ih;exports.FollowNumberWithType=so;exports.FontItalic=Tn;exports.FontStyleType=Oo;exports.FontWeight=yn;exports.FormatType=Vs;exports.GlyphType=Jt;exports.GridType=uo;exports.HLSColor=to;exports.HorizontalAlign=Dt;exports.IAuthzIoService=Ca;exports.ICommandService=dn;exports.IConfigService=Gi;exports.IContextService=cn;exports.ILocalStorageService=Qh;exports.ILogService=St;exports.IPermissionService=es;exports.IResourceLoaderService=ts;exports.IResourceManagerService=zn;exports.ISnapshotServerService=Jh;exports.IUndoRedoService=Xn;exports.IUniverInstanceService=Kt;exports.Inject=it;exports.Injector=pt;exports.InterceptorManager=Zh;exports.InterpolationPointType=Ks;exports.JSON1=Lc;exports.JSONX=Lt;exports.KeyIterator=Go;exports.LRUHelper=qt;exports.LRUMap=zo;exports.LifecycleStages=de;exports.LocaleService=nn;exports.LocaleType=Pt;exports.LogLevel=mi;exports.MOVE_BUFFER_VALUE=Qt;exports.Many=ri;exports.MemoryCursor=$i;exports.NamedStyleType=mo;exports.NilCommand=Ri;exports.NumberUnitType=wo;exports.ObjectMatrix=ot;exports.ObjectRelativeFromH=So;exports.ObjectRelativeFromV=No;exports.OnLifecycle=sa;exports.Optional=si;exports.OtherShapes=Zs;exports.PRESET_LIST_TYPE=fc;exports.PageElementType=Uo;exports.PageOrientType=yo;exports.PageType=yr;exports.ParagraphElementType=_o;exports.PermissionService=la;exports.PermissionStatus=Jr;exports.Plugin=Ar;exports.PositionedObjectLayoutType=po;exports.PresetListType=Pn;exports.ProtectionType=zs;exports.RANGE_TYPE=oe;exports.RCDisposable=Gl;exports.RGBA_PAREN=Ya;exports.RGB_PAREN=za;exports.ROTATE_BUFFER_VALUE=xs;exports.Range=Vt;exports.Rectangle=vt;exports.RediConsumer=hi;exports.RediContext=un;exports.RediError=Le;exports.RediProvider=Fr;exports.RedoCommand=pa;exports.RedoCommandId=fa;exports.RefAlias=eu;exports.Registry=jr;exports.RegistryAsMap=$r;exports.RelativeDate=Ys;exports.RelativeSlideLink=Lo;exports.ResourceManagerService=ua;exports.RgbColor=Dn;exports.RxDisposable=Bl;exports.SectionType=co;exports.Self=li;exports.SheetTypes=Hn;exports.SheetViewModel=ta;exports.SkipSelf=ai;exports.SliceBodyType=Gr;exports.SlideDataModel=Zr;exports.SpacingRule=Eo;exports.SpecialShapes=Js;exports.Styles=zi;exports.THEME_COLORS=eo;exports.TabStopAlignment=Co;exports.TextDecoration=Xs;exports.TextDirection=on;exports.TextDirectionType=fo;exports.TextX=Ot;exports.TextXActionType=Z;exports.ThemeColor=Mn;exports.ThemeColorType=He;exports.ThemeColors=jn;exports.ThemeService=ns;exports.Tools=x;exports.UndoCommand=ga;exports.UndoCommandId=_a;exports.UnitModel=Vn;exports.Univer=kh;exports.UniverInstanceType=J;exports.UpdateDocsAttributeType=ke;exports.ValueIterator=Vo;exports.VerticalAlign=Wt;exports.WidthType=Io;exports.WithDependency=ec;exports.WithNew=ui;exports.Worksheet=ln;exports.WrapStrategy=Bt;exports.WrapTextType=go;exports.afterInitApply=dc;exports.b64DecodeUnicode=rs;exports.b64EncodeUnicode=td;exports.binarySearchArray=Ps;exports.cellToRange=Ll;exports.characterSpacingControlType=To;exports.checkForSubstrings=xl;exports.checkIfMove=Ba;exports.checkParagraphHasBullet=Pl;exports.checkParagraphHasIndent=kl;exports.checkParagraphHasIndentByStyle=jo;exports.codeToBlob=Va;exports.composeBody=Or;exports.composeInterceptors=Sa;exports.concatMatrixArray=Ql;exports.connectDependencies=qu;exports.connectInjector=Qu;exports.convertBodyToHtml=lu;exports.covertTextRunToHtml=_r;exports.createDefaultUser=Fn;exports.createIdentifier=Ve;exports.createInterceptorKey=qh;exports.createInternalEditorID=Rh;exports.createRowColIter=fr;exports.debounce=au;exports.dedupe=Vl;exports.deepCompare=Dr;exports.deleteContent=Wo;exports.extractPureTextFromCell=Yc;exports.forwardRef=wu;exports.fromCallback=Ci;exports.fromEventSubject=Xh;exports.fromObservable=Wl;exports.generateRandomId=ko;exports.generateTemporarySnap=id;exports.getArrayLength=It;exports.getBodySlice=an;exports.getBodySliceHtml=In;exports.getBorderStyleType=Dl;exports.getCellInfoInMergeData=fl;exports.getCellValueType=ul;exports.getColorStyle=ut;exports.getCustomDecorationSlice=Hi;exports.getCustomRangeSlice=Fi;exports.getDocsUpdateBody=Ml;exports.getReverseDirection=Ka;exports.getSheetBlocksFromSnapshot=hd;exports.getWorksheetUID=th;exports.groupBy=Yl;exports.handleStyleToString=yl;exports.hashAlgorithm=Hl;exports.horizontalLineSegmentsSubtraction=Wn;exports.insertMatrixArray=cr;exports.insertTextToContent=$o;exports.isAsyncDependencyItem=Er;exports.isAsyncHook=On;exports.isBlackColor=il;exports.isBooleanString=Bh;exports.isCellCoverable=bl;exports.isCellV=hl;exports.isClassDependencyItem=gr;exports.isCtor=Lr;exports.isDisposable=Cr;exports.isEmptyCell=Fo;exports.isFactoryDependencyItem=pr;exports.isFormulaId=Tl;exports.isFormulaString=Al;exports.isICellData=ll;exports.isInternalEditorID=Ch;exports.isNullCell=cl;exports.isNumeric=Ia;exports.isRangesEqual=Hh;exports.isRealNum=Fl;exports.isSafeNumeric=Wh;exports.isSameStyleTextRun=Ho;exports.isUnitRangesEqual=jh;exports.isValidRange=Ul;exports.isValueDependencyItem=mr;exports.isWhiteColor=al;exports.makeArray=Xl;exports.makeCellRangeToRangeData=wl;exports.makeCellToSelection=Nl;exports.mergeOverrideWithDependencies=Ra;exports.mergeSets=Gh;exports.mergeWorksheetSnapshotWithDefault=ea;exports.moveMatrixArray=dr;exports.moveRangeByOffset=mu;exports.nameCharacterCheck=fd;exports.normalizeBody=Nc;exports.normalizeTextRuns=Wr;exports.numberToABC=ru;exports.numberToListABC=su;exports.orderSearchArray=ks;exports.queryObjectMatrix=pu;exports.remove=Bn;exports.repeatStringNumTimes=Xo;exports.replaceInDocumentBody=zh;exports.requestImmediateMacroTask=Kh;exports.rotate=zl;exports.runOnLifecycle=Kn;exports.searchArray=Ga;exports.selectionToArray=dl;exports.sequence=gi;exports.sequenceAsync=_i;exports.sequenceExecute=Hr;exports.sequenceExecuteAsync=hc;exports.setDependencies=Bu;exports.shallowEqual=$h;exports.skipParseTagNames=dd;exports.sliceMatrixArray=ql;exports.sortRules=ou;exports.sortRulesByDesc=iu;exports.sortRulesFactory=kt;exports.spliceArray=hr;exports.takeAfter=Ii;exports.textDecoder=Qn;exports.textEncoder=fn;exports.throttle=Vh;exports.toDisposable=Ne;exports.transformDocumentDataToSnapshot=cd;exports.transformSnapshotToDocumentData=ud;exports.transformSnapshotToWorkbookData=ld;exports.transformWorkbookDataToSnapshot=ad;exports.updateAttributeByDelete=Wi;exports.updateAttributeByInsert=Bi;exports.useDependency=Yu;exports.useDependencyContext=sc;exports.useDependencyContextValue=oc;exports.useDependencyValue=fi;exports.useInjector=di;exports.useObservable=nc;exports.useUpdateBinder=rc;
6
+ For more info please visit our website: https://redi.wendell.fun/en-US/docs/debug#import-scripts-of-redi-more-than-once`):globalObject$1[__REDI_GLOBAL_LOCK__]=!0;var __REDI_CONTEXT_LOCK__="REDI_CONTEXT_LOCK",isNode=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,globalObject=typeof globalThis<"u"&&globalThis||typeof window<"u"&&window||typeof global<"u"&&global;globalObject[__REDI_CONTEXT_LOCK__]?isNode||console.error(`[redi]: "RediContext" is already created. You may import "RediContext" from different paths. Use "import { RediContext } from '@wendellhu/redi/react-bindings'; instead."`):globalObject[__REDI_CONTEXT_LOCK__]=!0;var RediContext=React__namespace.createContext({injector:null});RediContext.displayName="RediContext";var RediProvider=RediContext.Provider,RediConsumer=RediContext.Consumer,__extends$1=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),HooksNotInRediContextError=function(_super){__extends$1(HooksNotInRediContextError2,_super);function HooksNotInRediContextError2(){return _super.call(this,"Using dependency injection outside of a RediContext.")||this}return __name(HooksNotInRediContextError2,"HooksNotInRediContextError"),HooksNotInRediContextError2}(RediError);function useInjector(){var injectionContext=React__namespace.useContext(RediContext);if(!injectionContext.injector)throw new HooksNotInRediContextError;return injectionContext.injector}__name(useInjector,"useInjector");function useDependency(id,quantityOrLookUp,lookUp){var injector=useInjector();return React__namespace.useMemo(function(){return injector.get(id,quantityOrLookUp,lookUp)},[id,quantityOrLookUp,lookUp])}__name(useDependency,"useDependency");var __assign=__name(function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p])}return t},__assign.apply(this,arguments)},"__assign");function RediInjector(props){var children=props.children,dependencies=props.dependencies,childInjectorRef=React__namespace.useRef(null);return React__namespace.useEffect(function(){return function(){var _a13;return(_a13=childInjectorRef.current)===null||_a13===void 0?void 0:_a13.dispose()}},[]),React__namespace.createElement(RediConsumer,null,function(context){var childInjector;return childInjectorRef.current?childInjector=childInjectorRef.current:(childInjector=context.injector?context.injector.createChild(dependencies):new Injector(dependencies),childInjectorRef.current=childInjector),React__namespace.createElement(RediProvider,{value:{injector:childInjector}},children)})}__name(RediInjector,"RediInjector");function connectInjector(Comp,injector){return __name(function(props){return React__namespace.createElement(RediProvider,{value:{injector}},React__namespace.createElement(Comp,__assign({},props)))},"ComponentWithInjector")}__name(connectInjector,"connectInjector");function connectDependencies(Comp,dependencies){return __name(function(props){return React__namespace.createElement(RediInjector,{dependencies},React__namespace.createElement(Comp,__assign({},props)))},"ComponentWithInjector")}__name(connectDependencies,"connectDependencies");var __extends=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),ClassComponentNotInRediContextError=function(_super){__extends(ClassComponentNotInRediContextError2,_super);function ClassComponentNotInRediContextError2(component){return _super.call(this,'You should make "RediContext" as '.concat(component.constructor.name,"'s default context type. ")+"If you want to use multiple context, please check this on React doc site. https://reactjs.org/docs/context.html#classcontexttype")||this}return __name(ClassComponentNotInRediContextError2,"ClassComponentNotInRediContextError"),ClassComponentNotInRediContextError2}(RediError);function WithDependency(id,quantity,lookUp){return function(){return{get:__name(function(){var thisComponent=this,context=thisComponent.context;if(!context||!context.injector)throw new ClassComponentNotInRediContextError(thisComponent);var injector=context.injector,thing=injector.get(id,quantity||exports.Quantity.REQUIRED,lookUp);return thing},"get")}}}__name(WithDependency,"WithDependency");var __spreadArray=__name(function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l2=from.length,ar;i<l2;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))},"__spreadArray");function useDependencyValue(depValue$,defaultValue){var firstValue=depValue$ instanceof rxjs.BehaviorSubject&&typeof defaultValue>"u"?depValue$.getValue():defaultValue,_a13=React.useState(firstValue),value=_a13[0],setValue=_a13[1];return React.useEffect(function(){var subscription=depValue$.subscribe(function(val){return setValue(val)});return function(){return subscription.unsubscribe()}},[depValue$]),value}__name(useDependencyValue,"useDependencyValue");function unwrap(o){return typeof o=="function"?o():o}__name(unwrap,"unwrap");function useObservable(observable,defaultValue,shouldHaveSyncValue,deps){if(typeof observable=="function"&&!deps)throw new RediError("Expected deps to be provided when observable is a function!");var observableRef=React.useRef(null),initializedRef=React.useRef(!1),destObservable=React.useMemo(function(){return observable},__spreadArray([],typeof deps<"u"?deps:[observable],!0)),_a13=React.useState(0);_a13[0];var setRenderCounter=_a13[1],valueRef=React.useRef(function(){var innerDefaultValue;if(destObservable){var sub=unwrap(destObservable).subscribe(function(value){initializedRef.current=!0,innerDefaultValue=value});sub.unsubscribe()}return innerDefaultValue!=null?innerDefaultValue:defaultValue}());if(React.useEffect(function(){var subscription=null;return destObservable&&(observableRef.current=unwrap(destObservable),subscription=observableRef.current.subscribe(function(value){valueRef.current=value,setRenderCounter(function(prev){return prev+1})})),function(){return subscription==null?void 0:subscription.unsubscribe()}},[destObservable]),shouldHaveSyncValue&&!initializedRef.current)throw new Error("Expect `shouldHaveSyncValue` but not getting a sync value!");return valueRef.current}__name(useObservable,"useObservable");function useUpdateBinder(update$){var _a13=React.useState(0),dumpSet=_a13[1];React.useEffect(function(){var subscription=update$.subscribe(function(){return dumpSet(function(prev){return prev+1})});return function(){return subscription.unsubscribe()}},[])}__name(useUpdateBinder,"useUpdateBinder");var DepValueMapProvider=new WeakMap;function useDependencyContext(depValue$,defaultValue){var depRef=React.useRef(void 0),value=useDependencyValue(depValue$,defaultValue),Context=React.useMemo(function(){return React.createContext(value)},[depValue$]),Provider=React.useCallback(function(props){return React.createElement(Context.Provider,{value},props.children)},[depValue$,value]);return depRef.current!==depValue$&&(depRef.current&&DepValueMapProvider.delete(depRef.current),depRef.current=depValue$,DepValueMapProvider.set(depValue$,Context)),{Provider,value}}__name(useDependencyContext,"useDependencyContext");function useDependencyContextValue(depValue$){var context=DepValueMapProvider.get(depValue$);if(!context)throw new RediError("try to read context value but no ancestor component subscribed it.");return React.useContext(context)}__name(useDependencyContextValue,"useDependencyContextValue");async function sequenceAsync(tasks){for(const[index2,task]of tasks.entries())try{if(!await task())return{index:index2,result:!1}}catch(e){return{index:index2,result:!1,error:e}}return{result:!0,index:-1}}__name(sequenceAsync,"sequenceAsync");function sequence(tasks){for(const[index2,task]of tasks.entries())try{if(!task())return{index:index2,result:!1}}catch(e){return{index:index2,result:!1,error:e}}return{result:!0,index:-1}}__name(sequence,"sequence");const IContextService=createIdentifier("univer.context-service"),_ContextService=class _ContextService extends Disposable{constructor(){super(...arguments);__publicField(this,"_contextChanged$",new rxjs.Subject);__publicField(this,"contextChanged$",this._contextChanged$.asObservable());__publicField(this,"_contextMap",new Map)}dispose(){super.dispose(),this._contextChanged$.complete()}getContextValue(key){var _a13;return(_a13=this._contextMap.get(key))!=null?_a13:!1}setContextValue(key,value){this._contextMap.set(key,value),this._contextChanged$.next({[key]:value})}subscribeContextValue$(key){return new rxjs.Observable(observer=>{const contextChangeSubscription=this._contextChanged$.pipe(rxjs.filter(event=>typeof event[key]<"u")).subscribe(event=>observer.next(event[key]));return this._contextMap.has(key)&&observer.next(this._contextMap.get(key)),()=>contextChangeSubscription.unsubscribe()})}};__name(_ContextService,"ContextService");let ContextService=_ContextService;var LogLevel=(LogLevel2=>(LogLevel2[LogLevel2.SILENT=0]="SILENT",LogLevel2[LogLevel2.ERROR=1]="ERROR",LogLevel2[LogLevel2.WARN=2]="WARN",LogLevel2[LogLevel2.INFO=3]="INFO",LogLevel2[LogLevel2.VERBOSE=4]="VERBOSE",LogLevel2))(LogLevel||{});const ILogService=createIdentifier("univer.log"),_DesktopLogService=class _DesktopLogService extends Disposable{constructor(){super(...arguments);__publicField(this,"_logLevel",3)}debug(...args){this._logLevel>=4&&this._log(console.debug,...args)}log(...args){this._logLevel>=3&&this._log(console.log,...args)}warn(...args){this._logLevel>=2&&this._log(console.warn,...args)}error(...args){this._logLevel>=1&&this._log(console.error,...args)}setLogLevel(logLevel){this._logLevel=logLevel}_log(method,...args){const firstArg=args[0];/^\[(.*?)\]/g.test(firstArg)?method(`\x1B[97;104m${firstArg}\x1B[0m`,...args.slice(1)):method(...args)}};__name(_DesktopLogService,"DesktopLogService");let DesktopLogService=_DesktopLogService;var __defProp$8=Object.defineProperty,__getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$8(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$8(target,key,result),result},"__decorateClass$8"),__decorateParam$7=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$7"),CommandType=(CommandType2=>(CommandType2[CommandType2.COMMAND=0]="COMMAND",CommandType2[CommandType2.OPERATION=1]="OPERATION",CommandType2[CommandType2.MUTATION=2]="MUTATION",CommandType2))(CommandType||{});const ICommandService=createIdentifier("anywhere.command-service"),_CommandRegistry=class _CommandRegistry{constructor(){__publicField(this,"_commands",new Map);__publicField(this,"_commandTypes",new Map)}registerCommand(command){if(this._commands.has(command.id))throw new Error(`[CommandRegistry]: command "${command.id}" has been registered before.`);return this._commands.set(command.id,command),this._commandTypes.set(command.id,command.type),toDisposable(()=>{var _a13;this._commands.delete(command.id),this._commandTypes.delete(command.id),(_a13=command.onDispose)==null||_a13.call(command)})}hasCommand(id){return this._commands.has(id)}getCommand(id){return this._commands.has(id)?[this._commands.get(id)]:null}getCommandType(id){return this._commandTypes.get(id)}};__name(_CommandRegistry,"CommandRegistry");let CommandRegistry=_CommandRegistry;const NilCommand={id:"nil",type:0,handler:__name(()=>!0,"handler")};var _a2;exports.CommandService=(_a2=class extends Disposable{constructor(_injector,_logService){super();__publicField(this,"_commandRegistry");__publicField(this,"_beforeCommandExecutionListeners",[]);__publicField(this,"_commandExecutedListeners",[]);__publicField(this,"_multiCommandDisposables",new Map);__publicField(this,"_commandExecutingLevel",0);__publicField(this,"_commandExecutionStack",[]);this._injector=_injector,this._logService=_logService,this._commandRegistry=new CommandRegistry,this._registerCommand(NilCommand)}dispose(){super.dispose(),this._commandExecutedListeners.length=0,this._beforeCommandExecutionListeners.length=0}hasCommand(commandId){return this._commandRegistry.hasCommand(commandId)}registerCommand(command){return this._registerCommand(command)}registerMultipleCommand(command){return this._registerMultiCommand(command)}beforeCommandExecuted(listener){if(this._beforeCommandExecutionListeners.indexOf(listener)===-1)return this._beforeCommandExecutionListeners.push(listener),toDisposable(()=>{const index2=this._beforeCommandExecutionListeners.indexOf(listener);this._beforeCommandExecutionListeners.splice(index2,1)});throw new Error("[CommandService]: could not add a listener twice.")}onCommandExecuted(listener){if(this._commandExecutedListeners.indexOf(listener)===-1)return this._commandExecutedListeners.push(listener),toDisposable(()=>{const index2=this._commandExecutedListeners.indexOf(listener);this._commandExecutedListeners.splice(index2,1)});throw new Error("[CommandService]: could not add a listener twice.")}async executeCommand(id,params,options){try{const item=this._commandRegistry.getCommand(id);if(item){const[command]=item,commandInfo={id:command.id,type:command.type,params},stackItemDisposable=this._pushCommandExecutionStack(commandInfo);this._beforeCommandExecutionListeners.forEach(listener=>listener(commandInfo,options));const result=await this._execute(command,params,options);return this._commandExecutedListeners.forEach(listener=>listener(commandInfo,options)),stackItemDisposable.dispose(),result}throw new Error(`[CommandService]: command "${id}" is not registered.`)}catch(error){throw this._logService.error(error),error}}syncExecuteCommand(id,params,options){var _a13;const item=this._commandRegistry.getCommand(id);if(item){const[command]=item,commandInfo={id:command.id,type:command.type,params};if(command.type===2){const triggerCommand=findLast(this._commandExecutionStack,item2=>item2.type===0);triggerCommand&&(commandInfo.params=(_a13=commandInfo.params)!=null?_a13:{},commandInfo.params.trigger=triggerCommand.id)}const stackItemDisposable=this._pushCommandExecutionStack(commandInfo);this._beforeCommandExecutionListeners.forEach(listener=>listener(commandInfo,options));const result=this._syncExecute(command,params,options);return this._commandExecutedListeners.forEach(listener=>listener(commandInfo,options)),stackItemDisposable.dispose(),result}throw new Error(`[CommandService]: command "${id}" is not registered.`)}_pushCommandExecutionStack(stackItem){return this._commandExecutionStack.push(stackItem),toDisposable(()=>remove(this._commandExecutionStack,stackItem))}_registerCommand(command){return this._commandRegistry.registerCommand(command)}_registerMultiCommand(command){const registry=this._commandRegistry.getCommand(command.id);let multiCommand;if(registry){if(registry[0].multi!==!0)throw new Error("Command has registered as a single command.");multiCommand=registry[0]}else{const disposableCollection=new DisposableCollection;multiCommand=new MultiCommand(command.id),disposableCollection.add(this._commandRegistry.registerCommand(multiCommand)),disposableCollection.add(toDisposable(()=>{this._multiCommandDisposables.delete(command.id)})),this._multiCommandDisposables.set(command.id,disposableCollection)}const implementationDisposable=multiCommand.registerImplementation(command);return toDisposable(()=>{var _a13;implementationDisposable.dispose(),multiCommand.hasImplementations()||(_a13=this._multiCommandDisposables.get(command.id))==null||_a13.dispose()})}async _execute(command,params,options){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(this._commandExecutingLevel,0))}executing command "${command.id}"`),this._commandExecutingLevel++;let result;try{result=await this._injector.invoke(command.handler,params,options),this._commandExecutingLevel--}catch(e){throw result=!1,this._commandExecutingLevel=0,e}return result}_syncExecute(command,params,options){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(0,this._commandExecutingLevel))}executing command "${command.id}".`),this._commandExecutingLevel++;let result;try{if(result=this._injector.invoke(command.handler,params,options),result instanceof Promise)throw new TypeError("[CommandService]: Command handler should not return a promise.");this._commandExecutingLevel--}catch(e){throw result=!1,this._commandExecutingLevel=0,e}return result}},__name(_a2,"CommandService"),_a2);exports.CommandService=__decorateClass$8([__decorateParam$7(0,Inject(Injector)),__decorateParam$7(1,ILogService)],exports.CommandService);const _MultiCommand=class _MultiCommand{constructor(id){__publicField(this,"name");__publicField(this,"multi",!0);__publicField(this,"type",0);__publicField(this,"priority",0);__publicField(this,"_implementations",[]);__publicField(this,"handler",__name(async(accessor,params)=>{if(!this._implementations.length)return!1;const logService=accessor.get(ILogService),contextService=accessor.get(IContextService),injector=accessor.get(Injector);for(const item of this._implementations){const preconditions=item.command.preconditions;if((!preconditions||preconditions&&preconditions(contextService))&&(logService.debug("[MultiCommand]",`executing implementation "${item.command.name}".`),await injector.invoke(item.command.handler,params)))return!0}return!1},"handler"));this.id=id,this.name=id}registerImplementation(implementation){const registry={command:implementation};return this._implementations.push(registry),this._implementations.sort((a,b)=>b.command.priority-a.command.priority),toDisposable(()=>{var _a13;const index2=this._implementations.indexOf(registry);this._implementations.splice(index2,1),(_a13=implementation.onDispose)==null||_a13.call(implementation)})}hasImplementations(){return this._implementations.length>0}};__name(_MultiCommand,"MultiCommand");let MultiCommand=_MultiCommand;function sequenceExecute(tasks,commandService,options){const taskFns=tasks.map(task=>()=>commandService.syncExecuteCommand(task.id,task.params,options));return sequence(taskFns)}__name(sequenceExecute,"sequenceExecute");function sequenceExecuteAsync(tasks,commandService,options){const promises=tasks.map(task=>()=>commandService.executeCommand(task.id,task.params,options));return sequenceAsync(promises)}__name(sequenceExecuteAsync,"sequenceExecuteAsync");function fromCallback(callback){return new rxjs.Observable(subscriber=>{const disposable=callback((...args)=>subscriber.next(args));return()=>disposable==null?void 0:disposable.dispose()})}__name(fromCallback,"fromCallback");function takeAfter(callback){return __name(function(source){return new rxjs.Observable(subscriber=>(source.subscribe({next:__name(v=>{subscriber.next(v),callback(v)&&subscriber.complete()},"next"),complete:__name(()=>subscriber.complete(),"complete"),error:__name(error=>subscriber.error(error),"error")}),()=>subscriber.unsubscribe()))},"complateAfter")}__name(takeAfter,"takeAfter");const afterInitApply=__name(commandService=>new Promise(res=>{rxjs.merge(fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(operators.filter(([info])=>info.type===CommandType.MUTATION)),rxjs.timer(300)).pipe(operators.debounceTime(16),operators.first()).subscribe(()=>{res()})}),"afterInitApply");var N=(E=>(E[E.UNDEFINED=0]="UNDEFINED",E[E.OK=1]="OK",E[E.INTERNAL_ERROR=2]="INTERNAL_ERROR",E[E.PERMISSION_DENIED=3]="PERMISSION_DENIED",E[E.NOT_FOUND=4]="NOT_FOUND",E[E.UNAUTHENTICATED=5]="UNAUTHENTICATED",E[E.ALREADY_EXISTS=6]="ALREADY_EXISTS",E[E.INVALID_ARGUMENT=7]="INVALID_ARGUMENT",E[E.TOO_MANY_REQUESTS=8]="TOO_MANY_REQUESTS",E[E.COMPLETION_FINISHED=9]="COMPLETION_FINISHED",E[E.CHANGESET_REVISION_CONFILICT=5001]="CHANGESET_REVISION_CONFILICT",E[E.SNAPSHOT_INVALID_SNAPSHOT=6001]="SNAPSHOT_INVALID_SNAPSHOT",E[E.SNAPSHOT_HAS_BEEN_REMOVED=6002]="SNAPSHOT_HAS_BEEN_REMOVED",E[E.APPLY_REJECT=7001]="APPLY_REJECT",E[E.APPLY_NON_SEQUENTIAL_REVISION=7002]="APPLY_NON_SEQUENTIAL_REVISION",E[E.APPLY_REVISION_CONFILICT=7003]="APPLY_REVISION_CONFILICT",E[E.APPLY_PERMISSION_DENIED=7004]="APPLY_PERMISSION_DENIED",E[E.CONNECTOR_DATA_TOO_LARGE=8001]="CONNECTOR_DATA_TOO_LARGE",E[E.LICENSE_MAX_UNITS_EXCEEDED=9001]="LICENSE_MAX_UNITS_EXCEEDED",E[E.LICENSE_MAX_MEMBERS_PER_UNIT_EXCEEDED=9002]="LICENSE_MAX_MEMBERS_PER_UNIT_EXCEEDED",E[E.LICENSE_IMPORT_SIZE_EXCEEDED=9003]="LICENSE_IMPORT_SIZE_EXCEEDED",E[E.LICENSE_EXPORT_SIZE_EXCEEDED=9004]="LICENSE_EXPORT_SIZE_EXCEEDED",E[E.LICENSE_DISTRO_REJECTED=9005]="LICENSE_DISTRO_REJECTED",E[E.YUUMI_UNABLE_LOAD_URL=10001]="YUUMI_UNABLE_LOAD_URL",E[E.YUUMI_URL_COL_OUT_OF_RANGE=10002]="YUUMI_URL_COL_OUT_OF_RANGE",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(N||{});function T(E){return!!(E&&E.code&&E.code!==N.OK&&E.code!=="OK")}__name(T,"T");var I=(E=>(E[E.UNIVER_UNKNOWN=0]="UNIVER_UNKNOWN",E[E.UNIVER_DOC=1]="UNIVER_DOC",E[E.UNIVER_SHEET=2]="UNIVER_SHEET",E[E.UNIVER_SLIDE=3]="UNIVER_SLIDE",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(I||{}),L=(E=>(E[E.SomeCollaborator=0]="SomeCollaborator",E[E.AllCollaborator=1]="AllCollaborator",E[E.OneSelf=2]="OneSelf",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(L||{}),l=(E=>(E[E.Reader=0]="Reader",E[E.Editor=1]="Editor",E[E.Owner=2]="Owner",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(l||{}),G=(E=>(E[E.Unkonwn=0]="Unkonwn",E[E.Workbook=1]="Workbook",E[E.Worksheet=2]="Worksheet",E[E.SelectRange=3]="SelectRange",E[E.Document=4]="Document",E[E.Slide=5]="Slide",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(G||{});const _UnitModel=class _UnitModel extends Disposable{};__name(_UnitModel,"UnitModel");let UnitModel=_UnitModel;const _Registry=class _Registry{constructor(){__publicField(this,"_data",[])}static create(){return new _Registry}add(dataInstance){this._data.indexOf(dataInstance)>-1||this._data.push(dataInstance)}delete(dataInstance){const index2=this._data.indexOf(dataInstance);this._data.splice(index2,1)}getData(){return this._data}};__name(_Registry,"Registry");let Registry=_Registry;const _RegistryAsMap=class _RegistryAsMap{constructor(){__publicField(this,"_data",new Map)}static create(){return new _RegistryAsMap}add(id,dataInstance){this._data.has(id)||this._data.set(id,dataInstance)}delete(id){this._data.delete(id)}getData(){return this._data}};__name(_RegistryAsMap,"RegistryAsMap");let RegistryAsMap=_RegistryAsMap;var DataStreamTreeNodeType=(DataStreamTreeNodeType2=>(DataStreamTreeNodeType2[DataStreamTreeNodeType2.PARAGRAPH=0]="PARAGRAPH",DataStreamTreeNodeType2[DataStreamTreeNodeType2.SECTION_BREAK=1]="SECTION_BREAK",DataStreamTreeNodeType2[DataStreamTreeNodeType2.TABLE=2]="TABLE",DataStreamTreeNodeType2[DataStreamTreeNodeType2.TABLE_ROW=3]="TABLE_ROW",DataStreamTreeNodeType2[DataStreamTreeNodeType2.TABLE_CELL=4]="TABLE_CELL",DataStreamTreeNodeType2[DataStreamTreeNodeType2.CUSTOM_BLOCK=5]="CUSTOM_BLOCK",DataStreamTreeNodeType2))(DataStreamTreeNodeType||{}),DataStreamTreeTokenType=(DataStreamTreeTokenType2=>(DataStreamTreeTokenType2.PARAGRAPH="\r",DataStreamTreeTokenType2.SECTION_BREAK=`
7
+ `,DataStreamTreeTokenType2.TABLE_START="",DataStreamTreeTokenType2.TABLE_ROW_START="\x1B",DataStreamTreeTokenType2.TABLE_CELL_START="",DataStreamTreeTokenType2.TABLE_CELL_END="",DataStreamTreeTokenType2.TABLE_ROW_END="",DataStreamTreeTokenType2.TABLE_END="",DataStreamTreeTokenType2.CUSTOM_RANGE_START="",DataStreamTreeTokenType2.CUSTOM_RANGE_END="",DataStreamTreeTokenType2.COLUMN_BREAK="\v",DataStreamTreeTokenType2.PAGE_BREAK="\f",DataStreamTreeTokenType2.DOCS_END="\0",DataStreamTreeTokenType2.TAB=" ",DataStreamTreeTokenType2.CUSTOM_BLOCK="\b",DataStreamTreeTokenType2.LETTER="",DataStreamTreeTokenType2.SPACE=" ",DataStreamTreeTokenType2))(DataStreamTreeTokenType||{}),PresetListType=(PresetListType2=>(PresetListType2.BULLET_LIST="BULLET_LIST",PresetListType2.ORDER_LIST="ORDER_LIST",PresetListType2))(PresetListType||{});const PRESET_LIST_TYPE={BULLET_LIST:{listType:"BULLET_LIST",nestingLevel:[{bulletAlignment:BulletAlignment.START,glyphFormat:" %0",textStyle:{fs:12},startNumber:0,glyphSymbol:"●",paragraphProperties:{hanging:{v:21},indentStart:{v:21}}},{bulletAlignment:BulletAlignment.START,glyphFormat:" %1",textStyle:{fs:12},startNumber:0,glyphSymbol:"■",paragraphProperties:{hanging:{v:21},indentStart:{v:42}}},{bulletAlignment:BulletAlignment.START,glyphFormat:" %1",textStyle:{fs:12},startNumber:0,glyphSymbol:"◆",paragraphProperties:{hanging:{v:21},indentStart:{v:63}}}]},ORDER_LIST:{listType:"ORDER_LIST",nestingLevel:[{bulletAlignment:BulletAlignment.START,glyphFormat:" %1.",textStyle:{fs:12},startNumber:0,glyphType:GlyphType.DECIMAL,paragraphProperties:{hanging:{v:21},indentStart:{v:21}}},{bulletAlignment:BulletAlignment.START,glyphFormat:" %1.%2)",textStyle:{fs:12},startNumber:0,glyphType:GlyphType.DECIMAL,paragraphProperties:{hanging:{v:21},indentStart:{v:42}}},{bulletAlignment:BulletAlignment.START,glyphFormat:" %1.%2.%3.",textStyle:{fs:12},startNumber:0,glyphType:GlyphType.DECIMAL,paragraphProperties:{hanging:{v:21},indentStart:{v:63}}}]}};function normalizeTextRuns(textRuns){const results=[];for(const textRun of textRuns){const{ed,ts}=textRun;if(textRun.sId===void 0&&delete textRun.sId,Tools.isEmptyObject(ts)&&textRun.sId==null)continue;if(results.length===0){results.push(textRun);continue}const peak=results.pop();isSameStyleTextRun(textRun,peak)&&Tools.hasIntersectionBetweenTwoRanges(peak.st,peak.ed,textRun.st,textRun.ed)?results.push({...textRun,st:peak.st,ed}):results.push(peak,textRun)}return results}__name(normalizeTextRuns,"normalizeTextRuns");function insertTextRuns(body,insertBody,textLength,currentIndex){var _a13;const{textRuns}=body;if(textRuns==null)return;const newTextRuns=[],len=textRuns.length;let hasInserted=!1;const insertTextRuns2=(_a13=insertBody.textRuns)!=null?_a13:[];if(insertTextRuns2.length)for(const insertTextRun of insertTextRuns2)insertTextRun.st+=currentIndex,insertTextRun.ed+=currentIndex;for(let i=0;i<len;i++){const textRun=textRuns[i],nextRun=textRuns[i+1],{st,ed}=textRun;if(ed<currentIndex)newTextRuns.push(textRun);else if(currentIndex>=st&&currentIndex<=ed){if(nextRun&&nextRun.st===nextRun.ed&&currentIndex===nextRun.st){newTextRuns.push(textRun);continue}if(hasInserted)textRun.st+=textLength,textRun.ed+=textLength,newTextRuns.push(textRun);else{hasInserted=!0,textRun.ed+=textLength;const pendingTextRuns=[];if(insertTextRuns2.length){const startSplitTextRun={...textRun,st,ed:insertTextRuns2[0].st};startSplitTextRun.ed>startSplitTextRun.st&&pendingTextRuns.push(startSplitTextRun),pendingTextRuns.push(...insertTextRuns2);const lastInsertTextRuns=insertTextRuns2[insertTextRuns2.length-1],endSplitTextRun={...textRun,st:lastInsertTextRuns.ed,ed:ed+textLength};endSplitTextRun.ed>endSplitTextRun.st&&pendingTextRuns.push(endSplitTextRun)}else pendingTextRuns.push(textRun);newTextRuns.push(...pendingTextRuns)}}else textRun.st+=textLength,textRun.ed+=textLength,hasInserted||(hasInserted=!0,newTextRuns.push(...insertTextRuns2)),newTextRuns.push(textRun)}hasInserted||(hasInserted=!0,newTextRuns.push(...insertTextRuns2)),body.textRuns=normalizeTextRuns(newTextRuns)}__name(insertTextRuns,"insertTextRuns");function insertParagraphs(body,insertBody,textLength,currentIndex){const{paragraphs}=body;if(paragraphs==null)return;const{paragraphs:insertParagraphs2,dataStream:insertDataStream}=insertBody,paragraphIndexList=[];let firstInsertParagraphNextIndex=-1;for(let i=0,len=paragraphs.length;i<len;i++){const paragraph=paragraphs[i],{startIndex}=paragraph;startIndex>=currentIndex&&(paragraph.startIndex+=textLength),firstInsertParagraphNextIndex===-1&&startIndex>=currentIndex&&(firstInsertParagraphNextIndex=i),paragraphIndexList.push(paragraph.startIndex)}let deleteReptIndex=-1;if(insertParagraphs2){for(let i=0,len=insertParagraphs2.length;i<len;i++){const insertParagraph=insertParagraphs2[i];insertParagraph.startIndex+=currentIndex;const insertIndex=insertParagraph.startIndex;deleteReptIndex=paragraphIndexList.indexOf(insertIndex)}if(insertDataStream===DataStreamTreeTokenType.PARAGRAPH&&insertParagraphs2.length===1){const nextParagraph=paragraphs[firstInsertParagraphNextIndex],insertParagraph=insertParagraphs2[0],nextParagraphStyle=nextParagraph.paragraphStyle,nextBullet=nextParagraph.bullet;nextParagraph.paragraphStyle=insertParagraph.paragraphStyle,nextParagraph.bullet=insertParagraph.bullet,insertParagraph.paragraphStyle=nextParagraphStyle,insertParagraph.bullet=nextBullet}deleteReptIndex!==-1&&paragraphs.splice(deleteReptIndex,1),paragraphs.push(...insertParagraphs2),paragraphs.sort(sortRulesFactory("startIndex"))}}__name(insertParagraphs,"insertParagraphs");function insertSectionBreaks(body,insertBody,textLength,currentIndex){const{sectionBreaks}=body;if(sectionBreaks==null)return;for(let i=0,len=sectionBreaks.length;i<len;i++){const sectionBreak=sectionBreaks[i],{startIndex}=sectionBreak;startIndex>=currentIndex&&(sectionBreak.startIndex+=textLength)}const insertSectionBreaks2=insertBody.sectionBreaks;if(insertSectionBreaks2){for(let i=0,len=insertSectionBreaks2.length;i<len;i++){const sectionBreak=insertSectionBreaks2[i];sectionBreak.startIndex+=currentIndex}sectionBreaks.push(...insertSectionBreaks2),sectionBreaks.sort(sortRulesFactory("startIndex"))}}__name(insertSectionBreaks,"insertSectionBreaks");function insertCustomBlocks(body,insertBody,textLength,currentIndex){const{customBlocks}=body;if(customBlocks==null)return;for(let i=0,len=customBlocks.length;i<len;i++){const customBlock=customBlocks[i],{startIndex}=customBlock;startIndex>=currentIndex&&(customBlock.startIndex+=textLength)}const insertCustomBlocks2=insertBody.customBlocks;if(insertCustomBlocks2){for(let i=0,len=insertCustomBlocks2.length;i<len;i++){const customBlock=insertCustomBlocks2[i];customBlock.startIndex+=currentIndex}customBlocks.push(...insertCustomBlocks2),customBlocks.sort(sortRulesFactory("startIndex"))}}__name(insertCustomBlocks,"insertCustomBlocks");function insertTables(body,insertBody,textLength,currentIndex){const{tables}=body;if(tables==null)return;for(let i=0,len=tables.length;i<len;i++){const table=tables[i],{startIndex,endIndex}=table;startIndex>currentIndex?(table.startIndex+=textLength,table.endIndex+=textLength):endIndex>=currentIndex-1&&(table.endIndex+=textLength)}const insertTables2=insertBody.tables;if(insertTables2){for(let i=0,len=insertTables2.length;i<len;i++){const table=insertTables2[i];table.startIndex+=currentIndex,table.endIndex+=currentIndex}tables.push(...insertTables2),tables.sort(sortRulesFactory("startIndex"))}}__name(insertTables,"insertTables");function insertCustomRanges(body,insertBody,textLength,currentIndex){body.customRanges||(body.customRanges=[]);const{customRanges}=body,customRangeMap={};for(let i=0,len=customRanges.length;i<len;i++){const customRange=customRanges[i];customRangeMap[customRange.rangeId]=customRange;const{startIndex,endIndex}=customRange;startIndex>=currentIndex?(customRange.startIndex+=textLength,customRange.endIndex+=textLength):endIndex>currentIndex-1&&(customRange.endIndex+=textLength)}if(customRanges.find(range=>range.startIndex>currentIndex&&range.endIndex<currentIndex))return;const insertCustomRanges2=[];if(insertBody.customRanges){for(let i=0,len=insertBody.customRanges.length;i<len;i++){const customRange=insertBody.customRanges[i],oldCustomRange=customRangeMap[customRange.rangeId];if(customRange.startIndex+=currentIndex,customRange.endIndex+=currentIndex,oldCustomRange){if(oldCustomRange.startIndex<=customRange.startIndex&&oldCustomRange.endIndex>=customRange.endIndex||body.dataStream[oldCustomRange.startIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_START&&body.dataStream[oldCustomRange.endIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_END)continue;if(body.dataStream[oldCustomRange.startIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_START){oldCustomRange.endIndex=customRange.endIndex;continue}if(body.dataStream[oldCustomRange.endIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_END){oldCustomRange.startIndex=customRange.startIndex;continue}}insertCustomRanges2.push(customRange)}customRanges.push(...insertCustomRanges2),customRanges.sort(sortRulesFactory("startIndex"))}}__name(insertCustomRanges,"insertCustomRanges");function mergeRanges(lineSegments){lineSegments.sort((a,b)=>a.startIndex-b.startIndex);const mergedSegments=[];let currentSegment=lineSegments[0];for(let i=1;i<lineSegments.length;i++)currentSegment.endIndex+1>=lineSegments[i].startIndex?currentSegment.endIndex=Math.max(currentSegment.endIndex,lineSegments[i].endIndex):(mergedSegments.push(currentSegment),currentSegment=lineSegments[i]);return mergedSegments.push(currentSegment),mergedSegments}__name(mergeRanges,"mergeRanges");function mergeDecorations(customDecorations){const customDecorationMap={};for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],currentDecorations=customDecorationMap[customDecoration.id];customDecorationMap[customDecoration.id]=[...currentDecorations!=null?currentDecorations:[],customDecoration]}return Object.keys(customDecorationMap).forEach(id=>{const decorations=customDecorationMap[id],newRanges=mergeRanges(decorations);customDecorationMap[id]=newRanges}),Object.values(customDecorationMap).flat()}__name(mergeDecorations,"mergeDecorations");function insertCustomDecorations(body,insertBody,textLength,currentIndex){body.customDecorations||(body.customDecorations=[]);const{customDecorations}=body;if(textLength>0)for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],{startIndex,endIndex}=customDecoration;startIndex>=currentIndex?(customDecoration.startIndex+=textLength,customDecoration.endIndex+=textLength):endIndex>currentIndex-1&&(customDecoration.endIndex+=textLength)}if(insertBody.customDecorations){const insertCustomDecorations2=[];for(let i=0,len=insertBody.customDecorations.length;i<len;i++){const customDecoration=insertBody.customDecorations[i];insertCustomDecorations2.push(customDecoration),customDecoration.startIndex+=currentIndex,customDecoration.endIndex+=currentIndex}customDecorations.push(...insertCustomDecorations2),body.customDecorations=mergeDecorations(customDecorations),body.customDecorations.sort(sortRulesFactory("startIndex"))}}__name(insertCustomDecorations,"insertCustomDecorations");function deleteTextRuns(body,textLength,currentIndex){var _a13;const{textRuns}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeTextRuns=[];if(startIndex===endIndex&&(textRuns!=null&&textRuns.find(t=>t.st===currentIndex&&t.ed===currentIndex))){const textRun=textRuns.find(t=>t.st===currentIndex&&t.ed===currentIndex);return removeTextRuns.push({...textRun,st:textRun.st-currentIndex,ed:textRun.ed-currentIndex}),body.textRuns=(_a13=body.textRuns)==null?void 0:_a13.filter(t=>t!==textRun),removeTextRuns}if(textRuns){const newTextRuns=[];for(let i=0,len=textRuns.length;i<len;i++){const textRun=textRuns[i],{st,ed}=textRun;if(startIndex<=st&&endIndex>=ed){removeTextRuns.push({...textRun,st:st-startIndex,ed:ed-startIndex});continue}else st<=startIndex&&ed>=endIndex?(removeTextRuns.push({...textRun,st:startIndex-startIndex,ed:endIndex-startIndex}),textRun.ed-=textLength):startIndex>=st&&startIndex<ed?(removeTextRuns.push({...textRun,st:startIndex-startIndex,ed:ed-startIndex}),textRun.ed=startIndex):endIndex>st&&endIndex<=ed?(removeTextRuns.push({...textRun,st:st-startIndex,ed:endIndex-startIndex}),textRun.st=endIndex-textLength,textRun.ed-=textLength):st>=endIndex&&(textRun.st-=textLength,textRun.ed-=textLength);newTextRuns.push(textRun)}body.textRuns=newTextRuns}return removeTextRuns.length===0&&removeTextRuns.push({st:0,ed:textLength,ts:{}}),removeTextRuns}__name(deleteTextRuns,"deleteTextRuns");function deleteParagraphs(body,textLength,currentIndex){const{paragraphs}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeParagraphs=[];if(paragraphs){const newParagraphs=[];for(let i=0,len=paragraphs.length;i<len;i++){const paragraph=paragraphs[i],{startIndex:index2}=paragraph;if(index2>=startIndex&&index2<endIndex){removeParagraphs.push({...paragraph,startIndex:index2-currentIndex});continue}else index2>=endIndex&&(paragraph.startIndex-=textLength);newParagraphs.push(paragraph)}body.paragraphs=newParagraphs}return removeParagraphs}__name(deleteParagraphs,"deleteParagraphs");function deleteSectionBreaks(body,textLength,currentIndex){const{sectionBreaks}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeSectionBreaks=[];if(sectionBreaks){const newSectionBreaks=[];for(let i=0,len=sectionBreaks.length;i<len;i++){const sectionBreak=sectionBreaks[i],{startIndex:index2}=sectionBreak;if(index2>=startIndex&&index2<=endIndex){removeSectionBreaks.push({...sectionBreak,startIndex:index2-currentIndex});continue}else index2>endIndex&&(sectionBreak.startIndex-=textLength);newSectionBreaks.push(sectionBreak)}body.sectionBreaks=newSectionBreaks}return removeSectionBreaks}__name(deleteSectionBreaks,"deleteSectionBreaks");function deleteCustomBlocks(body,textLength,currentIndex){const{customBlocks}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomBlocks=[];if(customBlocks){const newCustomBlocks=[];for(let i=0,len=customBlocks.length;i<len;i++){const customBlock=customBlocks[i],{startIndex:index2}=customBlock;if(index2>=startIndex&&index2<=endIndex){removeCustomBlocks.push({...customBlock,startIndex:index2-currentIndex});continue}else index2>endIndex&&(customBlock.startIndex-=textLength);newCustomBlocks.push(customBlock)}body.customBlocks=newCustomBlocks}return removeCustomBlocks}__name(deleteCustomBlocks,"deleteCustomBlocks");function deleteTables(body,textLength,currentIndex){const{tables}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeTables=[];if(tables){const newTables=[];for(let i=0,len=tables.length;i<len;i++){const table=tables[i],{startIndex:st,endIndex:ed}=table;if(startIndex<=st&&endIndex>=ed){removeTables.push({...table,startIndex:st-currentIndex,endIndex:ed-currentIndex});continue}else if(st<=startIndex&&ed>=endIndex){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);table.startIndex=segments[0],table.endIndex=segments[1]}else endIndex<st&&(table.startIndex-=textLength,table.endIndex-=textLength);newTables.push(table)}body.tables=newTables}return removeTables}__name(deleteTables,"deleteTables");function deleteCustomRanges(body,textLength,currentIndex){const{customRanges}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomRanges=[];if(customRanges){const newCustomRanges=[];for(let i=0,len=customRanges.length;i<len;i++){const customRange=customRanges[i],{startIndex:st,endIndex:ed}=customRange;if(startIndex<=st&&endIndex>=st){removeCustomRanges.push({...customRange,startIndex:st-currentIndex,endIndex:ed-currentIndex});continue}else if(st<=startIndex&&ed>=endIndex){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);customRange.startIndex=segments[0],customRange.endIndex=segments[1]}else endIndex<st&&(customRange.startIndex-=textLength,customRange.endIndex-=textLength);newCustomRanges.push(customRange)}body.customRanges=newCustomRanges}return removeCustomRanges}__name(deleteCustomRanges,"deleteCustomRanges");function deleteCustomDecorations(body,textLength,currentIndex,needOffset=!0){const{customDecorations}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomDecorations=[];if(customDecorations){const newCustomDecorations=[];for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],{startIndex:st,endIndex:ed}=customDecoration;if(st>=startIndex&&ed<=endIndex){removeCustomDecorations.push(customDecoration);continue}else if(Math.max(startIndex,st)<=Math.min(endIndex,ed)){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);customDecoration.startIndex=segments[0],customDecoration.endIndex=segments[1]}else endIndex<st&&needOffset&&(customDecoration.startIndex-=textLength,customDecoration.endIndex-=textLength);newCustomDecorations.push(customDecoration)}body.customDecorations=newCustomDecorations}return removeCustomDecorations}__name(deleteCustomDecorations,"deleteCustomDecorations");function updateAttribute(body,updateBody,textLength,currentIndex,coverType){const removeTextRuns=updateTextRuns(body,updateBody,textLength,currentIndex,coverType),removeParagraphs=updateParagraphs(body,updateBody,textLength,currentIndex,coverType),removeSectionBreaks=updateSectionBreaks(body,updateBody,textLength,currentIndex,coverType),removeCustomBlocks=updateCustomBlocks(body,updateBody,textLength,currentIndex,coverType),removeTables=updateTables(body,updateBody,textLength,currentIndex,coverType),removeCustomRanges=updateCustomRanges(body,updateBody,textLength,currentIndex,coverType),removeCustomDecorations=updateCustomDecorations(body,updateBody,textLength,currentIndex,coverType);return{dataStream:"",textRuns:removeTextRuns,paragraphs:removeParagraphs,sectionBreaks:removeSectionBreaks,customBlocks:removeCustomBlocks,tables:removeTables,customRanges:removeCustomRanges,customDecorations:removeCustomDecorations}}__name(updateAttribute,"updateAttribute");function updateTextRuns(body,updateBody,textLength,currentIndex,coverType){const{textRuns}=body,{textRuns:updateTextRuns2}=updateBody;if(textRuns==null||updateTextRuns2==null)return;const removeTextRuns=deleteTextRuns(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateTextRun=coverTextRuns(updateTextRuns2,removeTextRuns,coverType);updateBody.textRuns=newUpdateTextRun}return insertTextRuns(body,updateBody,textLength,currentIndex),removeTextRuns}__name(updateTextRuns,"updateTextRuns");function coverTextRuns(updateDataTextRuns,removeTextRuns,coverType){if(removeTextRuns.length===0)return updateDataTextRuns;updateDataTextRuns=Tools.deepClone(updateDataTextRuns),removeTextRuns=Tools.deepClone(removeTextRuns);const newUpdateTextRuns=[],updateLength=updateDataTextRuns.length,removeLength=removeTextRuns.length;let updateIndex=0,removeIndex=0,pending=null;function pushPendingAndReturnStatus(){return pending?(newUpdateTextRuns.push(pending),pending=null,!0):!1}for(__name(pushPendingAndReturnStatus,"pushPendingAndReturnStatus");updateIndex<updateLength&&removeIndex<removeLength;){const{st:updateSt,ed:updateEd,ts:updateStyle}=updateDataTextRuns[updateIndex],{st:removeSt,ed:removeEd,ts:removeStyle,sId}=removeTextRuns[removeIndex];let newTs;if(coverType===UpdateDocsAttributeType.COVER?newTs={...removeStyle,...updateStyle}:newTs={...updateStyle,...removeStyle},updateEd<removeSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(updateDataTextRuns[updateIndex]),updateIndex++;else if(removeEd<updateSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(removeTextRuns[removeIndex]),removeIndex++;else{const newTextRun={st:Math.min(updateSt,removeSt),ed:Math.max(updateSt,removeSt),ts:updateSt<removeSt?{...updateStyle}:{...removeStyle},sId:updateSt<removeSt?void 0:sId};newTextRun.ed>newTextRun.st&&newUpdateTextRuns.push(newTextRun),newUpdateTextRuns.push({st:Math.max(updateSt,removeSt),ed:Math.min(updateEd,removeEd),ts:newTs,sId}),updateEd<removeEd?(updateIndex++,removeTextRuns[removeIndex].st=updateEd,removeTextRuns[removeIndex].st===removeTextRuns[removeIndex].ed&&removeIndex++):(removeIndex++,updateDataTextRuns[updateIndex].st=removeEd,updateDataTextRuns[updateIndex].st===updateDataTextRuns[updateIndex].ed&&updateIndex++);const pendingTextRun={st:Math.min(updateEd,removeEd),ed:Math.max(updateEd,removeEd),ts:updateEd<removeEd?{...removeStyle}:{...updateStyle},sId:updateEd<removeEd?sId:void 0};pending=pendingTextRun.ed>pendingTextRun.st?pendingTextRun:null}}pushPendingAndReturnStatus();const tempTopTextRun=newUpdateTextRuns[newUpdateTextRuns.length-1],updateLastTextRun=updateDataTextRuns[updateLength-1],removeLastTextRun=removeTextRuns[removeLength-1];return tempTopTextRun.ed!==Math.max(updateLastTextRun.ed,removeLastTextRun.ed)&&(updateLastTextRun.ed>removeLastTextRun.ed?newUpdateTextRuns.push(updateLastTextRun):newUpdateTextRuns.push(removeLastTextRun)),normalizeTextRuns(newUpdateTextRuns)}__name(coverTextRuns,"coverTextRuns");function updateParagraphs(body,updateBody,textLength,currentIndex,coverType){const{paragraphs}=body,{paragraphs:updateDataParagraphs}=updateBody;if(paragraphs==null||updateDataParagraphs==null)return;const removeParagraphs=deleteParagraphs(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateParagraphs=[];for(const updateParagraph of updateDataParagraphs){const{startIndex:updateStartIndex,paragraphStyle:updateParagraphStyle,bullet:updateBullet}=updateParagraph;let splitUpdateParagraphs=[];for(const removeParagraph of removeParagraphs){const{startIndex:removeStartIndex,paragraphStyle:removeParagraphStyle,bullet:removeBullet}=removeParagraph;let newParagraphStyle,newBullet;if(coverType===UpdateDocsAttributeType.COVER?(newParagraphStyle={...removeParagraphStyle,...updateParagraphStyle},newBullet={listId:"",listType:PresetListType.BULLET_LIST,nestingLevel:0,textStyle:{},...removeBullet,...updateBullet}):(newParagraphStyle={...updateParagraphStyle,...removeParagraphStyle},newBullet={listId:"",listType:PresetListType.BULLET_LIST,nestingLevel:0,textStyle:{},...updateBullet,...removeBullet}),updateStartIndex===removeStartIndex){splitUpdateParagraphs.push({startIndex:updateStartIndex,paragraphStyle:newParagraphStyle,bullet:newBullet});break}}newUpdateParagraphs.push(...splitUpdateParagraphs),splitUpdateParagraphs=[]}updateBody.paragraphs=newUpdateParagraphs}return insertParagraphs(body,updateBody,textLength,currentIndex),removeParagraphs}__name(updateParagraphs,"updateParagraphs");function updateSectionBreaks(body,updateBody,textLength,currentIndex,coverType){const{sectionBreaks}=body,{sectionBreaks:updateDataSectionBreaks}=updateBody;if(sectionBreaks==null||updateDataSectionBreaks==null)return;const removeSectionBreaks=deleteSectionBreaks(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateSectionBreaks=[];for(const updateSectionBreak of updateDataSectionBreaks){const{startIndex:updateStartIndex}=updateSectionBreak;let splitUpdateSectionBreaks=[];for(const removeSectionBreak of removeSectionBreaks){const{startIndex:removeStartIndex}=removeSectionBreak;if(updateStartIndex===removeStartIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateSectionBreaks.push({...removeSectionBreak,...updateSectionBreak}):splitUpdateSectionBreaks.push({...updateSectionBreak,...removeSectionBreak});break}}newUpdateSectionBreaks.push(...splitUpdateSectionBreaks),splitUpdateSectionBreaks=[]}updateBody.sectionBreaks=newUpdateSectionBreaks}return insertParagraphs(body,updateBody,textLength,currentIndex),removeSectionBreaks}__name(updateSectionBreaks,"updateSectionBreaks");function updateCustomBlocks(body,updateBody,textLength,currentIndex,coverType){const{customBlocks}=body,{customBlocks:updateDataCustomBlocks}=updateBody;if(customBlocks==null||updateDataCustomBlocks==null)return;const removeCustomBlocks=deleteCustomBlocks(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateCustomBlocks=[];for(const updateCustomBlock of updateDataCustomBlocks){const{startIndex:updateStartIndex}=updateCustomBlock;let splitUpdateCustomBlocks=[];for(const removeCustomBlock of removeCustomBlocks){const{startIndex:removeStartIndex}=removeCustomBlock;if(updateStartIndex===removeStartIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateCustomBlocks.push({...removeCustomBlock,...updateCustomBlock}):splitUpdateCustomBlocks.push({...updateCustomBlock,...removeCustomBlock});break}}newUpdateCustomBlocks.push(...splitUpdateCustomBlocks),splitUpdateCustomBlocks=[]}updateBody.customBlocks=newUpdateCustomBlocks}return insertCustomBlocks(body,updateBody,textLength,currentIndex),removeCustomBlocks}__name(updateCustomBlocks,"updateCustomBlocks");function updateTables(body,updateBody,textLength,currentIndex,coverType){const{tables}=body,{tables:updateDataTables}=updateBody;if(tables==null||updateDataTables==null)return;const removeTables=deleteTables(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateTables=[];for(const updateTable of updateDataTables){const{startIndex:updateStartIndex,endIndex:updateEndIndex}=updateTable;let splitUpdateTables=[];for(const removeTable of removeTables){const{startIndex:removeStartIndex,endIndex:removeEndIndex}=removeTable;if(removeStartIndex>=updateStartIndex&&removeEndIndex<=updateEndIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateTables.push({...removeTable,...updateTable}):splitUpdateTables.push({...updateTable,...removeTable});break}}newUpdateTables.push(...splitUpdateTables),splitUpdateTables=[]}updateBody.tables=newUpdateTables}return insertTables(body,updateBody,textLength,currentIndex),removeTables}__name(updateTables,"updateTables");function updateCustomRanges(body,updateBody,textLength,currentIndex,coverType){body.customRanges||(body.customRanges=[]);const{customRanges}=body,{customRanges:updateDataCustomRanges}=updateBody;if(customRanges==null||updateDataCustomRanges==null)return;let removeCustomRanges=[];return coverType===UpdateDocsAttributeType.REPLACE&&(removeCustomRanges=deleteCustomRanges(body,textLength,currentIndex)),insertCustomRanges(body,updateBody,0,currentIndex),removeCustomRanges}__name(updateCustomRanges,"updateCustomRanges");function updateCustomDecorations(body,updateBody,textLength,currentIndex,coverType){body.customDecorations||(body.customDecorations=[]);let removeCustomDecorations=[];return coverType===UpdateDocsAttributeType.REPLACE&&(removeCustomDecorations=deleteCustomDecorations(body,textLength,currentIndex,!1)),insertCustomDecorations(body,updateBody,0,currentIndex),removeCustomDecorations}__name(updateCustomDecorations,"updateCustomDecorations");var SliceBodyType=(SliceBodyType2=>(SliceBodyType2[SliceBodyType2.copy=0]="copy",SliceBodyType2[SliceBodyType2.cut=1]="cut",SliceBodyType2))(SliceBodyType||{});function getBodySlice(body,startOffset,endOffset,returnEmptyTextRun=!1,type2=1){const{dataStream,textRuns=[],paragraphs=[],customBlocks=[]}=body,docBody={dataStream:dataStream.slice(startOffset,endOffset)},newTextRuns=[];for(const textRun of textRuns){const clonedTextRun=Tools.deepClone(textRun),{st,ed}=clonedTextRun;Tools.hasIntersectionBetweenTwoRanges(st,ed,startOffset,endOffset)&&(startOffset>=st&&startOffset<=ed?newTextRuns.push({...clonedTextRun,st:startOffset,ed:Math.min(endOffset,ed)}):endOffset>=st&&endOffset<=ed?newTextRuns.push({...clonedTextRun,st:Math.max(startOffset,st),ed:endOffset}):newTextRuns.push(clonedTextRun))}newTextRuns.length?docBody.textRuns=newTextRuns.map(tr=>{const{st,ed}=tr;return{...tr,st:st-startOffset,ed:ed-startOffset}}):returnEmptyTextRun&&(docBody.textRuns=[{st:0,ed:endOffset-startOffset,ts:{}}]);const newParagraphs=[];for(const paragraph of paragraphs){const{startIndex}=paragraph;startIndex>=startOffset&&startIndex<=endOffset&&newParagraphs.push(Tools.deepClone(paragraph))}newParagraphs.length&&(docBody.paragraphs=newParagraphs.map(p=>({...p,startIndex:p.startIndex-startOffset}))),type2===1&&(docBody.customDecorations=getCustomDecorationSlice(body,startOffset,endOffset));const{customRanges}=getCustomRangeSlice(body,startOffset,endOffset);docBody.customRanges=customRanges;const newCustomBlocks=[];for(const block of customBlocks){const{startIndex}=block;startIndex>=startOffset&&startIndex<=endOffset&&newCustomBlocks.push(Tools.deepClone(block))}return newCustomBlocks.length&&(docBody.customBlocks=newCustomBlocks.map(b=>({...b,startIndex:b.startIndex-startOffset}))),docBody}__name(getBodySlice,"getBodySlice");function normalizeBody(body){const{dataStream,textRuns,paragraphs,customRanges,customDecorations}=body;let leftOffset=0,rightOffset=0;customRanges==null||customRanges.forEach(range=>{range.startIndex<0&&(leftOffset=Math.max(leftOffset,-range.startIndex)),range.endIndex>dataStream.length-1&&(rightOffset=Math.max(rightOffset,range.endIndex-dataStream.length+1))});const newData=`${DataStreamTreeTokenType.CUSTOM_RANGE_START.repeat(leftOffset)}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END.repeat(rightOffset)}`;return textRuns&&(textRuns[0]&&(textRuns[0].st=textRuns[0].st-leftOffset),textRuns[textRuns.length-1]&&(textRuns[textRuns.length-1].ed=textRuns[textRuns.length-1].ed+rightOffset)),textRuns==null||textRuns.forEach(textRun=>{textRun.st+=leftOffset,textRun.ed+=leftOffset}),paragraphs==null||paragraphs.forEach(p=>{p.startIndex+=leftOffset}),customRanges==null||customRanges.forEach(range=>{range.startIndex+=leftOffset,range.endIndex+=leftOffset}),customDecorations==null||customDecorations.forEach(d=>{d.startIndex+=leftOffset,d.endIndex+=rightOffset}),{...body,dataStream:newData,textRuns,paragraphs,customRanges,customDecorations}}__name(normalizeBody,"normalizeBody");function getCustomRangeSlice(body,startOffset,endOffset){const{customRanges=[]}=body;let leftOffset=0,rightOffset=0;const relativeCustomRanges=customRanges.filter(customRange=>Math.max(customRange.startIndex,startOffset)<=Math.min(customRange.endIndex,endOffset-1)).map(range=>({...range,startIndex:range.startIndex,endIndex:range.endIndex}));if(relativeCustomRanges.length){relativeCustomRanges.forEach(customRange=>{customRange.startIndex<startOffset&&(leftOffset+=1),customRange.endIndex>endOffset-1&&(rightOffset+=1)});for(let i=0;i<leftOffset;i++){const range=relativeCustomRanges[i];range.startIndex=startOffset-leftOffset+i}if(rightOffset){const sorted=[...relativeCustomRanges].sort((pre,aft)=>aft.endIndex-pre.endIndex);for(let i=0;i<rightOffset;i++){const range=sorted[i];range.endIndex=endOffset+rightOffset-i-1}}}return{customRanges:relativeCustomRanges.map(range=>({...range,startIndex:range.startIndex-startOffset,endIndex:range.endIndex-startOffset})),leftOffset,rightOffset}}__name(getCustomRangeSlice,"getCustomRangeSlice");function getCustomDecorationSlice(body,startOffset,endOffset){const{customDecorations=[]}=body,customDecorationSlice=[];return customDecorations.forEach(range=>{if(Math.max(range.startIndex,startOffset)<=Math.min(range.endIndex,endOffset-1)){const copy=Tools.deepClone(range);customDecorationSlice.push({...copy,startIndex:Math.max(copy.startIndex-startOffset,0),endIndex:Math.min(copy.endIndex,endOffset)-startOffset})}}),customDecorationSlice}__name(getCustomDecorationSlice,"getCustomDecorationSlice");function composeBody(thisBody,otherBody,coverType=UpdateDocsAttributeType.COVER){if(otherBody.dataStream!=="")throw new Error("Cannot compose other body with non-empty dataStream");const retBody={dataStream:thisBody.dataStream},{textRuns:thisTextRuns=[],paragraphs:thisParagraphs=[]}=thisBody,{textRuns:otherTextRuns=[],paragraphs:otherParagraphs=[]}=otherBody,textRuns=coverTextRuns(otherTextRuns,thisTextRuns,coverType);textRuns.length&&(retBody.textRuns=textRuns);const paragraphs=[];let thisIndex=0,otherIndex=0;for(;thisIndex<thisParagraphs.length&&otherIndex<otherParagraphs.length;){const thisParagraph=thisParagraphs[thisIndex],otherParagraph=otherParagraphs[otherIndex],{startIndex:thisStart}=thisParagraph,{startIndex:otherStart}=otherParagraph;thisStart===otherStart?(paragraphs.push(Tools.deepMerge(thisParagraph,otherParagraph)),thisIndex++,otherIndex++):thisStart<otherStart?(paragraphs.push(Tools.deepClone(thisParagraph)),thisIndex++):(paragraphs.push(Tools.deepClone(otherParagraph)),otherIndex++)}return thisIndex<thisParagraphs.length&&paragraphs.push(...thisParagraphs.slice(thisIndex)),otherIndex<otherParagraphs.length&&paragraphs.push(...otherParagraphs.slice(otherIndex)),paragraphs.length&&(retBody.paragraphs=paragraphs),retBody}__name(composeBody,"composeBody");function isUselessRetainAction(action){const{body}=action;if(body==null)return!0;const{textRuns=[],paragraphs=[]}=body;return textRuns.length===0&&paragraphs.length===0}__name(isUselessRetainAction,"isUselessRetainAction");function getEmptySnapshot$1(unitID=Tools.generateRandomId(6),locale=LocaleType.EN_US,title=""){return{id:unitID,locale,title,body:{dataStream:`\r
8
+ `,textRuns:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:5},lineSpacing:1,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]},documentStyle:{pageSize:{width:793.3333333333334,height:1122.6666666666667},marginTop:50,marginBottom:50,marginRight:40,marginLeft:40,renderConfig:{vertexAngle:0,centerAngle:0}},settings:{}}}__name(getEmptySnapshot$1,"getEmptySnapshot$1");var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}__name(getDefaultExportFromCjs,"getDefaultExportFromCjs");var dist$1={},json1_release={},deepEqual$1={};Object.defineProperty(deepEqual$1,"__esModule",{value:!0});function eqObj(a,b){if(Array.isArray(b))return!1;for(let k in a)if(!deepEqual(a[k],b[k]))return!1;for(let k in b)if(a[k]===void 0)return!1;return!0}__name(eqObj,"eqObj");function eqArr(a,b){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return!1;return!0}__name(eqArr,"eqArr");function deepEqual(a,b){return a===b?!0:a===null||b===null||typeof a!="object"||typeof b!="object"?!1:Array.isArray(a)?eqArr(a,b):eqObj(a,b)}__name(deepEqual,"deepEqual");deepEqual$1.default=deepEqual;var deepClone$1={};Object.defineProperty(deepClone$1,"__esModule",{value:!0});function deepClone(old){if(old===null)return null;if(Array.isArray(old))return old.map(deepClone);if(typeof old=="object"){const o={};for(let k in old)o[k]=deepClone(old[k]);return o}else return old}__name(deepClone,"deepClone");deepClone$1.default=deepClone;var cursor={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.eachChildOf=exports2.advancer=exports2.readCursor=exports2.writeCursor=exports2.WriteCursor=exports2.ReadCursor=exports2.isValidPathItem=void 0;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert");const isObject2=__name(o=>o!=null&&typeof o=="object"&&!Array.isArray(o),"isObject"),isGreaterKey=__name((a,b)=>typeof a==typeof b?a>b:typeof a=="string"&&typeof b=="number","isGreaterKey");function copyAll(c,w){for(let _k in c){const k=_k;w.write(k,c[k])}}__name(copyAll,"copyAll"),exports2.isValidPathItem=k=>typeof k=="number"||typeof k=="string"&&k!=="__proto__";const _Cursor=class _Cursor{constructor(op=null){this.parents=[],this.indexes=[],this.lcIdx=-1,this.idx=-1,this.container=op}ascend(){assert(this.parents.length===this.indexes.length/2),this.idx===0?this.parents.length?(this.lcIdx=this.indexes.pop(),this.container=this.parents.pop(),this.idx=this.indexes.pop()):(this.lcIdx=0,this.idx=-1):(assert(this.idx>0),this.idx--,isObject2(this.container[this.idx])&&this.idx--)}getPath(){const path=[];let c=this.container,p=this.parents.length-1,i=this.idx;for(;i>=0;)path.unshift(c[i]),i===0?(i=this.indexes[p*2],c=this.parents[p--]):i-=isObject2(c[i-1])?2:1;return path}};__name(_Cursor,"Cursor");let Cursor=_Cursor;const _ReadCursor=class _ReadCursor extends Cursor{get(){return this.container?this.container.slice(this.idx+1):null}getKey(){return assert(this.container!=null,"Invalid call to getKey before cursor descended"),this.container[this.idx]}getComponent(){let c;return this.container&&this.container.length>this.idx+1&&isObject2(c=this.container[this.idx+1])?c:null}descendFirst(){let i=this.idx+1;if(!this.container||i>=this.container.length||isObject2(this.container[i])&&i+1>=this.container.length)return!1;isObject2(this.container[i])&&i++;const firstChild=this.container[i];return Array.isArray(firstChild)?(this.indexes.push(this.idx),this.parents.push(this.container),this.indexes.push(i),this.idx=0,this.container=firstChild):this.idx=i,!0}nextSibling(){if(assert(this.parents.length===this.indexes.length/2),this.idx>0||this.parents.length===0)return!1;const i=this.indexes[this.indexes.length-1]+1,c=this.parents[this.parents.length-1];return i>=c.length?!1:(assert(!isNaN(i)),this.indexes[this.indexes.length-1]=i,this.container=c[i],!0)}_init(_container,_idx,_parents,_indexes){this.container=_container,this.idx=_idx,this.parents=_parents.slice(),this.indexes=_indexes.slice()}clone(){const c=new _ReadCursor;return c._init(this.container,this.idx,this.parents,this.indexes),c}*[Symbol.iterator](){if(this.descendFirst()){do yield this.getKey();while(this.nextSibling());this.ascend()}}traverse(w,fn){const c=this.getComponent();c&&fn(c,w);for(const key of this)w&&w.descend(key),this.traverse(w,fn),w&&w.ascend()}eachPick(w,fn){this.traverse(w,(c,w2)=>{c.p!=null&&fn(c.p,w2)})}eachDrop(w,fn){this.traverse(w,(c,w2)=>{c.d!=null&&fn(c.d,w2)})}};__name(_ReadCursor,"ReadCursor");let ReadCursor=_ReadCursor;exports2.ReadCursor=ReadCursor;const _WriteCursor=class _WriteCursor extends Cursor{constructor(op=null){super(op),this.pendingDescent=[],this._op=op}flushDescent(){assert(this.parents.length===this.indexes.length/2),this.container===null&&(this._op=this.container=[]);for(let j=0;j<this.pendingDescent.length;j++){const k=this.pendingDescent[j];let i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i])&&i++,assert(i===this.container.length||!isObject2(this.container[i])),i===this.container.length)this.container.push(k),this.idx=i;else if(this.container[i]===k)this.idx=i;else{if(!Array.isArray(this.container[i])){const oldChild=this.container.splice(i,this.container.length-i);this.container.push(oldChild),this.lcIdx>-1&&(this.lcIdx=i)}for(this.indexes.push(this.idx),this.parents.push(this.container),this.lcIdx!==-1&&(assert(isGreaterKey(k,this.container[this.lcIdx][0])),i=this.lcIdx+1,this.lcIdx=-1);i<this.container.length&&isGreaterKey(k,this.container[i][0]);)i++;if(this.indexes.push(i),this.idx=0,i<this.container.length&&this.container[i][0]===k)this.container=this.container[i];else{const child=[k];this.container.splice(i,0,child),this.container=child}}}this.pendingDescent.length=0}reset(){this.lcIdx=-1}getComponent(){this.flushDescent();const i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i]))return this.container[i];{const component={};return this.container.splice(i,0,component),component}}write(key,value){const component=this.getComponent();assert(component[key]==null||component[key]===value,"Internal consistency error: Overwritten component. File a bug"),component[key]=value}get(){return this._op}descend(key){if(!exports2.isValidPathItem(key))throw Error("Invalid JSON key");this.pendingDescent.push(key)}descendPath(path){return this.pendingDescent.push(...path),this}ascend(){this.pendingDescent.length?this.pendingDescent.pop():super.ascend()}mergeTree(data,mergeFn=copyAll){if(data===null)return;if(assert(Array.isArray(data)),data===this._op)throw Error("Cannot merge into my own tree");const _lcIdx=this.lcIdx,oldDepth=this.parents.length;let depth=0;for(let i=0;i<data.length;i++){const c=data[i];typeof c=="string"||typeof c=="number"?(depth++,this.descend(c)):Array.isArray(c)?this.mergeTree(c,mergeFn):typeof c=="object"&&mergeFn(c,this)}for(;depth--;)this.ascend();this.lcIdx=this.parents.length===oldDepth?_lcIdx:-1}at(path,fn){this.descendPath(path),fn(this);for(let i=0;i<path.length;i++)this.ascend();return this}writeAtPath(path,key,value){return this.at(path,()=>this.write(key,value)),this.reset(),this}writeMove(path1,path2,slot=0){return this.writeAtPath(path1,"p",slot).writeAtPath(path2,"d",slot)}getPath(){const path=super.getPath();return path.push(...this.pendingDescent),path}};__name(_WriteCursor,"WriteCursor");let WriteCursor=_WriteCursor;exports2.WriteCursor=WriteCursor,exports2.writeCursor=()=>new WriteCursor,exports2.readCursor=op=>new ReadCursor(op);function advancer(r,listMap,listAdv){let didDescend,valid;valid=didDescend=r?r.descendFirst():!1;function adv(ktarget){let k2_;for(;valid;){const k2=k2_=r.getKey();if(ktarget!=null){let skip=!1;if(listMap&&typeof k2=="number"&&(k2_=listMap(k2,r.getComponent()),k2_<0&&(k2_=~k2_,skip=!0)),isGreaterKey(k2_,ktarget))return null;if(k2_===ktarget&&!skip)return r}listAdv&&typeof k2_=="number"&&listAdv(k2_,r.getComponent()),valid=r.nextSibling()}return null}return __name(adv,"adv"),adv.end=()=>{didDescend&&r.ascend()},adv}__name(advancer,"advancer"),exports2.advancer=advancer;function eachChildOf(r1,r2,fn){let hasChild1,descended1,hasChild2,descended2;for(hasChild1=descended1=r1&&r1.descendFirst(),hasChild2=descended2=r2&&r2.descendFirst();hasChild1||hasChild2;){let k1=hasChild1?r1.getKey():null,k2=hasChild2?r2.getKey():null;k1!==null&&k2!==null&&(isGreaterKey(k2,k1)?k2=null:k1!==k2&&(k1=null)),fn(k1==null?k2:k1,k1!=null?r1:null,k2!=null?r2:null),k1!=null&&hasChild1&&(hasChild1=r1.nextSibling()),k2!=null&&hasChild2&&(hasChild2=r2.nextSibling())}descended1&&r1.ascend(),descended2&&r2.ascend()}__name(eachChildOf,"eachChildOf"),exports2.eachChildOf=eachChildOf})(cursor);var types={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.ConflictType=void 0,function(ConflictType){ConflictType[ConflictType.RM_UNEXPECTED_CONTENT=1]="RM_UNEXPECTED_CONTENT",ConflictType[ConflictType.DROP_COLLISION=2]="DROP_COLLISION",ConflictType[ConflictType.BLACKHOLE=3]="BLACKHOLE"}(exports2.ConflictType||(exports2.ConflictType={}))})(types);var dist={},unicount={},hasRequiredUnicount;function requireUnicount(){return hasRequiredUnicount||(hasRequiredUnicount=1,Object.defineProperty(unicount,"__esModule",{value:!0}),unicount.uniToStrPos=unicount.strPosToUni=void 0,unicount.strPosToUni=(s,strOffset=s.length)=>{let pairs=0,i=0;for(;i<strOffset;i++){const code=s.charCodeAt(i);code>=55296&&code<=57343&&(pairs++,i++)}if(i!==strOffset)throw Error("Invalid offset - splits unicode bytes");return i-pairs},unicount.uniToStrPos=(s,uniOffset)=>{let pos=0;for(;uniOffset>0;uniOffset--){const code=s.charCodeAt(pos);pos+=code>=55296&&code<=57343?2:1}return pos}),unicount}__name(requireUnicount,"requireUnicount");var type={},hasRequiredType;function requireType(){return hasRequiredType||(hasRequiredType=1,function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.uniSlice=exports2.dlen=exports2.eachOp=void 0;const unicount_1=requireUnicount(),checkOp=__name(op=>{if(!Array.isArray(op))throw Error("Op must be an array of components");let last=null;for(let i=0;i<op.length;i++){const c=op[i];switch(typeof c){case"object":if(typeof c.d!="number"&&typeof c.d!="string")throw Error("Delete must be number or string");if(exports2.dlen(c.d)<=0)throw Error("Deletes must not be empty");break;case"string":if(!(c.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(c>0))throw Error("Skip components must be >0");if(typeof last=="number")throw Error("Adjacent skip components should be combined");break}last=c}if(typeof last=="number")throw Error("Op has a trailing skip")},"checkOp");function eachOp(op,fn){let prePos=0,postPos=0;for(let i=0;i<op.length;i++){const c=op[i];switch(fn(c,prePos,postPos),typeof c){case"object":prePos+=exports2.dlen(c.d);break;case"string":postPos+=unicount_1.strPosToUni(c);break;case"number":prePos+=c,postPos+=c;break}}}__name(eachOp,"eachOp"),exports2.eachOp=eachOp;function mapOp(op,fn){const newOp=[],append=makeAppend(newOp);return eachOp(op,(c,prePos,postPos)=>{append(fn(c,prePos,postPos))}),trim(newOp)}__name(mapOp,"mapOp");const id=__name(x=>x,"id"),normalize=__name(op=>mapOp(op,id),"normalize");exports2.dlen=d=>typeof d=="number"?d:unicount_1.strPosToUni(d);const makeAppend=__name(op=>component=>{if(!(!component||component.d===0||component.d===""))if(op.length===0)op.push(component);else if(typeof component==typeof op[op.length-1])if(typeof component=="object"){const last=op[op.length-1];last.d=typeof last.d=="string"&&typeof component.d=="string"?last.d+component.d:exports2.dlen(last.d)+exports2.dlen(component.d)}else op[op.length-1]+=component;else op.push(component)},"makeAppend"),componentLength=__name(c=>typeof c=="number"?c:typeof c=="string"?unicount_1.strPosToUni(c):typeof c.d=="number"?c.d:unicount_1.strPosToUni(c.d),"componentLength");exports2.uniSlice=(s,startUni,endUni)=>{const start=unicount_1.uniToStrPos(s,startUni),end=endUni==null?1/0:unicount_1.uniToStrPos(s,endUni);return s.slice(start,end)};const dslice=__name((d,start,end)=>typeof d=="number"?end==null?d-start:Math.min(d,end)-start:exports2.uniSlice(d,start,end),"dslice"),makeTake=__name(op=>{let idx=0,offset=0;return{take:__name((n,indivisableField)=>{if(idx===op.length)return n===-1?null:n;const c=op[idx];let part;if(typeof c=="number")return n===-1||c-offset<=n?(part=c-offset,++idx,offset=0,part):(offset+=n,n);if(typeof c=="string"){if(n===-1||indivisableField==="i"||unicount_1.strPosToUni(c.slice(offset))<=n)return part=c.slice(offset),++idx,offset=0,part;{const offset2=offset+unicount_1.uniToStrPos(c.slice(offset),n);return part=c.slice(offset,offset2),offset=offset2,part}}else{if(n===-1||indivisableField==="d"||exports2.dlen(c.d)-offset<=n)return part={d:dslice(c.d,offset)},++idx,offset=0,part;{let result=dslice(c.d,offset,offset+n);return offset+=n,{d:result}}}},"take"),peek:__name(()=>op[idx],"peek")}},"makeTake"),trim=__name(op=>(op.length>0&&typeof op[op.length-1]=="number"&&op.pop(),op),"trim");function transform(op1,op2,side){if(side!=="left"&&side!=="right")throw Error("side ("+side+") must be 'left' or 'right'");checkOp(op1),checkOp(op2);const newOp=[],append=makeAppend(newOp),{take,peek}=makeTake(op1);for(let i=0;i<op2.length;i++){const c2=op2[i];let length,c1;switch(typeof c2){case"number":for(length=c2;length>0;)c1=take(length,"i"),append(c1),typeof c1!="string"&&(length-=componentLength(c1));break;case"string":side==="left"&&typeof peek()=="string"&&append(take(-1)),append(unicount_1.strPosToUni(c2));break;case"object":for(length=exports2.dlen(c2.d);length>0;)switch(c1=take(length,"i"),typeof c1){case"number":length-=c1;break;case"string":append(c1);break;case"object":length-=exports2.dlen(c1.d)}break}}let c;for(;c=take(-1);)append(c);return trim(newOp)}__name(transform,"transform");function compose(op1,op2){checkOp(op1),checkOp(op2);const result=[],append=makeAppend(result),{take}=makeTake(op1);for(let i=0;i<op2.length;i++){const component=op2[i];let length,chunk;switch(typeof component){case"number":for(length=component;length>0;)chunk=take(length,"d"),append(chunk),typeof chunk!="object"&&(length-=componentLength(chunk));break;case"string":append(component);break;case"object":length=exports2.dlen(component.d);let offset=0;for(;offset<length;)switch(chunk=take(length-offset,"d"),typeof chunk){case"number":append({d:dslice(component.d,offset,offset+chunk)}),offset+=chunk;break;case"string":offset+=unicount_1.strPosToUni(chunk);break;case"object":append(chunk)}break}}let c;for(;c=take(-1);)append(c);return trim(result)}__name(compose,"compose");const transformPosition=__name((cursor2,op)=>{let pos=0;for(let i=0;i<op.length&&cursor2>pos;i++){const c=op[i];switch(typeof c){case"number":{pos+=c;break}case"string":const offset=unicount_1.strPosToUni(c);pos+=offset,cursor2+=offset;break;case"object":cursor2-=Math.min(exports2.dlen(c.d),cursor2-pos);break}}return cursor2},"transformPosition"),transformSelection=__name((selection,op)=>typeof selection=="number"?transformPosition(selection,op):selection.map(s=>transformPosition(s,op)),"transformSelection");function makeInvertible(op,doc,ropeImpl){return mapOp(op,(c,prePos)=>typeof c=="object"&&typeof c.d=="number"?{d:ropeImpl.slice(doc,prePos,prePos+c.d)}:c)}__name(makeInvertible,"makeInvertible");function invert(op){return mapOp(op,c=>{switch(typeof c){case"object":if(typeof c.d=="number")throw Error("Cannot invert text op: Deleted characters missing from operation. makeInvertible must be called first.");return c.d;case"string":return{d:c};case"number":return c}})}__name(invert,"invert");function stripInvertible(op){return mapOp(op,c=>typeof c=="object"&&typeof c.d=="string"?{d:unicount_1.strPosToUni(c.d)}:c)}__name(stripInvertible,"stripInvertible");function isInvertible(op){let invertible=!0;return eachOp(op,c=>{typeof c=="object"&&typeof c.d=="number"&&(invertible=!1)}),invertible}__name(isInvertible,"isInvertible");function makeType(ropeImpl){return{name:"text-unicode",uri:"http://sharejs.org/types/text-unicode",trim,normalize,checkOp,create(initial=""){if(typeof initial!="string")throw Error("Initial data must be a string");return ropeImpl.create(initial)},apply(str,op){checkOp(op);const builder=ropeImpl.builder(str);for(let i=0;i<op.length;i++){const component=op[i];switch(typeof component){case"number":builder.skip(component);break;case"string":builder.append(component);break;case"object":builder.del(exports2.dlen(component.d));break}}return builder.build()},transform,compose,transformPosition,transformSelection,isInvertible,makeInvertible(op,doc){return makeInvertible(op,doc,ropeImpl)},stripInvertible,invert,invertWithDoc(op,doc){return invert(makeInvertible(op,doc,ropeImpl))},isNoop:__name(op=>op.length===0,"isNoop")}}__name(makeType,"makeType"),exports2.default=makeType}(type)),type}__name(requireType,"requireType");var api={},hasRequiredApi;function requireApi(){if(hasRequiredApi)return api;hasRequiredApi=1,Object.defineProperty(api,"__esModule",{value:!0});const type_1=requireType(),unicount_1=requireUnicount();function api$1(getSnapshot,submitOp){return{get:getSnapshot,getLength(){return getSnapshot().length},insert(pos,text,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,text],callback)},remove(pos,lengthOrContent,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,{d:lengthOrContent}],callback)},_onOp(op){type_1.eachOp(op,(component,prePos,postPos)=>{switch(typeof component){case"string":this.onInsert&&this.onInsert(postPos,component);break;case"object":const dl=type_1.dlen(component.d);this.onRemove&&this.onRemove(postPos,dl)}})},onInsert:null,onRemove:null}}return __name(api$1,"api$1"),api.default=api$1,api$1.provides={text:!0},api}__name(requireApi,"requireApi");var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=commonjsGlobal&&commonjsGlobal.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.type=exports2.remove=exports2.insert=void 0;const unicount_1=requireUnicount(),type_1=__importStar(requireType()),api_1=__importDefault(requireApi()),ropeImplUnicodeString={create(s){return s},toString(s){return s},builder(oldDoc){if(typeof oldDoc!="string")throw Error("Invalid document snapshot: "+oldDoc);const newDoc=[];return{skip(n){let offset=unicount_1.uniToStrPos(oldDoc,n);if(offset>oldDoc.length)throw Error("The op is too long for this document");newDoc.push(oldDoc.slice(0,offset)),oldDoc=oldDoc.slice(offset)},append(s){newDoc.push(s)},del(n){oldDoc=oldDoc.slice(unicount_1.uniToStrPos(oldDoc,n))},build(){return newDoc.join("")+oldDoc}}},slice:type_1.uniSlice},textString=type_1.default(ropeImplUnicodeString),type2=Object.assign(Object.assign({},textString),{api:api_1.default});exports2.type=type2,exports2.insert=(pos,text)=>text.length===0?[]:pos===0?[text]:[pos,text],exports2.remove=(pos,textOrLen)=>type_1.dlen(textOrLen)===0?[]:pos===0?[{d:textOrLen}]:[pos,{d:textOrLen}];var type_2=requireType();Object.defineProperty(exports2,"makeType",{enumerable:!0,get:__name(function(){return type_2.default},"get")})}(dist)),dist}__name(requireDist,"requireDist");(function(exports2){var __importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.editOp=exports2.replaceOp=exports2.insertOp=exports2.moveOp=exports2.removeOp=exports2.type=void 0;const deepEqual_js_1=__importDefault(deepEqual$1),deepClone_js_1=__importDefault(deepClone$1),cursor_js_1=cursor,types_js_1=types;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert"),exports2.type={name:"json1",uri:"http://sharejs.org/types/JSONv1",readCursor:cursor_js_1.readCursor,writeCursor:cursor_js_1.writeCursor,create:__name(data=>data,"create"),isNoop:__name(op=>op==null,"isNoop"),setDebug(val){},registerSubtype,checkValidOp,normalize,apply,transformPosition,compose,tryTransform,transform,makeInvertible,invert,invertWithDoc,RM_UNEXPECTED_CONTENT:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,DROP_COLLISION:types_js_1.ConflictType.DROP_COLLISION,BLACKHOLE:types_js_1.ConflictType.BLACKHOLE,transformNoConflict:__name((op1,op2,side)=>transformWithConflictsPred(()=>!0,op1,op2,side),"transformNoConflict"),typeAllowingConflictsPred:__name(allowConflict=>Object.assign(Object.assign({},exports2.type),{transform:__name((op1,op2,side)=>transformWithConflictsPred(allowConflict,op1,op2,side),"transform")}),"typeAllowingConflictsPred")};const getComponent=__name(r=>r?r.getComponent():null,"getComponent");function isObject2(o){return o&&typeof o=="object"&&!Array.isArray(o)}__name(isObject2,"isObject");const shallowClone=__name(obj=>Array.isArray(obj)?obj.slice():obj!==null&&typeof obj=="object"?Object.assign({},obj):obj,"shallowClone"),hasPick=__name(c=>c&&(c.p!=null||c.r!==void 0),"hasPick"),hasDrop=__name(c=>c&&(c.d!=null||c.i!==void 0),"hasDrop");function removeChild(container,key){return assert(container!=null),typeof key=="number"?(assert(Array.isArray(container),"Invalid key - child is not an array"),(container=container.slice()).splice(key,1)):(assert(isObject2(container),"Invalid key - child is not an object"),delete(container=Object.assign({},container))[key]),container}__name(removeChild,"removeChild");function insertChildMut(container,key,value){return typeof key=="number"?(assert(container!=null,"Container is missing for key"),assert(Array.isArray(container),"Cannot use numerical key for object container"),assert(container.length>=key,"Cannot insert into out of bounds index"),container.splice(key,0,value)):(assert(isObject2(container),"Cannot insert into missing item"),assert(container[key]===void 0,"Trying to overwrite value at key. Your op needs to remove it first"),container[key]=value),value}__name(insertChildMut,"insertChildMut"),exports2.removeOp=(path,value=!0)=>cursor_js_1.writeCursor().writeAtPath(path,"r",value).get(),exports2.moveOp=(from,to)=>cursor_js_1.writeCursor().writeMove(from,to).get(),exports2.insertOp=(path,value)=>cursor_js_1.writeCursor().writeAtPath(path,"i",value).get(),exports2.replaceOp=(path,oldVal,newVal)=>cursor_js_1.writeCursor().at(path,w=>{w.write("r",oldVal),w.write("i",newVal)}).get(),exports2.editOp=(path,type2,subOp,preserveNoop=!1)=>cursor_js_1.writeCursor().at(path,w=>writeEdit(w,type2,subOp,preserveNoop)).get();const isValidKey=__name((container,key)=>container!=null&&(typeof key=="number"?Array.isArray(container):typeof container=="object"),"isValidKey"),maybeGetChild=__name((container,key)=>isValidKey(container,key)?container[key]:void 0,"maybeGetChild"),subtypes={};function registerSubtype(subtype){let _subtype=subtype.type?subtype.type:subtype;_subtype.name&&(subtypes[_subtype.name]=_subtype),_subtype.uri&&(subtypes[_subtype.uri]=_subtype)}__name(registerSubtype,"registerSubtype");const typeOrThrow=__name(name=>{const type2=subtypes[name];if(type2)return type2;throw Error("Missing type: "+name)},"typeOrThrow");registerSubtype(requireDist());const add=__name((a,b)=>a+b,"add");registerSubtype({name:"number",apply:add,compose:add,invert:__name(n=>-n,"invert"),transform:__name(a=>a,"transform")});const getEditType=__name(c=>c==null?null:c.et?typeOrThrow(c.et):c.es?subtypes["text-unicode"]:c.ena!=null?subtypes.number:null,"getEditType"),getEdit=__name(c=>c.es?c.es:c.ena!=null?c.ena:c.e,"getEdit"),writeEdit=__name((w,typeOrName,edit,preserveNoop=!1)=>{const[type2,name]=typeof typeOrName=="string"?[typeOrThrow(typeOrName),typeOrName]:[typeOrName,typeOrName.name];!preserveNoop&&type2.isNoop&&type2.isNoop(edit)||(name==="number"?w.write("ena",edit):name==="text-unicode"?w.write("es",edit):(w.write("et",name),w.write("e",edit)))},"writeEdit");function checkNonNegInteger(n){assert(typeof n=="number"),assert(n>=0),assert(n===(0|n))}__name(checkNonNegInteger,"checkNonNegInteger");function checkScalar(s){typeof s=="number"?checkNonNegInteger(s):assert(typeof s=="string")}__name(checkScalar,"checkScalar");function checkValidOp(op){if(op===null)return;const pickedSlots=new Set,droppedSlots=new Set,checkComponent=__name(e=>{let empty=!0,hasEdit=!1;for(let k in e){const v=e[k];if(empty=!1,assert(k==="p"||k==="r"||k==="d"||k==="i"||k==="e"||k==="es"||k==="ena"||k==="et","Invalid component item '"+k+"'"),k==="p")checkNonNegInteger(v),assert(!pickedSlots.has(v)),pickedSlots.add(v),assert(e.r===void 0);else if(k==="d")checkNonNegInteger(v),assert(!droppedSlots.has(v)),droppedSlots.add(v),assert(e.i===void 0);else if(k==="e"||k==="es"||k==="ena"){assert(!hasEdit),hasEdit=!0;const t=getEditType(e);assert(t,"Missing type in edit"),t.checkValidOp&&t.checkValidOp(getEdit(e))}}assert(!empty)},"checkComponent"),checkDescent=__name((descent,isRoot,removed)=>{if(!Array.isArray(descent))throw Error("Op must be null or a list");if(descent.length===0)throw Error("Empty descent");isRoot||checkScalar(descent[0]);let last=1,numDescents=0,lastKey=0;for(let i=0;i<descent.length;i++){const d=descent[i];if(assert(d!=null),Array.isArray(d)){const key=checkDescent(d,!1);if(numDescents){const t1=typeof lastKey,t2=typeof key;t1===t2?assert(lastKey<key,"descent keys are not in order"):assert(t1==="number"&&t2==="string")}lastKey=key,numDescents++,last=3}else typeof d=="object"?(assert(last===1,`Prev not scalar - instead ${last}`),checkComponent(d),last=2):(assert(last!==3),checkScalar(d),assert(cursor_js_1.isValidPathItem(d),"Invalid path key"),last=1)}return assert(numDescents!==1,"Operation makes multiple descents. Remove some []"),assert(last===2||last===3),descent[0]},"checkDescent");checkDescent(op,!0),assert(pickedSlots.size===droppedSlots.size,"Mismatched picks and drops in op");for(let i=0;i<pickedSlots.size;i++)assert(pickedSlots.has(i)),assert(droppedSlots.has(i))}__name(checkValidOp,"checkValidOp");function normalize(op){let nextSlot=0,slotMap=[];const w=cursor_js_1.writeCursor();return w.mergeTree(op,(c,w2)=>{const t=getEditType(c);if(t){const op2=getEdit(c);writeEdit(w2,t,t.normalize?t.normalize(op2):op2)}for(const k of["r","p","i","d"])if(c[k]!==void 0){const r=k==="p"||k==="d"?(inSlot=c[k],slotMap[inSlot]==null&&(slotMap[inSlot]=nextSlot++),slotMap[inSlot]):c[k];w2.write(k,r)}var inSlot}),w.get()}__name(normalize,"normalize");function apply(snapshot,op){if(checkValidOp(op),op===null)return snapshot;const held=[];return __name(function drop(root,descent){let subDoc=root,i=0,rootContainer={root},m=0,container=rootContainer,key="root";function mut(){for(;m<i;m++){let d=descent[m];typeof d!="object"&&(assert(isValidKey(container,key)),container=container[key]=shallowClone(container[key]),key=d)}}for(__name(mut,"mut");i<descent.length;i++){const d=descent[i];if(Array.isArray(d)){const child=drop(subDoc,d);child!==subDoc&&child!==void 0&&(mut(),subDoc=container[key]=child)}else if(typeof d=="object"){d.d!=null?(mut(),subDoc=insertChildMut(container,key,held[d.d])):d.i!==void 0&&(mut(),subDoc=insertChildMut(container,key,d.i));const t=getEditType(d);if(t)mut(),subDoc=container[key]=t.apply(subDoc,getEdit(d));else if(d.e!==void 0)throw Error("Subtype "+d.et+" undefined")}else subDoc=maybeGetChild(subDoc,d)}return rootContainer.root},"drop")(snapshot=__name(function pick(subDoc,descent){const stack=[];let i=0;for(;i<descent.length;i++){const d=descent[i];if(Array.isArray(d))break;typeof d!="object"&&(stack.push(subDoc),subDoc=maybeGetChild(subDoc,d))}for(let j=descent.length-1;j>=i;j--)subDoc=pick(subDoc,descent[j]);for(--i;i>=0;i--){const d=descent[i];if(typeof d!="object"){const container=stack.pop();subDoc=subDoc===maybeGetChild(container,d)?container:subDoc===void 0?removeChild(container,d):(k=d,v=subDoc,(obj=shallowClone(obj=container))[k]=v,obj)}else hasPick(d)&&(assert(subDoc!==void 0,"Cannot pick up or remove undefined"),d.p!=null&&(held[d.p]=subDoc),subDoc=void 0)}var obj,k,v;return subDoc},"pick")(snapshot,op),op)}__name(apply,"apply");function transformPosition(path,op){path=path.slice(),checkValidOp(op);const r=cursor_js_1.readCursor(op);let pickedAtSlot,pickIndex,removed=!1;const advStack=[];for(let i=0;;i++){const k=path[i],c=r.getComponent();if(c&&(c.r!==void 0?removed=!0:c.p!=null&&(removed=!1,pickedAtSlot=c.p,pickIndex=i)),i>=path.length)break;let pickOffset=0;const pickAdv=cursor_js_1.advancer(r,void 0,(k2,c2)=>{hasPick(c2)&&pickOffset++});advStack.unshift(pickAdv);const hasNext=pickAdv(k);if(typeof k=="number"&&(path[i]-=pickOffset),!hasNext)break}if(advStack.forEach(pickAdv=>pickAdv.end()),removed)return null;const handleDrop=__name(()=>{let i=0;if(pickedAtSlot!=null){const rPath=r.getPath();i=rPath.length,path=rPath.concat(path.slice(pickIndex))}for(;i<path.length;i++){const k=path[i],c=getComponent(r),et=getEditType(c);if(et){const e=getEdit(c);et.transformPosition&&(path[i]=et.transformPosition(path[i],e));break}let dropOffset=0;const hasNext=cursor_js_1.advancer(r,(k2,c2)=>hasDrop(c2)?~(k2-dropOffset):k2-dropOffset,(k2,c2)=>{hasDrop(c2)&&dropOffset++})(k);if(typeof k=="number"&&(path[i]+=dropOffset),!hasNext)break}},"handleDrop");return pickedAtSlot!=null?r.eachDrop(null,slot=>{slot===pickedAtSlot&&handleDrop()}):handleDrop(),path}__name(transformPosition,"transformPosition");function compose(op1,op2){if(checkValidOp(op1),checkValidOp(op2),op1==null)return op2;if(op2==null)return op1;let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor(),heldPickWrites=[],heldDropWrites=[],held1Pick=[],held2Drop=[],p1SlotMap=[],p2SlotMap=[],visitedOp2EditCs=new Set;r1.traverse(null,c=>{c.p!=null&&(held1Pick[c.p]=r1.clone())}),r2.traverse(null,c=>{c.d!=null&&(held2Drop[c.d]=r2.clone())});const w2=cursor_js_1.writeCursor();return __name(function xfBoundary(r1Pick,r1Drop,r2Pick,r2Drop,litIn,rmParent,wd,wp){assert(r1Drop||r2Pick);const c1d=getComponent(r1Drop),c2p=getComponent(r2Pick),rmHere=!!c2p&&c2p.r!==void 0,insHere=!!c1d&&c1d.i!==void 0,drop1Slot=c1d?c1d.d:null,pick2Slot=c2p?c2p.p:null,rmChildren=(rmParent||rmHere)&&pick2Slot==null;if(pick2Slot!=null)r2Drop=held2Drop[pick2Slot],wd=heldDropWrites[pick2Slot]=new cursor_js_1.WriteCursor;else if(c2p&&c2p.r!==void 0)r2Drop=null;else{const c2d2=getComponent(r2Drop);c2d2&&c2d2.d!=null&&(r2Drop=null)}const c2d=getComponent(r2Drop);if(drop1Slot!=null)if(r1Pick=held1Pick[drop1Slot],wp=heldPickWrites[drop1Slot]=new cursor_js_1.WriteCursor,rmChildren)rmParent&&!rmHere&&wp.write("r",!0);else{const slot=p1SlotMap[drop1Slot]=nextSlot++;wd.write("d",slot)}else if(c1d&&c1d.i!==void 0)r1Pick=null;else{const c1p=getComponent(r1Pick);c1p&&c1p.p!=null&&(r1Pick=null)}let litOut;insHere?(assert(litIn===void 0),litOut=c1d.i):litOut=litIn;const insComponent=(pick2Slot==null?!insHere||rmParent||rmHere:litOut===void 0)?null:wd.getComponent();if(pick2Slot!=null){if(!(litIn!==void 0||insHere)){const slot=drop1Slot!=null?p1SlotMap[drop1Slot]:nextSlot++;p2SlotMap[pick2Slot]=slot,wp.write("p",slot)}}else rmHere&&(insHere||litIn!==void 0||(c2p.r,wp.write("r",c2p.r)));const type1=rmChildren?null:getEditType(c1d),type2=getEditType(c2d);if((type1||type2)&&(type1&&type1.name,type2&&type2.name),type1&&type2){assert(type1===type2);const e1=getEdit(c1d),e2=getEdit(c2d),r=type1.compose(e1,e2);writeEdit(wd,type1,r),visitedOp2EditCs.add(c2d)}else type1?writeEdit(wd,type1,getEdit(c1d)):type2&&(writeEdit(wd,type2,getEdit(c2d)),visitedOp2EditCs.add(c2d));const hasContainerLiteral=typeof litOut=="object"&&litOut!=null;let isCloned=!1,p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,litOff=0;const p2DropAdv=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?p2DropOff-k-1:k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++}),p1PickAdv=cursor_js_1.advancer(r1Pick,(k,c)=>hasPick(c)?p1PickOff-k-1:k-p1PickOff,(k,c)=>{hasPick(c)&&p1PickOff++});if(cursor_js_1.eachChildOf(r1Drop,r2Pick,(inKey,_p1Drop,_p2Pick)=>{let _p1Pick,_p2Drop,p1PickKey=inKey,p2DropKey=inKey,litKey=inKey;if(typeof inKey=="number"){let p2Mid=inKey+p2PickOff;_p2Drop=p2DropAdv(p2Mid),p2DropKey=p2Mid+p2DropOff;let p1Mid=inKey+p1DropOff;_p1Pick=p1PickAdv(p1Mid),hasDrop(getComponent(_p2Drop))&&(_p1Pick=null),p1PickKey=p1Mid+p1PickOff,litKey=inKey+litOff,assert(p1PickKey>=0,"p1PickKey is negative"),assert(p2DropKey>=0,"p2DropKey is negative");const hd1=hasDrop(getComponent(_p1Drop)),hp2=hasPick(getComponent(_p2Pick));(hd1||hp2&&!rmChildren)&&litOff--,hd1&&p1DropOff--,hp2&&p2PickOff--}else _p1Pick=p1PickAdv(inKey),_p2Drop=p2DropAdv(inKey);wp.descend(p1PickKey),wd.descend(p2DropKey);const _lit=hasContainerLiteral&&!hasDrop(getComponent(_p1Drop))?litOut[litKey]:void 0,_litResult=xfBoundary(_p1Pick,_p1Drop,_p2Pick,_p2Drop,_lit,rmChildren,wd,wp);var container,key,child;hasContainerLiteral&&!rmChildren?_lit!==_litResult&&(isCloned||(litOut=Array.isArray(litOut)?litOut.slice():Object.assign({},litOut),isCloned=!0),container=litOut,child=_litResult,typeof(key=litKey)=="number"?(assert(Array.isArray(container)),assert(key<container.length)):(assert(!Array.isArray(container)),assert(container[key]!==void 0)),child===void 0?typeof key=="number"?container.splice(key,1):delete container[key]:container[key]=child):assert(_litResult===void 0),wd.ascend(),wp.ascend()}),p1PickAdv.end(),p2DropAdv.end(),insComponent!=null)insComponent.i=litOut;else if(!rmParent&&!rmHere&&pick2Slot==null)return litOut},"xfBoundary")(r1,r1.clone(),r2,r2.clone(),void 0,!1,w,w2),w.reset(),w.mergeTree(w2.get()),w.reset(),w.get(),heldPickWrites.map(w3=>w3.get()),heldDropWrites.map(w3=>w3.get()),r1.traverse(w,(c,w3)=>{const slot1=c.p;if(slot1!=null){const slot=p1SlotMap[slot1];slot!=null&&w3.write("p",slot);const _w=heldPickWrites[slot1];_w&&_w.get(),_w&&w3.mergeTree(_w.get())}else c.r!==void 0&&w3.write("r",c.r)}),w.reset(),w.get(),r2.traverse(w,(c,w3)=>{const slot2=c.d;if(slot2!=null){const slot=p2SlotMap[slot2];slot!=null&&w3.write("d",slot);const _w=heldDropWrites[slot2];_w&&w3.mergeTree(_w.get())}else c.i!==void 0&&w3.write("i",c.i);const t=getEditType(c);t&&!visitedOp2EditCs.has(c)&&writeEdit(w3,t,getEdit(c))}),w.get()}__name(compose,"compose");function invert(op){if(op==null)return null;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let editsToTransform;const heldPick=[],heldWrites=[];return __name(function invertSimple(r2,w2,subDoc){const c=r2.getComponent();let insertHere,subdocModified=!1;if(c){c.p!=null&&(w2.write("d",c.p),heldPick[c.p]=r2.clone()),c.r!==void 0&&w2.write("i",c.r),c.d!=null&&(w2.write("p",c.d),subDoc=void 0),c.i!==void 0&&(subDoc=insertHere=c.i);const t=getEditType(c);t&&(subDoc===void 0?(editsToTransform||(editsToTransform=new Set),editsToTransform.add(c)):(getEdit(c),subDoc=t.apply(subDoc,getEdit(c)),subdocModified=!0))}let dropOff=0;for(const key of r2){w2.descend(key);const raw=typeof key=="number"?key-dropOff:key,childIn=maybeGetChild(subDoc,raw);hasDrop(r2.getComponent())&&dropOff++;const childOut=invertSimple(r2,w2,childIn);if(subDoc!==void 0&&childOut!==void 0){if(subdocModified||(subdocModified=!0,subDoc=shallowClone(subDoc)),!isValidKey(subDoc,raw))throw Error("Cannot modify child - invalid operation");subDoc[raw]=childOut}w2.ascend()}if(insertHere===void 0)return subdocModified?subDoc:void 0;w2.write("r",subDoc)},"invertSimple")(r,w,void 0),editsToTransform&&(w.reset(),__name(function transformEdits(rPick,rDrop,w2){const cd=rDrop.getComponent();if(cd){const dropSlot=cd.d;if(dropSlot!=null&&(rPick=heldPick[dropSlot],w2=heldWrites[dropSlot]=cursor_js_1.writeCursor()),editsToTransform.has(cd)){const t=getEditType(cd);if(!t.invert)throw Error(`Cannot invert subtype ${t.name}`);writeEdit(w2,t,t.invert(getEdit(cd)))}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c)=>hasPick(c)?pickOff-k-1:k-pickOff,(k,c)=>{hasPick(c)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff;w2.descend(raw),transformEdits(_rPick,rDrop,w2),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else w2.descend(key),transformEdits(ap(key),rDrop,w2),w2.ascend();ap.end()},"transformEdits")(r.clone(),r,w),heldWrites.length&&(w.reset(),r.traverse(w,(c,w2)=>{const slot=c.p;if(slot!=null){const _w=heldWrites[slot];_w&&_w.get(),_w&&w2.mergeTree(_w.get())}}))),w.get()}__name(invert,"invert");const anyComponent=__name((op,fn)=>op.some(c=>typeof c=="object"&&(Array.isArray(c)?anyComponent(c,fn):fn(c))),"anyComponent");function makeInvertible(op,doc){if(op==null||!anyComponent(op,c=>{var _a13;return c.r!==void 0||((_a13=getEditType(c))===null||_a13===void 0?void 0:_a13.makeInvertible)!=null}))return op;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let hasEdits=!1;const heldPick=[],heldDoc=[],traversePick=__name((r2,w2,subDoc)=>{const c=r2.getComponent();let modified=!1;if(c){c.d!=null&&w2.write("d",c.d),c.i!==void 0&&w2.write("i",c.i);const pickSlot=c.p;if(pickSlot!=null&&(heldPick[pickSlot]=r2.clone(),assert(subDoc!==void 0,"Operation picks up at an invalid key"),heldDoc[pickSlot]=subDoc,w2.write("p",c.p)),c.r!==void 0&&subDoc===void 0)throw Error("Invalid doc / op in makeInvertible: removed item missing from doc");const t=getEditType(c);t&&(t.makeInvertible?hasEdits=!0:writeEdit(w2,t,getEdit(c),!0))}let listOff=0;for(const key of r2){w2.descend(key);const keyRaw=typeof key=="number"?key-listOff:key,childIn=maybeGetChild(subDoc,keyRaw),childOut=traversePick(r2,w2,childIn);childIn!==childOut&&(modified||(modified=!0,subDoc=shallowClone(subDoc)),childOut===void 0?(subDoc=removeChild(subDoc,keyRaw),typeof key=="number"&&listOff++):subDoc[keyRaw]=childOut),w2.ascend()}return c&&(c.r!==void 0?(w2.write("r",deepClone_js_1.default(subDoc)),subDoc=void 0):c.p!=null&&(subDoc=void 0)),subDoc},"traversePick");return traversePick(r,w,doc),w.get(),hasEdits&&(w.reset(),__name(function traverseDrop(rPick,rDrop,w2,subDoc,isLiteral){const c=rDrop.getComponent();if(c){c.i!==void 0?(subDoc=c.i,isLiteral=!0):c.d!=null&&(subDoc=heldDoc[c.d],rPick=heldPick[c.d],isLiteral=!1,c.d);let t=getEditType(c);if(t&&t.makeInvertible){const edit=getEdit(c);writeEdit(w2,t,t.makeInvertible(edit,subDoc),!0)}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c2)=>hasPick(c2)?pickOff-k-1:k-pickOff,(k,c2)=>{hasPick(c2)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff,child=maybeGetChild(subDoc,isLiteral?mid:raw);w2.descend(key),traverseDrop(_rPick,rDrop,w2,child,isLiteral),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else{const child=maybeGetChild(subDoc,key);w2.descend(key),traverseDrop(ap(key),rDrop,w2,child,isLiteral),w2.ascend()}ap.end()},"traverseDrop")(r.clone(),r,w,doc,!1)),w.get()}__name(makeInvertible,"makeInvertible");function invertWithDoc(op,doc){return invert(makeInvertible(op,doc))}__name(invertWithDoc,"invertWithDoc");const shallowCloneOp=__name(op=>{if(op==null)return null;const result=op.slice();for(let i=0;i<op.length;i++){const c=result[i];Array.isArray(c)&&(result[i]=shallowCloneOp(c))}return result},"shallowCloneOp");function tryTransform(op1,op2,direction){assert(direction==="left"||direction==="right","Direction must be left or right");const side=direction==="left"?0:1;if(op2==null)return{ok:!0,result:op1};checkValidOp(op1),checkValidOp(op2);let conflict=null;const heldOp1PickByOp1=[],heldOp1DropByOp1=[],heldOp2PickByOp2=[],heldOp2DropByOp2=[],heldOp1PickByOp2=[],heldOp2PickByOp1=[],heldOp2DropByOp1=[],heldOp2RmForOp1=[],heldOp1RmForOp2=[],cancelledOp2=[],discardedOp2Drop=[],heldPickWrites=[],heldDropWrites=[],op1PickAtOp2Pick=[],op1PicksOp2DropSlots=[];let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor();if(__name(function scanOp2Pick(r2Pick,r1Pick=null,removed1){const c1=getComponent(r1Pick);c1&&(c1.r!==void 0?removed1=r1Pick.clone():c1.p!=null&&(removed1=null,heldOp2PickByOp1[c1.p]=r2Pick.clone()));const c2=r2Pick.getComponent();let slot2;c2&&(slot2=c2.p)!=null&&(heldOp1PickByOp2[slot2]=r1Pick?r1Pick.clone():null,heldOp2PickByOp2[slot2]=r2Pick.clone(),removed1&&(cancelledOp2[slot2]=!0,heldOp1RmForOp2[slot2]=removed1),c1&&c1.p!=null&&(op1PickAtOp2Pick[slot2]=c1.p));const ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Pick)scanOp2Pick(r2Pick,ap1(key),removed1);ap1.end()},"scanOp2Pick")(r2,r1,null),__name(function scanOp2Drop(r1Pick,r2Pick,r2Drop,pickSlot1,removed1){const c2d=r2Drop.getComponent();let slot2,droppedHere=!1;c2d&&((slot2=c2d.d)!=null?(heldOp2DropByOp2[slot2]=r2Drop.clone(),pickSlot1!=null&&(op1PicksOp2DropSlots[pickSlot1]==null&&(op1PicksOp2DropSlots[pickSlot1]=[]),op1PicksOp2DropSlots[pickSlot1].push(slot2)),r1Pick=heldOp1PickByOp2[slot2]||null,r2Pick=heldOp2PickByOp2[slot2]||null,cancelledOp2[slot2]?(removed1&&(discardedOp2Drop[slot2]=!0),removed1=heldOp1RmForOp2[slot2]||null):!removed1||side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.moveOp(r2Pick.getPath(),r2Drop.getPath())}),droppedHere=!0):c2d.i!==void 0&&(r1Pick=r2Pick=null,droppedHere=!0,removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.insertOp(r2Drop.getPath(),c2d.i)})));const c1p=getComponent(r1Pick);c1p&&(c1p.r!==void 0?removed1=r1Pick.clone():c1p.p!=null&&(c1p.p,pickSlot1=c1p.p,removed1=null));const t2=getEditType(c2d);t2&&removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.editOp(r2Drop.getPath(),t2,getEdit(c2d),!0)});let p2PickOff=0,p2DropOff=0;const ap2=cursor_js_1.advancer(r2Pick,(k,c)=>hasPick(c)?p2PickOff-k-1:k-p2PickOff,(k,c)=>{hasPick(c)&&p2PickOff++}),ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Drop)if(typeof key=="number"){const p2Mid=key-p2DropOff,_p2Pick=ap2(p2Mid);p2DropOff+=+scanOp2Drop(ap1(p2Mid+p2PickOff),_p2Pick,r2Drop,pickSlot1,removed1)}else{const _p2Pick=ap2(key);scanOp2Drop(ap1(key),_p2Pick,r2Drop,pickSlot1,removed1)}return ap2.end(),ap1.end(),droppedHere},"scanOp2Drop")(r1,r2,r2.clone(),null,null),heldOp2DropByOp2.map(x=>x&&x.get()),conflict)return{ok:!1,conflict};discardedOp2Drop.map(x=>!!x);const pickComponents=[];let cancelledRemoves=null;__name(function writeOp1Pick(r1Pick,r2Pick,r2Drop,w2,removed2){let iAmMoved=!1;const c2p=getComponent(r2Pick);if(hasPick(c2p)){const slot2=c2p.p;slot2!=null?(r2Drop=heldOp2DropByOp2[slot2],w2=heldPickWrites[slot2]=cursor_js_1.writeCursor(),iAmMoved=!0,removed2=null):(r2Drop=null,removed2=r2Pick.clone())}else hasDrop(getComponent(r2Drop))&&(r2Drop=null);const c1=r1Pick.getComponent();if(c1){const slot1=c1.p;slot1!=null?(removed2&&(heldOp2RmForOp1[slot1]=removed2),pickComponents[slot1]=removed2||side===1&&iAmMoved?null:w2.getComponent(),heldOp1PickByOp1[slot1]=r1Pick.clone(),r2Drop&&(heldOp2DropByOp1[slot1]=r2Drop.clone())):c1.r!==void 0&&(removed2||w2.write("r",!0),(removed2||iAmMoved)&&(cancelledRemoves==null&&(cancelledRemoves=new Set),cancelledRemoves.add(c1)))}let p2PickOff=0,p2DropOff=0;const ap2Pick=cursor_js_1.advancer(r2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++}),ap2Drop=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?~(k-p2DropOff):k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++});if(r1Pick)for(const key of r1Pick)if(typeof key=="string"){const p2Pick_=ap2Pick(key),p2Drop_=ap2Drop(key);w2.descend(key),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}else{const p2Pick_=ap2Pick(key),p2Mid=key-p2PickOff,p2Drop_=hasPick(getComponent(p2Pick_))?null:ap2Drop(p2Mid),finalKey=p2Mid+p2DropOff;assert(finalKey>=0),w2.descend(finalKey),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}ap2Pick.end(),ap2Drop.end()},"writeOp1Pick")(r1,r2,r2.clone(),w,null),w.reset();let outputSlotMap=[];if(__name(function writeOp1Drop(p1Pick,p1Drop,p2Pick,p2Drop,w2,removed2){assert(p1Drop);const c1d=p1Drop.getComponent();let c2d=getComponent(p2Drop),droppedHere=!1;const insOrMv=__name((r12,r22,c)=>r12?exports2.moveOp(r12.getPath(),r22.getPath()):exports2.insertOp(r22.getPath(),c.i),"insOrMv");if(hasDrop(c1d)){const slot1=c1d.d;slot1!=null&&(heldOp1DropByOp1[slot1]=p1Drop.clone());const pc=slot1!=null?pickComponents[slot1]:null;let identical=!1;if(c1d.i!==void 0||slot1!=null&&pc){let slot2;c2d&&(c2d.i!==void 0||(slot2=c2d.d)!=null&&!cancelledOp2[slot2])&&(identical=slot2!=null?slot1!=null&&slot1===op1PickAtOp2Pick[slot2]:deepEqual_js_1.default(c2d.i,c1d.i),identical||slot2!=null&&side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.DROP_COLLISION,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:insOrMv(slot2!=null?heldOp2PickByOp2[slot2]:null,p2Drop,c2d)})),identical||(removed2?conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:exports2.removeOp(removed2.getPath())}):(slot1!=null?(outputSlotMap[nextSlot]=slot1,w2.write("d",pc.p=nextSlot++)):w2.write("i",deepClone_js_1.default(c1d.i)),droppedHere=!0))}else if(slot1!=null&&!pc){const h=heldOp2RmForOp1[slot1];h&&(removed2=h.clone())}slot1!=null?(p1Pick=heldOp1PickByOp1[slot1],p2Pick=heldOp2PickByOp1[slot1],p2Drop=heldOp2DropByOp1[slot1]):c1d.i!==void 0&&(p1Pick=p2Pick=null,identical||(p2Drop=null))}else hasPick(getComponent(p1Pick))&&(p1Pick=p2Pick=p2Drop=null);const c1p=getComponent(p1Pick),c2p=getComponent(p2Pick);if(hasPick(c2p)){const slot2=c2p.p;c2p.r!==void 0&&(!c1p||c1p.r===void 0)||cancelledOp2[slot2]?(p2Drop=null,removed2=p2Pick.clone()):slot2!=null&&(p2Drop=heldOp2DropByOp2[slot2],side!==1&&op1PickAtOp2Pick[slot2]!=null||((w2=heldDropWrites[slot2])||(w2=heldDropWrites[slot2]=cursor_js_1.writeCursor()),w2.reset(),removed2=null))}else!hasDrop(c1d)&&hasDrop(c2d)&&(p2Drop=null);c2d=p2Drop!=null?p2Drop.getComponent():null;const t1=getEditType(c1d);if(t1){const e1=getEdit(c1d);if(removed2)conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.editOp(p1Drop.getPath(),t1,e1,!0),op2:exports2.removeOp(removed2.getPath())});else{const t2=getEditType(c2d);let e;if(t2){if(t1!==t2)throw Error("Transforming incompatible types");const e2=getEdit(c2d);e=t1.transform(e1,e2,direction)}else e=deepClone_js_1.default(e1);writeEdit(w2,t1,e)}}let p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,outPickOff=0,outDropOff=0,p1pValid=p1Pick!=null&&p1Pick.descendFirst(),p1pDidDescend=p1pValid;const ap2p=cursor_js_1.advancer(p2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++});let p2dValid=p2Drop!=null&&p2Drop.descendFirst(),p2dDidDescend=p2dValid;for(const key of p1Drop)if(typeof key=="number"){let _p1Pick;const hd1=hasDrop(p1Drop.getComponent()),k1Mid=key-p1DropOff;{let p1k;for(;p1pValid&&typeof(p1k=p1Pick.getKey())=="number";){p1k+=p1PickOff;const c=p1Pick.getComponent(),hp=hasPick(c);if(p1k>k1Mid||p1k===k1Mid&&(!hp||side===0&&hd1))break;if(hp){p1PickOff--;const slot1=c.p;op1PickAtOp2Pick.includes(slot1),c.d,getComponent(heldDropWrites[c.d]),hasPick(getComponent(heldDropWrites[c.d])),(c.r===void 0||cancelledRemoves&&cancelledRemoves.has(c))&&(slot1==null||!pickComponents[slot1]||side!==1&&op1PickAtOp2Pick.includes(slot1))||outPickOff--}p1pValid=p1Pick.nextSibling()}_p1Pick=p1pValid&&p1k===k1Mid?p1Pick:null}const raw=k1Mid-p1PickOff;let _p2Pick=ap2p(raw);const k2Mid=raw-p2PickOff;let _p2Drop=null;{let p2dk,op2Mid;for(;p2dValid&&typeof(p2dk=p2Drop.getKey())=="number";){op2Mid=p2dk-p2DropOff;const c=p2Drop.getComponent(),hd2=hasDrop(c);if(op2Mid>k2Mid)break;if(op2Mid===k2Mid){if(!hd2){_p2Drop=p2Drop;break}{if(side===0&&hd1){_p2Drop=p2Drop;break}const hp2=_p2Pick&&hasPick(_p2Pick.getComponent());if(side===0&&hp2)break}}if(hd2){const slot2=c.d;op1PickAtOp2Pick[slot2],c.i===void 0&&(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side!==1)?(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side===0)&&(p2DropOff++,outDropOff--):p2DropOff++}p2dValid=p2Drop.nextSibling()}}const descend=k2Mid+p2DropOff+outPickOff+outDropOff;assert(descend>=0,"trying to descend to a negative index"),w2.descend(descend),hd1&&(_p1Pick=_p2Pick=_p2Drop=null,p1DropOff++),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2)&&outDropOff++,w2.ascend()}else{let p1k;for(;p1pValid&&(p1k=p1Pick.getKey(),typeof p1k!="string"||!(p1k>key||p1k===key));)p1pValid=p1Pick.nextSibling();const _p1Pick=p1pValid&&p1k===key?p1Pick:null,_p2Pick=ap2p(key);let p2dk;for(;p2dValid&&(p2dk=p2Drop.getKey(),typeof p2dk!="string"||!(p2dk>key||p2dk===key));)p2dValid=p2Drop.nextSibling();const _p2Drop=p2dValid&&p2dk===key?p2Drop:null;w2.descend(key),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2),w2.ascend()}return ap2p.end(),p1pDidDescend&&p1Pick.ascend(),p2dDidDescend&&p2Drop.ascend(),droppedHere},"writeOp1Drop")(r1,r1.clone(),r2,r2.clone(),w,null),conflict)return{ok:!1,conflict};w.reset();const eachDrop=__name((r,w2,fn)=>r.traverse(w2,(c,w3)=>{c.d!=null&&fn(c.d,r,w3)}),"eachDrop");(cancelledOp2.length||heldPickWrites.length)&&(eachDrop(r2,w,(slot2,r,w2)=>{cancelledOp2[slot2]&&!discardedOp2Drop[slot2]&&w2.write("r",!0),heldPickWrites[slot2]&&w2.mergeTree(heldPickWrites[slot2].get())}),w.reset());const heldOutDropRead=[],heldOutDropWrites=[];if((heldDropWrites.length||cancelledOp2.length)&&!conflict){const rOut=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut,null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()}),heldDropWrites.forEach(hdw=>{hdw&&eachDrop(cursor_js_1.readCursor(hdw.get()),null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()})}),__name(function writeHeldOp2Drop(p2Drop,outPick,outDrop,w2,parentC,removedOut){const coutp=getComponent(outPick);if(coutp&&hasPick(coutp))if(coutp.p!=null){const slot=coutp.p;heldOutDropRead[slot].getPath(),outDrop=heldOutDropRead[slot],w2=heldOutDropWrites[slot]=cursor_js_1.writeCursor()}else coutp.r!==void 0&&(outDrop=null);else hasDrop(getComponent(outDrop))&&(outDrop=null);const c2=p2Drop.getComponent();if(c2){let slot2;if((slot2=c2.d)!=null){const _w=heldDropWrites[slot2];_w&&(_w.get(),w2.mergeTree(_w.get()),outDrop=cursor_js_1.readCursor(_w.get()))}}let outPickOff=0,outDropOff=0;const oPickAdv=cursor_js_1.advancer(outPick,void 0,(k,c)=>{hasPick(c)&&outPickOff--}),oDropAdv=cursor_js_1.advancer(outDrop,(k,c)=>hasDrop(c)?-(k-outDropOff)-1:k-outDropOff,(k,c)=>{hasDrop(c)&&outDropOff++});for(const o2dk of p2Drop)if(typeof o2dk=="number"){const _outPick=oPickAdv(o2dk),rmid=o2dk+outPickOff,_outDrop=oDropAdv(rmid),rfinal=rmid+outDropOff;w2.descend(rfinal),writeHeldOp2Drop(p2Drop,_outPick,_outDrop,w2),w2.ascend()}else w2.descend(o2dk),writeHeldOp2Drop(p2Drop,oPickAdv(o2dk),oDropAdv(o2dk),w2),w2.ascend();oPickAdv.end(),oDropAdv.end()},"writeHeldOp2Drop")(r2,rOut,rOut.clone(),w),w.reset(),conflict)return{ok:!1,conflict};if(w.get(),heldOutDropWrites.length){const heldOutDropContent=heldOutDropWrites.map(w2=>w2?w2.get():null),rOut2=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut2,w,(slotOut,r,w2)=>{const data=heldOutDropContent[slotOut];data&&(w2.mergeTree(data),heldOutDropContent[slotOut]=null)}),heldOutDropContent.find(x=>x)){const w1=cursor_js_1.writeCursor(),w2=cursor_js_1.writeCursor();let nextSlot1=0,nextSlot2=0;heldOutDropContent.forEach(data=>{data!=null&&eachDrop(cursor_js_1.readCursor(data),null,c=>{const slot1=outputSlotMap[c];w1.writeMove(heldOp1PickByOp1[slot1].getPath(),heldOp1DropByOp1[slot1].getPath(),nextSlot1++);const slot2s=op1PicksOp2DropSlots[slot1];slot2s&&slot2s.forEach(slot2=>{cancelledOp2[slot2]||side!==1&&op1PickAtOp2Pick[slot2]!=null||w2.writeMove(heldOp2PickByOp2[slot2].getPath(),heldOp2DropByOp2[slot2].getPath(),nextSlot2++)})})}),conflict={type:types_js_1.ConflictType.BLACKHOLE,op1:w1.get(),op2:w2.get()}}}}return conflict?{ok:!1,conflict}:{ok:!0,result:w.get()}}__name(tryTransform,"tryTransform");const throwConflictErr=__name(conflict=>{const err=new Error("Transform detected write conflict");throw err.conflict=conflict,err.type=err.name="writeConflict",err},"throwConflictErr");function transform(op1,op2,side){const res=tryTransform(op1,op2,side);if(res.ok)return res.result;throwConflictErr(res.conflict)}__name(transform,"transform");const opThatRemovesDE=__name(op=>{const w=cursor_js_1.writeCursor();return cursor_js_1.readCursor(op).traverse(w,(c,w2)=>{(hasDrop(c)||getEditType(c))&&w2.write("r",!0)}),w.get()},"opThatRemovesDE"),resolveConflict=__name((conflict,side)=>{const{type:type2,op1,op2}=conflict;switch(type2){case types_js_1.ConflictType.DROP_COLLISION:return side==="left"?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.RM_UNEXPECTED_CONTENT:let op1HasRemove=!1;return cursor_js_1.readCursor(op1).traverse(null,c=>{c.r!==void 0&&(op1HasRemove=!0)}),op1HasRemove?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.BLACKHOLE:return[opThatRemovesDE(op1),opThatRemovesDE(op2)];default:throw Error("Unrecognised conflict: "+type2)}},"resolveConflict");function transformWithConflictsPred(allowConflict,op1,op2,side){let r2Aggregate=null;for(;;){const res=tryTransform(op1,op2,side);if(res.ok)return compose(r2Aggregate,res.result);{const{conflict}=res;allowConflict(conflict)||throwConflictErr(conflict);const[r1,r2]=resolveConflict(conflict,side);op1=compose(normalize(op1),r1),op2=compose(normalize(op2),r2),r2Aggregate=compose(r2Aggregate,r2)}}}__name(transformWithConflictsPred,"transformWithConflictsPred")})(json1_release);(function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__exportStar=commonjsGlobal&&commonjsGlobal.__exportStar||function(m,exports3){for(var p in m)p!=="default"&&!exports3.hasOwnProperty(p)&&__createBinding(exports3,m,p)};Object.defineProperty(exports2,"__esModule",{value:!0}),__exportStar(json1_release,exports2);var cursor_js_1=cursor;Object.defineProperty(exports2,"ReadCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.ReadCursor},"get")}),Object.defineProperty(exports2,"WriteCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.WriteCursor},"get")});var types_1=types;Object.defineProperty(exports2,"ConflictType",{enumerable:!0,get:__name(function(){return types_1.ConflictType},"get")})})(dist$1);const index=getDefaultExportFromCjs(dist$1),index$1=_mergeNamespaces({__proto__:null,default:index},[dist$1]);var TextXActionType=(TextXActionType2=>(TextXActionType2.RETAIN="r",TextXActionType2.INSERT="i",TextXActionType2.DELETE="d",TextXActionType2))(TextXActionType||{});const _ActionIterator=class _ActionIterator{constructor(_actions){__publicField(this,"_index",0);__publicField(this,"_offset",0);this._actions=_actions}hasNext(){return this.peekLength()<Number.POSITIVE_INFINITY}next(length){length||(length=Number.POSITIVE_INFINITY);const nextAction=this._actions[this._index];if(nextAction){const offset=this._offset,actionLength=nextAction.len;return length>=actionLength-offset?(length=actionLength-offset,this._index+=1,this._offset=0):this._offset+=length,nextAction.t===TextXActionType.DELETE||nextAction.t===TextXActionType.RETAIN&&nextAction.body==null?Tools.deepClone({...nextAction,len:length}):Tools.deepClone({...nextAction,len:length,body:getBodySlice(nextAction.body,offset,offset+length)})}else return{t:TextXActionType.RETAIN,len:Number.POSITIVE_INFINITY}}peek(){return this._actions[this._index]}peekLength(){return this._actions[this._index]?this._actions[this._index].len-this._offset:Number.POSITIVE_INFINITY}peekType(){const action=this._actions[this._index];return action?action.t:TextXActionType.RETAIN}rest(){if(this.hasNext()){if(this._offset===0)return this._actions.slice(this._index);{const offset=this._offset,index2=this._index,next=this.next(),restActions=this._actions.slice(this._index);return this._offset=offset,this._index=index2,[next].concat(restActions)}}else return[]}};__name(_ActionIterator,"ActionIterator");let ActionIterator=_ActionIterator;const _MemoryCursor=class _MemoryCursor{constructor(){__publicField(this,"cursor",0)}reset(){return this.cursor=0,this}moveCursor(pos){this.cursor+=pos}moveCursorTo(pos){this.cursor=pos}};__name(_MemoryCursor,"MemoryCursor");let MemoryCursor=_MemoryCursor;function updateAttributeByDelete(body,textLength,currentIndex){const{dataStream}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeTextRuns=deleteTextRuns(body,textLength,currentIndex),removeParagraphs=deleteParagraphs(body,textLength,currentIndex),removeSectionBreaks=deleteSectionBreaks(body,textLength,currentIndex),removeCustomBlocks=deleteCustomBlocks(body,textLength,currentIndex),removeTables=deleteTables(body,textLength,currentIndex),removeCustomRanges=deleteCustomRanges(body,textLength,currentIndex),removeCustomDecorations=deleteCustomDecorations(body,textLength,currentIndex);let removeDataStream="";return dataStream&&(body.dataStream=deleteContent(dataStream,startIndex,endIndex),removeDataStream=dataStream.slice(startIndex,endIndex)),{dataStream:removeDataStream,textRuns:removeTextRuns,paragraphs:removeParagraphs,sectionBreaks:removeSectionBreaks,customBlocks:removeCustomBlocks,tables:removeTables,customRanges:removeCustomRanges,customDecorations:removeCustomDecorations}}__name(updateAttributeByDelete,"updateAttributeByDelete");function updateAttributeByInsert(body,insertBody,textLength,currentIndex){body.dataStream=insertTextToContent(body.dataStream,currentIndex,insertBody.dataStream),insertTextRuns(body,insertBody,textLength,currentIndex),insertParagraphs(body,insertBody,textLength,currentIndex),insertSectionBreaks(body,insertBody,textLength,currentIndex),insertCustomBlocks(body,insertBody,textLength,currentIndex),insertTables(body,insertBody,textLength,currentIndex),insertCustomRanges(body,insertBody,textLength,currentIndex),insertCustomDecorations(body,insertBody,textLength,currentIndex)}__name(updateAttributeByInsert,"updateAttributeByInsert");function updateApply(doc,updateBody,textLength,currentIndex,coverType=UpdateDocsAttributeType.COVER){return updateAttribute(doc,updateBody,textLength,currentIndex,coverType)}__name(updateApply,"updateApply");function deleteApply(doc,textLength,currentIndex){return textLength<=0?{dataStream:""}:updateAttributeByDelete(doc,textLength,currentIndex)}__name(deleteApply,"deleteApply");function insertApply(doc,insertBody,textLength,currentIndex){textLength!==0&&updateAttributeByInsert(doc,insertBody,textLength,currentIndex)}__name(insertApply,"insertApply");function textXApply(doc,actions){const memoryCursor=new MemoryCursor;return memoryCursor.reset(),actions.forEach(action=>{switch(action=Tools.deepClone(action),action.t){case TextXActionType.RETAIN:{const{coverType,body,len}=action;body!=null&&updateApply(doc,body,len,memoryCursor.cursor,coverType),memoryCursor.moveCursor(len);break}case TextXActionType.INSERT:{const{body,len}=action;insertApply(doc,body,len,memoryCursor.cursor),memoryCursor.moveCursor(len);break}case TextXActionType.DELETE:{const{len}=action;deleteApply(doc,len,memoryCursor.cursor);break}default:throw new Error(`Unknown action type for action: ${action}.`)}}),doc}__name(textXApply,"textXApply");function onlyHasDataStream(body){return Object.keys(body).length===1}__name(onlyHasDataStream,"onlyHasDataStream");const _TextX=class _TextX{constructor(){__publicField(this,"_actions",[])}static apply(doc,actions){return textXApply(doc,actions)}static compose(thisActions,otherActions){const thisIter=new ActionIterator(thisActions),otherIter=new ActionIterator(otherActions),textX=new _TextX;for(;thisIter.hasNext()||otherIter.hasNext();)if(otherIter.peekType()===TextXActionType.INSERT)textX.push(otherIter.next());else if(thisIter.peekType()===TextXActionType.DELETE)textX.push(thisIter.next());else{const length=Math.min(thisIter.peekLength(),otherIter.peekLength()),thisAction=thisIter.next(length),otherAction=otherIter.next(length);thisAction.t===TextXActionType.INSERT&&otherAction.t===TextXActionType.RETAIN?otherAction.body==null?textX.push(thisAction):textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.RETAIN?thisAction.body==null&&otherAction.body==null?textX.push(thisAction.len!==Number.POSITIVE_INFINITY?thisAction:otherAction):thisAction.body&&otherAction.body?textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):textX.push(thisAction.body?thisAction:otherAction):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.DELETE?textX.push(otherAction):thisAction.t===TextXActionType.INSERT&&(otherAction.t,TextXActionType.DELETE)}return textX.trimEndUselessRetainAction(),textX.serialize()}static transform(_thisActions,_otherActions,_priority){throw new Error("transform is not implemented in TextX")}static isNoop(actions){return actions.length===0}static invert(actions){const invertedActions=[];for(const action of actions)if(action.t===TextXActionType.INSERT)invertedActions.push({t:TextXActionType.DELETE,len:action.len,line:0,body:action.body,segmentId:action.segmentId});else if(action.t===TextXActionType.DELETE){if(action.body==null)throw new Error("Can not invert DELETE action without body property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.INSERT,body:action.body,len:action.len,line:0,segmentId:action.segmentId})}else if(action.body!=null){if(action.oldBody==null)throw new Error("Can not invert RETAIN action without oldBody property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.RETAIN,body:action.oldBody,oldBody:action.body,len:action.len,coverType:UpdateDocsAttributeType.REPLACE,segmentId:action.segmentId})}else invertedActions.push(action);return invertedActions}static makeInvertible(actions,doc){const invertibleActions=[];let index2=0;for(const action of actions){if(action.t===TextXActionType.DELETE&&action.body==null){const body=getBodySlice(doc,index2,index2+action.len,!1);action.len=body.dataStream.length,action.body=body}if(action.t===TextXActionType.RETAIN&&action.body!=null){const body=getBodySlice(doc,index2,index2+action.len,!0);action.oldBody={...body,dataStream:""},action.len=body.dataStream.length}invertibleActions.push(action),action.t!==TextXActionType.INSERT&&(index2+=action.len)}return invertibleActions}insert(len,body,segmentId=""){const insertAction={t:TextXActionType.INSERT,body,len,line:0,segmentId};return this.push(insertAction),this}retain(len,segmentId="",body,coverType){const retainAction={t:TextXActionType.RETAIN,len,segmentId};return body!=null&&(retainAction.body=body),coverType!=null&&(retainAction.coverType=coverType),this.push(retainAction),this}delete(len,segmentId=""){const deleteAction={t:TextXActionType.DELETE,len,line:0,segmentId};return this.push(deleteAction),this}empty(){return this._actions=[],this}serialize(){return this._actions}push(...args){if(args.length>1){for(const ac of args)this.push(ac);return this}let index2=this._actions.length,lastAction=this._actions[index2-1];const newAction=Tools.deepClone(args[0]);if(newAction.t===TextXActionType.RETAIN&&newAction.len===0&&newAction.body==null)return this;if(typeof lastAction=="object"){if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.DELETE)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.INSERT&&(index2-=1,lastAction=this._actions[index2-1],lastAction==null))return this._actions.unshift(newAction),this;if(lastAction.t===TextXActionType.RETAIN&&newAction.t===TextXActionType.RETAIN&&lastAction.body==null&&newAction.body==null)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.INSERT&&onlyHasDataStream(lastAction.body)&&newAction.t===TextXActionType.INSERT&&onlyHasDataStream(newAction.body))return lastAction.len+=newAction.len,lastAction.body.dataStream+=newAction.body.dataStream,this}return index2===this._actions.length?this._actions.push(newAction):this._actions.splice(index2,0,newAction),this}trimEndUselessRetainAction(){let lastAction=this._actions[this._actions.length-1];for(;lastAction&&lastAction.t===TextXActionType.RETAIN&&isUselessRetainAction(lastAction);)this._actions.pop(),lastAction=this._actions[this._actions.length-1];return this}};__name(_TextX,"TextX"),__publicField(_TextX,"id","text-x"),__publicField(_TextX,"uri","https://github.com/dream-num/univer#text-x");let TextX=_TextX;Object.defineProperty(TextX,"name",{value:"text-x"});const _JSONX=class _JSONX{static registerSubtype(subType){var _a13;this._subTypes.has(subType.name)&&((_a13=this._subTypes.get(subType.name))==null?void 0:_a13.id)!==TextX.id||(this._subTypes.set(subType.name,subType),dist$1.type.registerSubtype(subType))}static apply(doc,actions){if(!dist$1.type.isNoop(actions))return dist$1.type.apply(doc,actions)}static compose(thisActions,otherActions){return dist$1.type.compose(thisActions,otherActions)}static transform(_thisActions,_otherActions,_priority){throw new Error("transform is not implemented in JsonX")}static invertWithDoc(actions,doc){return dist$1.type.invertWithDoc(actions,doc)}static isNoop(actions){return dist$1.type.isNoop(actions)}static getInstance(){return this._instance==null&&(this._instance=new _JSONX),this._instance}removeOp(path,value){return dist$1.removeOp(path,value)}moveOp(from,to){return dist$1.moveOp(from,to)}insertOp(path,value){return dist$1.insertOp(path,value)}replaceOp(path,oldVal,newVal){return dist$1.replaceOp(path,oldVal,newVal)}editOp(subOp,path=["body"]){return dist$1.editOp(path,TextX.name,subOp)}};__name(_JSONX,"JSONX"),__publicField(_JSONX,"uri","https://github.com/dream-num/univer#json-x"),__publicField(_JSONX,"_subTypes",new Map),__publicField(_JSONX,"_instance",null);let JSONX=_JSONX;JSONX.registerSubtype(TextX);const DEFAULT_DOC={id:"default_doc",documentStyle:{}},_DocumentDataModelSimple=class _DocumentDataModelSimple extends UnitModel{constructor(snapshot){super();__publicField(this,"type",I.UNIVER_DOC);__publicField(this,"snapshot");this.snapshot={...DEFAULT_DOC,...snapshot}}getUnitId(){throw new Error("Method not implemented.")}get drawings(){return this.snapshot.drawings}get documentStyle(){return this.snapshot.documentStyle}get lists(){return this.snapshot.lists}get zoomRatio(){var _a13;return((_a13=this.snapshot.settings)==null?void 0:_a13.zoomRatio)||1}resetDrawing(drawings,drawingsOrder){this.snapshot.drawings=drawings,this.snapshot.drawingsOrder=drawingsOrder}getBody(){return this.snapshot.body}getShouldRenderLoopImmediately(){return this.snapshot.shouldStartRenderingImmediately!==!1}getContainer(){return this.snapshot.container}getSnapshot(){return this.snapshot}updateDocumentId(unitId){this.snapshot.id=unitId}updateDocumentRenderConfig(config){const{documentStyle}=this.snapshot;documentStyle.renderConfig==null?documentStyle.renderConfig=config:documentStyle.renderConfig={...documentStyle.renderConfig,...config}}updateDocumentStyle(config){this.snapshot.documentStyle==null?this.snapshot.documentStyle=config:this.snapshot.documentStyle={...this.snapshot.documentStyle,...config}}updateDocumentDataMargin(data){const{t,l:l2,b,r}=data,{documentStyle}=this.snapshot;t!=null&&(documentStyle.marginTop=t),l2!=null&&(documentStyle.marginLeft=l2),b!=null&&(documentStyle.marginBottom=b),r!=null&&(documentStyle.marginRight=r)}updateDocumentDataPageSize(width,height){const{documentStyle}=this.snapshot;if(!documentStyle.pageSize){width=width!=null?width:Number.POSITIVE_INFINITY,height=height!=null?height:Number.POSITIVE_INFINITY,documentStyle.pageSize={width,height};return}width!==void 0&&(documentStyle.pageSize.width=width),height!==void 0&&(documentStyle.pageSize.height=height)}updateDrawing(id,config){const{drawings}=this,{width,height,left,top}=config,drawing=drawings==null?void 0:drawings[id];if(!drawing)return;const objectTransform=drawing.docTransform;objectTransform.size.width=width,objectTransform.size.height=height,objectTransform.positionH.posOffset=left,objectTransform.positionV.posOffset=top}setZoomRatio(zoomRatio=1){this.snapshot.settings==null?this.snapshot.settings={zoomRatio}:this.snapshot.settings.zoomRatio=1}};__name(_DocumentDataModelSimple,"DocumentDataModelSimple");let DocumentDataModelSimple=_DocumentDataModelSimple;const _DocumentDataModel=class _DocumentDataModel extends DocumentDataModelSimple{constructor(snapshot){var _a13,_b2;super(Tools.isEmptyObject(snapshot)?getEmptySnapshot$1():snapshot);__publicField(this,"_unitId");__publicField(this,"headerModelMap",new Map);__publicField(this,"footerModelMap",new Map);__publicField(this,"_name$",new rxjs.BehaviorSubject(""));__publicField(this,"name$",this._name$.asObservable());const UNIT_ID_LENGTH=6;this._unitId=(_a13=this.snapshot.id)!=null?_a13:Tools.generateRandomId(UNIT_ID_LENGTH),this._initializeHeaderFooterModel(),this._name$.next((_b2=this.snapshot.title)!=null?_b2:"")}setName(name){this.snapshot.title=name,this._name$.next(name)}dispose(){super.dispose(),this.headerModelMap.forEach(header=>{header.dispose()}),this.footerModelMap.forEach(footer=>{footer.dispose()}),this._name$.complete()}getDrawings(){return this.snapshot.drawings}getDrawingsOrder(){return this.snapshot.drawingsOrder}getCustomRanges(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customRanges}getCustomDecorations(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customDecorations}getRev(){var _a13;return(_a13=this.snapshot.rev)!=null?_a13:1}incrementRev(){this.snapshot.rev=this.getRev()+1}getSettings(){return this.snapshot.settings}reset(snapshot){if(snapshot.id&&snapshot.id!==this._unitId)throw new Error("Cannot reset a document model with a different unit id!");this.snapshot={...DEFAULT_DOC,...snapshot},this._initializeHeaderFooterModel()}getSelfOrHeaderFooterModel(segmentId){if(segmentId!=null){if(this.headerModelMap.has(segmentId))return this.headerModelMap.get(segmentId);if(this.footerModelMap.has(segmentId))return this.footerModelMap.get(segmentId)}return this}getUnitId(){return this._unitId}apply(actions){if(!JSONX.isNoop(actions))return this.snapshot=JSONX.apply(this.snapshot,actions),actions!=null&&actions.some(a=>Array.isArray(a)&&((a==null?void 0:a[0])==="headers"||(a==null?void 0:a[0])==="footers"))&&(this.headerModelMap.clear(),this.footerModelMap.clear(),this._initializeHeaderFooterModel()),this.snapshot}sliceBody(startOffset,endOffset,type2=SliceBodyType.copy){const body=this.getBody();if(body!=null)return getBodySlice(body,startOffset,endOffset,!1,type2)}_initializeHeaderFooterModel(){const{headers,footers}=this.getSnapshot();if(headers)for(const headerId in headers){const header=headers[headerId];this.headerModelMap.set(headerId,new _DocumentDataModel(header))}if(footers)for(const footerId in footers){const footer=footers[footerId];this.footerModelMap.set(footerId,new _DocumentDataModel(footer))}}updateDocumentId(unitId){super.updateDocumentId(unitId),this._unitId=unitId}};__name(_DocumentDataModel,"DocumentDataModel");let DocumentDataModel=_DocumentDataModel;const IConfigService=createIdentifier("univer.config-service"),_ConfigService=class _ConfigService{constructor(){__publicField(this,"_config",new Map)}getConfig(id){return this._config.get(id)}setConfig(id,value){this._config.set(id,value)}deleteConfig(id){this._config.delete(id)}};__name(_ConfigService,"ConfigService");let ConfigService=_ConfigService;const _ErrorService=class _ErrorService extends Disposable{constructor(){super(...arguments);__publicField(this,"_error$",new rxjs.Subject);__publicField(this,"error$",this._error$.asObservable())}dispose(){this._error$.complete()}emit(key){this._error$.next({errorKey:key})}};__name(_ErrorService,"ErrorService");let ErrorService=_ErrorService;const _Styles=class _Styles{constructor(styles={}){__publicField(this,"_styles");__publicField(this,"_cacheMap",new LRUMap(1e5));this._styles=styles,this._generateCacheMap()}each(callback){return Object.entries(this._styles).forEach(callback),this}search(data,styleObject){if(this._cacheMap.has(styleObject))return this._cacheMap.get(styleObject);const existingId=this._getExistingStyleId(data);return existingId||"-1"}get(id){return typeof id!="string"?id:(id=String(id),this._styles[id])}add(data,styleObject){const id=Tools.generateRandomId(6);return this._styles[id]=data,this._cacheMap.set(styleObject,id),id}setValue(data){if(data==null)return;const styleObject=JSON.stringify(data),result=this.search(data,styleObject);return result!=="-1"?result:this.add(data,styleObject)}toJSON(){return this._styles}getStyleByCell(cell){let style;cell&&Tools.isObject(cell.s)?style=cell.s:style=(cell==null?void 0:cell.s)&&this.get(cell.s);const interceptStyle=cell==null?void 0:cell.interceptorStyle;return interceptStyle?{...style,...interceptStyle}:style}_generateCacheMap(){const{_styles,_cacheMap}=this;for(const id in _styles){const styleObject=JSON.stringify(_styles[id]);_cacheMap.set(styleObject,id)}}_getExistingStyleId(data){const{_styles}=this;for(const id in _styles)if(Tools.diffValue(_styles[id],data))return id;return null}};__name(_Styles,"Styles");let Styles=_Styles;const _ColumnManager=class _ColumnManager{constructor(_config,data){__publicField(this,"_columnData",{});this._config=_config,this._columnData=data}getColumnData(){return this._columnData}getColVisible(colPos){const{_columnData}=this,col=_columnData[colPos];return col?col.hd!==BooleanNumber.TRUE:!0}getHiddenCols(start=0,end=this.getSize()-1){const hiddenCols=[];let inHiddenRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startColumn=i)}return inHiddenRange&&hiddenCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),hiddenCols}getVisibleCols(start=0,end=this.getSize()-1){const visibleCols=[];let inVisibleRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inVisibleRange&&visible&&(inVisibleRange=!0,startColumn=i)}return inVisibleRange&&visibleCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),visibleCols}getColumnDatas(columnPos,numColumns){const columnData={};let index2=0;for(let i=columnPos;i<columnPos+numColumns;i++){const data=this.getColumnOrCreate(i);columnData[index2]=data,index2++}return columnData}getSize(){return getArrayLength(this._columnData)}getColumnWidth(columnPos){const{_columnData}=this,config=this._config;let width=0;return width=(_columnData[columnPos]||{hd:BooleanNumber.FALSE,w:config.defaultColumnWidth}).w||config.defaultColumnWidth,width}getColumn(columnPos){const column=this._columnData[columnPos];if(column)return column}getColumnOrCreate(columnPos){const{_columnData}=this,config=this._config,column=_columnData[columnPos];if(column)return column;const create={w:config.defaultColumnWidth,hd:BooleanNumber.FALSE};return this._columnData[columnPos]=create,create}};__name(_ColumnManager,"ColumnManager");let ColumnManager=_ColumnManager;const _RowManager=class _RowManager{constructor(_config,_viewModel,data){__publicField(this,"_rowData");this._config=_config,this._viewModel=_viewModel,this._rowData=data}getRowData(){return this._rowData}getRowDatas(rowPos,numRows){const rowData={};let index2=0;for(let i=rowPos;i<rowPos+numRows;i++){const data=this.getRowOrCreate(i);rowData[index2]=data,index2++}return rowData}getRowHeight(rowPos,count=1){const{_rowData}=this,config=this._config;let height=0;for(let i=0;i<count;i++){const row=_rowData[i+rowPos]||{hd:BooleanNumber.FALSE,h:config.defaultRowHeight},{ia,ah,h=config.defaultRowHeight}=row;height+=(ia==null||ia===BooleanNumber.TRUE)&&typeof ah=="number"?ah:h}return height}getRow(rowPos){return this._rowData[rowPos]}getRowOrCreate(rowPos){const{_rowData}=this,row=_rowData[rowPos];if(row)return row;const config=this._config,create={hd:BooleanNumber.FALSE,h:config.defaultRowHeight};return _rowData[rowPos]=create,create}getHiddenRows(start=0,end=this.getSize()-1){const hiddenRows=[];let inHiddenRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startRow=i)}return inHiddenRange&&hiddenRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),hiddenRows}getVisibleRows(start=0,end=this.getSize()-1){const visibleRows=[];let inVisibleRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inVisibleRange&&visible&&(inVisibleRange=!0,startRow=i)}return inVisibleRange&&visibleRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),visibleRows}getRowRawVisible(row){const rowData=this.getRow(row);return rowData?rowData.hd!==BooleanNumber.TRUE:!0}getSize(){return getArrayLength(this._rowData)}};__name(_RowManager,"RowManager");let RowManager=_RowManager;const DEFAULT_WORKSHEET_ROW_COUNT_KEY="DEFAULT_WORKSHEET_ROW_COUNT",DEFAULT_WORKSHEET_ROW_COUNT=1e3,DEFAULT_WORKSHEET_COLUMN_COUNT_KEY="DEFAULT_WORKSHEET_COLUMN_COUNT",DEFAULT_WORKSHEET_COLUMN_COUNT=20,DEFAULT_WORKSHEET_ROW_HEIGHT_KEY="DEFAULT_WORKSHEET_ROW_HEIGHT",DEFAULT_WORKSHEET_ROW_HEIGHT=24,DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY="DEFAULT_WORKSHEET_COLUMN_WIDTH",DEFAULT_WORKSHEET_COLUMN_WIDTH=88,DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY="DEFAULT_WORKSHEET_ROW_TITLE_WIDTH",DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=46,DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY="DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT",DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=20;function mergeWorksheetSnapshotWithDefault(snapshot){const defaultSnapshot={name:"Sheet1",id:"sheet-01",tabColor:"",hidden:BooleanNumber.FALSE,rowCount:DEFAULT_WORKSHEET_ROW_COUNT,columnCount:DEFAULT_WORKSHEET_COLUMN_COUNT,zoomRatio:1,freeze:{xSplit:0,ySplit:0,startRow:-1,startColumn:-1},scrollTop:0,scrollLeft:0,defaultColumnWidth:DEFAULT_WORKSHEET_COLUMN_WIDTH,defaultRowHeight:DEFAULT_WORKSHEET_ROW_HEIGHT,mergeData:[],cellData:{},rowData:{},columnData:{},showGridlines:BooleanNumber.TRUE,rowHeader:{width:DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,hidden:BooleanNumber.FALSE},columnHeader:{height:DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,hidden:BooleanNumber.FALSE},selections:["A1"],rightToLeft:BooleanNumber.FALSE};return Object.keys(defaultSnapshot).forEach(_key=>{const key=_key;typeof snapshot[key]>"u"&&(snapshot[key]=defaultSnapshot[key])}),snapshot}__name(mergeWorksheetSnapshotWithDefault,"mergeWorksheetSnapshotWithDefault");const _SheetViewModel=class _SheetViewModel extends Disposable{constructor(getRawCell){super();__publicField(this,"_cellContentInterceptor",null);__publicField(this,"_rowFilteredInterceptor",null);this.getRawCell=getRawCell}dispose(){super.dispose(),this._cellContentInterceptor=null,this._rowFilteredInterceptor=null}getCell(row,col){return this._cellContentInterceptor?this._cellContentInterceptor.getCell(row,col):this.getRawCell(row,col)}getRowFiltered(row){var _a13,_b2;return(_b2=(_a13=this._rowFilteredInterceptor)==null?void 0:_a13.getRowFiltered(row))!=null?_b2:!1}registerCellContentInterceptor(interceptor){if(this._cellContentInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._cellContentInterceptor=interceptor,toDisposable(()=>this._cellContentInterceptor=null)}registerRowFilteredInterceptor(interceptor){if(this._rowFilteredInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._rowFilteredInterceptor=interceptor,toDisposable(()=>this._rowFilteredInterceptor=null)}};__name(_SheetViewModel,"SheetViewModel");let SheetViewModel=_SheetViewModel;const _Worksheet=class _Worksheet{constructor(unitId,snapshot,_styles){__publicField(this,"_sheetId");__publicField(this,"_snapshot");__publicField(this,"_cellData");__publicField(this,"_rowManager");__publicField(this,"_columnManager");__publicField(this,"_viewModel");var _a13;this.unitId=unitId,this._styles=_styles,this._snapshot=mergeWorksheetSnapshotWithDefault(snapshot);const{columnData,rowData,cellData}=this._snapshot;this._sheetId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6),this._cellData=new ObjectMatrix(cellData),this._viewModel=new SheetViewModel((row,col)=>this.getCellRaw(row,col)),this._rowManager=new RowManager(this._snapshot,this._viewModel,rowData),this._columnManager=new ColumnManager(this._snapshot,columnData)}__interceptViewModel(callback){callback(this._viewModel)}getSnapshot(){return this._snapshot}getCellMatrix(){return this._cellData}getCellMatrixPrintRange(){const matrix=this.getCellMatrix(),mergedCells=this.getMergeData();let startRow=-1,endRow=-1,startColumn=-1,endColumn=-1,rowInitd=!1,columnInitd=!1;return matrix.forEach((rowIndex,row)=>{Object.keys(row).forEach(colIndexStr=>{const colIndex=+colIndexStr,cellValue=matrix.getValue(rowIndex,colIndex),style=cellValue!=null&&cellValue.s?this._styles.get(cellValue.s):null,isLegalBorder=(style==null?void 0:style.bd)&&(style.bd.b||style.bd.l||style.bd.r||style.bd.t||style.bd.bc_tr||style.bd.bl_tr||style.bd.ml_tr||style.bd.tl_bc||style.bd.tl_br||style.bd.tl_mr);(cellValue&&(cellValue.v||cellValue.p)||style!=null&&style.bg||isLegalBorder)&&(rowInitd?startRow=Math.min(startRow,rowIndex):(startRow=rowIndex,rowInitd=!0),endRow=Math.max(endRow,rowIndex),columnInitd?startColumn=Math.min(startColumn,colIndex):(columnInitd=!0,startColumn=colIndex),endColumn=Math.max(endColumn,colIndex))})}),mergedCells.forEach(mergedCell=>{rowInitd?startRow=Math.min(startRow,mergedCell.startRow):(startRow=mergedCell.startRow,rowInitd=!0),endRow=Math.max(endRow,mergedCell.endRow),columnInitd?startColumn=Math.min(startColumn,mergedCell.startColumn):(startColumn=mergedCell.startColumn,rowInitd=!0),endColumn=Math.max(endColumn,mergedCell.endColumn)}),!rowInitd||!columnInitd?null:{startColumn,startRow,endColumn,endRow}}getRowManager(){return this._rowManager}getUnitId(){return this.unitId}getSheetId(){return this._sheetId}getColumnManager(){return this._columnManager}getName(){return this._snapshot.name}clone(){const{_snapshot:_config}=this,copy=Tools.deepClone(_config);return new _Worksheet(this.unitId,copy,this._styles)}getMergeData(){return this._snapshot.mergeData}getMergedCell(row,col){const rectangleList=this._snapshot.mergeData;for(let i=0;i<rectangleList.length;i++){const range=rectangleList[i];if(Rectangle.intersects({startRow:row,startColumn:col,endRow:row,endColumn:col},range))return range}return null}getCell(row,col){return row<0||col<0?null:this._viewModel.getCell(row,col)}getCellRaw(row,col){return this.getCellMatrix().getValue(row,col)}getRowFiltered(row){return this._viewModel.getRowFiltered(row)}getMatrixWithMergedCells(row,col,endRow,endCol,isRaw=!1){const matrix=this.getCellMatrix(),mergedCellsInRange=this._snapshot.mergeData.filter(rect=>Rectangle.intersects({startRow:row,startColumn:col,endRow,endColumn:endCol},rect)),returnCellMatrix=new ObjectMatrix;return createRowColIter(row,endRow,col,endCol).forEach((row2,col2)=>{const v=isRaw?this.getCellRaw(row2,col2):this.getCell(row2,col2);v&&returnCellMatrix.setValue(row2,col2,v)}),mergedCellsInRange.forEach(mergedCell=>{const{startColumn,startRow,endColumn,endRow:endRow2}=mergedCell;createRowColIter(startRow,endRow2,startColumn,endColumn).forEach((row2,col2)=>{row2===startRow&&col2===startColumn&&returnCellMatrix.setValue(row2,col2,{...matrix.getValue(row2,col2),rowSpan:endRow2-startRow+1,colSpan:endColumn-startColumn+1}),(row2!==startRow||col2!==startColumn)&&returnCellMatrix.realDeleteValue(row2,col2)})}),returnCellMatrix}getRange(startRowOrRange,startColumn,endRow,endColumn){return typeof startRowOrRange=="object"?new Range(this,startRowOrRange,{getStyles:__name(()=>this._styles,"getStyles")}):new Range(this,{startRow:startRowOrRange,startColumn,endColumn:endColumn||startColumn,endRow:endRow||startRowOrRange},{getStyles:__name(()=>this._styles,"getStyles")})}getScrollLeftTopFromSnapshot(){return{scrollLeft:this._snapshot.scrollLeft,scrollTop:this._snapshot.scrollTop}}getZoomRatio(){return this._snapshot.zoomRatio||1}getConfig(){return this._snapshot}getFreeze(){return this._snapshot.freeze}getMaxColumns(){const{_snapshot:_config}=this,{columnCount}=_config;return columnCount}getMaxRows(){const{_snapshot:_config}=this,{rowCount}=_config;return rowCount}getRowCount(){return this._snapshot.rowCount}setRowCount(count){this._snapshot.rowCount=count}getColumnCount(){return this._snapshot.columnCount}setColumnCount(count){this._snapshot.columnCount=count}isSheetHidden(){return this._snapshot.hidden}hasHiddenGridlines(){const{_snapshot:_config}=this,{showGridlines}=_config;return showGridlines===0}getTabColor(){const{_snapshot:_config}=this,{tabColor}=_config;return tabColor}getColumnWidth(columnPosition){return this.getColumnManager().getColumnWidth(columnPosition)}getRowHeight(row){return this._viewModel.getRowFiltered(row)?0:this.getRowManager().getRowHeight(row)}getRowVisible(row){return this._viewModel.getRowFiltered(row)?!1:this.getRowRawVisible(row)}getRowRawVisible(row){return this.getRowManager().getRowRawVisible(row)}getHiddenRows(start,end){const lastColumn=this.getMaxColumns()-1,ranges=this._rowManager.getHiddenRows(start,end);return ranges.forEach(range=>range.endColumn=lastColumn),ranges}getColVisible(col){return this._columnManager.getColVisible(col)}getHiddenCols(start,end){const lastRow=this.getMaxRows()-1,ranges=this._columnManager.getHiddenCols(start,end);return ranges.forEach(range=>range.endRow=lastRow),ranges}getVisibleRows(){const rowCount=this.getRowCount();return this._rowManager.getVisibleRows(0,rowCount-1)}getVisibleCols(){const columnCount=this.getColumnCount();return this._columnManager.getVisibleCols(0,columnCount-1)}isRightToLeft(){const{_snapshot:_config}=this,{rightToLeft}=_config;return rightToLeft}getLastRowWithContent(){return this._cellData.getLength()-1}getLastColumnWithContent(){return this._cellData.getRange().endColumn}cellHasValue(value){return value&&(value.v!==void 0||value.f!==void 0||value.p!==void 0)}iterateByRow(range,skipEmpty=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(columnIndex>endColumn&&(rowIndex+=1,columnIndex=startColumn),rowIndex>endRow)return{done:!0,value:void 0};const cellValue=worksheet.getCell(rowIndex,columnIndex),isEmptyCell2=!cellValue,mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){if(rowIndex!==mergedCell.startRow||columnIndex!==mergedCell.startColumn){columnIndex=mergedCell.endColumn+1;continue}if(isEmptyCell2&&skipEmpty){columnIndex=mergedCell.endColumn+1;continue}const value={row:rowIndex,col:columnIndex,value:cellValue};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,columnIndex=mergedCell.endColumn+1,{done:!1,value}}if(isEmptyCell2&&skipEmpty)columnIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return columnIndex+=1,{done:!1,value}}}}}}}}iterateByColumn(range,skipEmpty=!0,skipNonTopLeft=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(rowIndex>endRow&&(columnIndex+=1,rowIndex=startRow),columnIndex>endColumn)return{done:!0,value:void 0};const mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){const isNotTop=rowIndex!==mergedCell.startRow,isNotTopLeft=isNotTop||columnIndex!==mergedCell.startColumn;if(skipNonTopLeft&&isNotTopLeft||!skipNonTopLeft&&isNotTop){rowIndex=mergedCell.endRow+1;continue}const cellValue2=worksheet.getCell(mergedCell.startRow,mergedCell.startColumn);if(!cellValue2&&skipEmpty){rowIndex=mergedCell.endRow+1;continue}const value={row:rowIndex,col:mergedCell.startColumn,value:cellValue2};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,rowIndex=mergedCell.endRow+1,{done:!1,value}}const cellValue=worksheet.getCell(rowIndex,columnIndex);if(!cellValue&&skipEmpty)rowIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return rowIndex+=1,{done:!1,value}}}}}}}}};__name(_Worksheet,"Worksheet");let Worksheet=_Worksheet;function extractPureTextFromCell(cell){var _a13,_b2;if(!cell)return"";const richTextValue=(_b2=(_a13=cell.p)==null?void 0:_a13.body)==null?void 0:_b2.dataStream;if(richTextValue)return richTextValue;const rawValue=cell.v;return typeof rawValue=="string"?cell.t===CellValueType.BOOLEAN?rawValue.toUpperCase():rawValue.replace(/[\r\n]/g,""):typeof rawValue=="number"?cell.t===CellValueType.BOOLEAN?rawValue?"TRUE":"FALSE":rawValue.toString():typeof rawValue=="boolean"?rawValue?"TRUE":"FALSE":""}__name(extractPureTextFromCell,"extractPureTextFromCell");const version="0.2.6";function getEmptySnapshot(unitID="",locale=LocaleType.ZH_CN,name=""){return{id:unitID,sheetOrder:[],name,appVersion:version,locale,styles:{},sheets:{},resources:[]}}__name(getEmptySnapshot,"getEmptySnapshot");var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$7(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$7(target,key,result),result},"__decorateClass$7"),__decorateParam$6=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$6");function getWorksheetUID(workbook,worksheet){return`${workbook.getUnitId()}|${worksheet.getSheetId()}`}__name(getWorksheetUID,"getWorksheetUID");var _a3;exports.Workbook=(_a3=class extends UnitModel{constructor(workbookData={},_logService){super();__publicField(this,"type",I.UNIVER_SHEET);__publicField(this,"_sheetCreated$",new rxjs.Subject);__publicField(this,"sheetCreated$",this._sheetCreated$.asObservable());__publicField(this,"_sheetDisposed$",new rxjs.Subject);__publicField(this,"sheetDisposed$",this._sheetDisposed$.asObservable());__publicField(this,"_activeSheet$",new rxjs.BehaviorSubject(null));__publicField(this,"activeSheet$",this._activeSheet$.asObservable());__publicField(this,"_worksheets");__publicField(this,"_styles");__publicField(this,"_snapshot");__publicField(this,"_unitId");__publicField(this,"_count");__publicField(this,"_name$");__publicField(this,"name$");this._logService=_logService;const DEFAULT_WORKBOOK=getEmptySnapshot();Tools.isEmptyObject(workbookData)?this._snapshot=DEFAULT_WORKBOOK:this._snapshot=Tools.commonExtend(DEFAULT_WORKBOOK,workbookData);const{styles}=this._snapshot;(this._snapshot.id==null||this._snapshot.id.length===0)&&(this._snapshot.id=Tools.generateRandomId(6)),this._unitId=this._snapshot.id,this._styles=new Styles(styles),this._count=1,this._worksheets=new Map,this._name$=new rxjs.BehaviorSubject(workbookData.name||""),this.name$=this._name$.asObservable(),this._parseWorksheetSnapshots()}get _activeSheet(){return this._activeSheet$.getValue()}get name(){return this._name$.getValue()}dispose(){super.dispose(),this._sheetCreated$.complete(),this._sheetDisposed$.complete(),this._activeSheet$.complete(),this._name$.complete()}save(){return Tools.deepClone(this._snapshot)}static isIRangeType(range){return typeof range=="string"||"startRow"in range||"row"in range}getSnapshot(){return this._snapshot}getName(){return this._snapshot.name}setName(name){this._name$.next(name),this._snapshot.name=name}getUnitId(){return this._unitId}getRev(){var _a13;return(_a13=this._snapshot.rev)!=null?_a13:1}incrementRev(){this._snapshot.rev=this.getRev()+1}getShouldRenderLoopImmediately(){return this._snapshot.shouldStartRenderingImmediately!==!1}getContainer(){return this._snapshot.container}addWorksheet(id,index2,worksheetSnapshot){const{sheets,sheetOrder}=this._snapshot;if(sheets[id])return!1;sheets[id]=worksheetSnapshot,sheetOrder.splice(index2,0,id);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);return this._worksheets.set(id,worksheet),this._sheetCreated$.next(worksheet),!0}getSheetOrders(){return this._snapshot.sheetOrder}getWorksheets(){return this._worksheets}getActiveSpreadsheet(){return this}getStyles(){return this._styles}getConfig(){return this._snapshot}getIndexBySheetId(sheetId){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(id=>id===sheetId)}getActiveSheet(allowNull){if(!this._activeSheet&&typeof allowNull>"u")throw new Error(`[Workbook]: no active Worksheet on Workbook ${this._unitId}!`);return this._activeSheet}ensureActiveSheet(){const currentActive=this._activeSheet;if(currentActive)return currentActive;const sheetOrder=this._snapshot.sheetOrder;for(let i=0,len=sheetOrder.length;i<len;i++){const worksheet2=this._worksheets.get(sheetOrder[i]);if(worksheet2&&worksheet2.isSheetHidden()!==BooleanNumber.TRUE)return this.setActiveSheet(worksheet2),worksheet2}const worksheet=this._worksheets.get(sheetOrder[0]);return this.setActiveSheet(worksheet),worksheet}setActiveSheet(worksheet){this._activeSheet$.next(worksheet)}removeSheet(sheetId){const sheetToRemove=this._worksheets.get(sheetId);return sheetToRemove?(this._worksheets.delete(sheetId),this._snapshot.sheetOrder.splice(this._snapshot.sheetOrder.indexOf(sheetId),1),delete this._snapshot.sheets[sheetId],this._sheetDisposed$.next(sheetToRemove),!0):!1}getActiveSheetIndex(){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>this._worksheets.get(sheetId)===this._activeSheet)}getSheetSize(){return this._snapshot.sheetOrder.length}getSheets(){const{sheetOrder}=this._snapshot;return sheetOrder.map(sheetId=>this._worksheets.get(sheetId))}getSheetsName(){const{sheetOrder}=this._snapshot,names=[];return sheetOrder.forEach(sheetId=>{const worksheet=this._worksheets.get(sheetId);worksheet&&names.push(worksheet.getName())}),names}getSheetIndex(sheet){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>sheet.getSheetId()===sheetId)}getSheetBySheetName(name){const{sheetOrder}=this._snapshot,sheetId=sheetOrder.find(sheetId2=>this._worksheets.get(sheetId2).getName()===name);return this._worksheets.get(sheetId)}getSheetBySheetId(sheetId){return this._worksheets.get(sheetId)}getSheetByIndex(index2){const{sheetOrder}=this._snapshot;return this._worksheets.get(sheetOrder[index2])}getHiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden===BooleanNumber.TRUE).map(s=>s.getConfig().id)}getUnhiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden!==BooleanNumber.TRUE).map(s=>s.getConfig().id)}load(config){this._snapshot=config}checkSheetName(name){return this.getSheetsName().includes(name)}uniqueSheetName(name="Sheet1"){let output=name;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}generateNewSheetName(name){let output=name+this._count;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}_parseWorksheetSnapshots(){const{_snapshot,_worksheets}=this,{sheets,sheetOrder}=_snapshot;if(Tools.isEmptyObject(sheets)){const firstSheetId=Tools.generateRandomId();sheets[firstSheetId]={id:firstSheetId}}for(const sheetId in sheets){const worksheetSnapshot=sheets[sheetId],{name}=worksheetSnapshot;worksheetSnapshot.name=this.uniqueSheetName(name),worksheetSnapshot.name!==name&&this._logService.debug("[Workbook]",`The worksheet name ${name} is duplicated, we changed it to ${worksheetSnapshot.name}. Please fix the problem in your snapshot.`);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);_worksheets.set(sheetId,worksheet),sheetOrder.includes(sheetId)||sheetOrder.push(sheetId)}this.ensureActiveSheet()}},__name(_a3,"Workbook"),_a3);exports.Workbook=__decorateClass$7([__decorateParam$6(1,ILogService)],exports.Workbook);const _SlideDataModel=class _SlideDataModel extends UnitModel{constructor(snapshot){var _a13;super();__publicField(this,"type",I.UNIVER_SLIDE);__publicField(this,"_activePage$",new rxjs.BehaviorSubject(null));__publicField(this,"activePage$",this._activePage$.asObservable());__publicField(this,"_snapshot");__publicField(this,"_unitId");this._snapshot={...DEFAULT_SLIDE,...snapshot},this._unitId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6)}get _activePage(){var _a13,_b2;const activePage=this._activePage$.getValue();if(!activePage){const activePageId=(_a13=this.getPageOrder())==null?void 0:_a13[0];return activePageId?(_b2=this.getPages())==null?void 0:_b2[activePageId]:null}return activePage}getContainer(){return this._snapshot.container}getSnapshot(){return this._snapshot}getUnitId(){return this._unitId}getPages(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pages}getPageOrder(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pageOrder}getPage(pageId){const pages=this.getPages();return pages==null?void 0:pages[pageId]}getElementsByPage(pageId){var _a13;return(_a13=this.getPage(pageId))==null?void 0:_a13.pageElements}getElement(pageId,elementId){var _a13;return(_a13=this.getElementsByPage(pageId))==null?void 0:_a13[elementId]}getPageSize(){return this._snapshot.pageSize}addPage(){return{id:"cover_1",pageType:PageType.SLIDE,zIndex:10,title:"cover",description:"this is first page, cover",pageBackgroundFill:{rgb:"rgb(255,255,255)"},pageElements:{}}}setActivePage(page){this._activePage$.next(page)}getActivePage(){return this._activePage}updatePage(pageId,page){this._snapshot.body&&(this._snapshot.body.pages[pageId]=page)}};__name(_SlideDataModel,"SlideDataModel");let SlideDataModel=_SlideDataModel;const FOCUSING_SHEET="FOCUSING_SHEET",FOCUSING_DOC="FOCUSING_DOC",FOCUSING_SLIDE="FOCUSING_SLIDE",FOCUSING_EDITOR_BUT_HIDDEN="FOCUSING_EDITOR_BUT_HIDDEN",EDITOR_ACTIVATED="EDITOR_ACTIVATED",FOCUSING_EDITOR_INPUT_FORMULA="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_FORMULA_EDITOR="FOCUSING_FORMULA_EDITOR",FOCUSING_UNIVER_EDITOR="FOCUSING_UNIVER_EDITOR",FOCUSING_EDITOR_STANDALONE="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE="FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE",FOCUSING_COMMON_DRAWINGS="FOCUSING_COMMON_DRAWINGS";var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$6(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$6(target,key,result),result},"__decorateClass$6"),__decorateParam$5=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$5");const IUniverInstanceService=createIdentifier("univer.current");var _a4;exports.UniverInstanceService=(_a4=class extends Disposable{constructor(_injector,_contextService){super();__publicField(this,"_unitsByType",new Map);__publicField(this,"_createHandler");__publicField(this,"_ctorByType",new Map);__publicField(this,"_currentUnits",new Map);__publicField(this,"_currentUnits$",new rxjs.BehaviorSubject(this._currentUnits));__publicField(this,"currentUnits$",this._currentUnits$.asObservable());__publicField(this,"_unitAdded$",new rxjs.Subject);__publicField(this,"unitAdded$",this._unitAdded$.asObservable());__publicField(this,"_unitDisposed$",new rxjs.Subject);__publicField(this,"unitDisposed$",this._unitDisposed$.asObservable());__publicField(this,"_focused$",new rxjs.BehaviorSubject(null));__publicField(this,"focused$",this._focused$.asObservable());this._injector=_injector,this._contextService=_contextService}dispose(){super.dispose(),this._focused$.complete()}__setCreateHandler(handler){this._createHandler=handler}createUnit(type2,data){return this._createHandler(type2,data,this._ctorByType.get(type2))}registerCtorForType(type2,ctor){return this._ctorByType.set(type2,ctor),{dispose:__name(()=>{this._ctorByType.delete(type2)},"dispose")}}getCurrentTypeOfUnit$(type2){return this.currentUnits$.pipe(rxjs.map(units=>{var _a13;return(_a13=units.get(type2))!=null?_a13:null}),rxjs.distinctUntilChanged())}getCurrentUnitForType(type2){return this._currentUnits.get(type2)}setCurrentUnitForType(unitId){const result=this._getUnitById(unitId);if(!result)throw new Error(`[UniverInstanceService]: no document with unitId ${unitId}!`);this._currentUnits.set(result[1],result[0]),this._currentUnits$.next(this._currentUnits)}_removeCurrentUnitForType(type2){this._currentUnits.set(type2,null),this._currentUnits$.next(this._currentUnits)}getTypeOfUnitAdded$(type2){return this._unitAdded$.pipe(rxjs.filter(unit=>unit.type===type2))}__addUnit(unit){const type2=unit.type;this._unitsByType.has(type2)||this._unitsByType.set(type2,[]),this._unitsByType.get(type2).push(unit),this._unitAdded$.next(unit),this.setCurrentUnitForType(unit.getUnitId())}getTypeOfUnitDisposed$(type2){return this.unitDisposed$.pipe(rxjs.filter(unit=>unit.type===type2))}getUnit(id,type2){var _a13;const unit=(_a13=this._getUnitById(id))==null?void 0:_a13[0];return type2&&(unit==null?void 0:unit.type)!==type2?null:unit}getCurrentUniverDocInstance(){return this.getCurrentUnitForType(I.UNIVER_DOC)}getUniverDocInstance(unitId){return this.getUnit(unitId,I.UNIVER_DOC)}getUniverSheetInstance(unitId){return this.getUnit(unitId,I.UNIVER_SHEET)}getAllUnitsForType(type2){var _a13;return(_a13=this._unitsByType.get(type2))!=null?_a13:[]}changeDoc(unitId,doc){const allDocs=this.getAllUnitsForType(I.UNIVER_DOC),oldDoc=allDocs.find(doc2=>doc2.getUnitId()===unitId);if(oldDoc!=null){const index2=allDocs.indexOf(oldDoc);allDocs.splice(index2,1)}this.__addUnit(doc)}get focused(){var _a13;const id=this._focused$.getValue();return id?(_a13=this._getUnitById(id))==null?void 0:_a13[0]:null}focusUnit(id){this._focused$.next(id),this.focused instanceof exports.Workbook?(this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!0),this._contextService.setContextValue(FOCUSING_SLIDE,!1)):this.focused instanceof DocumentDataModel?(this._contextService.setContextValue(FOCUSING_DOC,!0),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!1)):this.focused instanceof SlideDataModel&&(this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!0))}getFocusedUnit(){return this.focused}getUnitType(unitId){const result=this._getUnitById(unitId);if(!result)throw new Error(`[UniverInstanceService]: No document with unitId ${unitId}`);return result[1]}disposeUnit(unitId){const result=this._getUnitById(unitId);if(!result)return!1;const[unit,type2]=result,units=this._unitsByType.get(type2),index2=units.indexOf(unit);return units.splice(index2,1),this._removeCurrentUnitForType(type2),this._focused$.next(null),this._unitDisposed$.next(unit),!0}_getUnitById(unitId){for(const[type2,units]of this._unitsByType){const unit=units.find(unit2=>unit2.getUnitId()===unitId);if(unit)return[unit,type2]}}},__name(_a4,"UniverInstanceService"),_a4);exports.UniverInstanceService=__decorateClass$6([__decorateParam$5(0,Inject(Injector)),__decorateParam$5(1,IContextService)],exports.UniverInstanceService);var LifecycleStages=(LifecycleStages2=>(LifecycleStages2[LifecycleStages2.Starting=0]="Starting",LifecycleStages2[LifecycleStages2.Ready=1]="Ready",LifecycleStages2[LifecycleStages2.Rendered=2]="Rendered",LifecycleStages2[LifecycleStages2.Steady=3]="Steady",LifecycleStages2))(LifecycleStages||{});const LifecycleNameMap={0:"Starting",1:"Ready",2:"Rendered",3:"Steady"},LifecycleToModules=new Map;function OnLifecycle(lifecycleStage,identifier){return __name(function(_){runOnLifecycle(lifecycleStage,identifier)},"decorator2")}__name(OnLifecycle,"OnLifecycle");function runOnLifecycle(lifecycleStage,identifier){LifecycleToModules.has(lifecycleStage)||LifecycleToModules.set(lifecycleStage,[]),LifecycleToModules.get(lifecycleStage).push(identifier)}__name(runOnLifecycle,"runOnLifecycle");var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$5(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$5(target,key,result),result},"__decorateClass$5"),__decorateParam$4=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$4"),_a5;exports.LifecycleService=(_a5=class extends Disposable{constructor(_logService){super();__publicField(this,"_lifecycle$",new rxjs.BehaviorSubject(LifecycleStages.Starting));__publicField(this,"lifecycle$",this._lifecycle$.asObservable());__publicField(this,"_lock",!1);this._logService=_logService,this._reportProgress(LifecycleStages.Starting)}get stage(){return this._lifecycle$.getValue()}set stage(stage){if(stage<this.stage)throw new Error("[LifecycleService]: lifecycle stage cannot go backward!");if(stage!==this.stage){if(this._lock)throw new Error("[LifecycleService]: cannot set new stage when related logic is all handled!");this._lock=!0,this._reportProgress(stage),this._lifecycle$.next(stage),this._lock=!1}}dispose(){this._lifecycle$.complete(),super.dispose()}subscribeWithPrevious(){return rxjs.merge(getLifecycleStagesAndBefore(this.stage),this._lifecycle$.pipe(rxjs.skip(1))).pipe(takeAfter(s=>s===LifecycleStages.Steady))}_reportProgress(stage){this._logService.debug("[LifecycleService]",`lifecycle progressed to "${LifecycleNameMap[stage]}".`)}},__name(_a5,"LifecycleService"),_a5);exports.LifecycleService=__decorateClass$5([__decorateParam$4(0,ILogService)],exports.LifecycleService);var _a6;exports.LifecycleInitializerService=(_a6=class extends Disposable{constructor(_injector){super();__publicField(this,"_seenTokens",new Set);this._injector=_injector}initModulesOnStage(stage){var _a13;(_a13=LifecycleToModules.get(stage))==null||_a13.forEach(m=>{this._injector.has(m)&&!this._seenTokens.has(m)&&(this._injector.get(m),this._seenTokens.add(m))})}},__name(_a6,"LifecycleInitializerService"),_a6);exports.LifecycleInitializerService=__decorateClass$5([__decorateParam$4(0,Inject(Injector))],exports.LifecycleInitializerService);function getLifecycleStagesAndBefore(lifecycleStage){switch(lifecycleStage){case LifecycleStages.Starting:return rxjs.of(LifecycleStages.Starting);case LifecycleStages.Ready:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready);case LifecycleStages.Rendered:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered);default:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered,LifecycleStages.Steady)}}__name(getLifecycleStagesAndBefore,"getLifecycleStagesAndBefore");const _LocaleService=class _LocaleService extends Disposable{constructor(){super();__publicField(this,"_currentLocale$",new rxjs.BehaviorSubject(LocaleType.ZH_CN));__publicField(this,"currentLocale$",this._currentLocale$.asObservable());__publicField(this,"_locales",null);__publicField(this,"localeChanged$",new rxjs.Subject);__publicField(this,"t",__name((key,...args)=>{if(!this._locales)throw new Error("[LocaleService]: Locale not initialized");const keys=key.split("."),resolvedValue=this.resolveKeyPath(this._locales[this._currentLocale],keys);if(typeof resolvedValue=="string"){let result=resolvedValue;return args.forEach((arg,index2)=>{result=result.replace(`{${index2}}`,arg)}),result}else return key},"t"));this.disposeWithMe(toDisposable(()=>this.localeChanged$.complete()))}get _currentLocale(){return this._currentLocale$.value}load(locales){var _a13;this._locales=Tools.deepMerge((_a13=this._locales)!=null?_a13:{},locales)}setLocale(locale){this._currentLocale$.next(locale),this.localeChanged$.next()}getLocales(){var _a13;return(_a13=this._locales)==null?void 0:_a13[this._currentLocale]}getCurrentLocale(){return this._currentLocale}resolveKeyPath(obj,keys){const currentKey=keys.shift();if(currentKey&&obj&&currentKey in obj){const nextObj=obj[currentKey];return keys.length>0&&(typeof nextObj=="object"||Array.isArray(nextObj))?this.resolveKeyPath(nextObj,keys):nextObj}return null}};__name(_LocaleService,"LocaleService");let LocaleService=_LocaleService;var PermissionStatus=(PermissionStatus2=>(PermissionStatus2.INIT="init",PermissionStatus2.FETCHING="fetching",PermissionStatus2.DONE="done",PermissionStatus2))(PermissionStatus||{});const IPermissionService=createIdentifier("univer.permission-service");runOnLifecycle(LifecycleStages.Starting,IPermissionService);const _PermissionService=class _PermissionService extends Disposable{constructor(){super(...arguments);__publicField(this,"_permissionPointMap",new Map);__publicField(this,"_permissionPointUpdate$",new rxjs.Subject);__publicField(this,"permissionPointUpdate$",this._permissionPointUpdate$.asObservable())}deletePermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);permissionPoint&&(permissionPoint.complete(),this._permissionPointMap.delete(permissionId))}addPermissionPoint(_item){const isSubject=_item instanceof rxjs.BehaviorSubject,item=isSubject?_item.getValue():_item;if(!item.id)return!1;if(this._permissionPointMap.get(item.id))throw new Error(`${item.id} PermissionPoint already exists`);return this._permissionPointMap.set(item.id,isSubject?_item:new rxjs.BehaviorSubject(item)),this._permissionPointUpdate$.next(item),!0}updatePermissionPoint(permissionId,value){const permissionPoint=this._permissionPointMap.get(permissionId);if(!permissionPoint)return;const subject=permissionPoint.getValue();subject.value=value,subject.status=PermissionStatus.DONE,permissionPoint.next({...subject}),this._permissionPointUpdate$.next(subject)}clearPermissionMap(){this._permissionPointMap.clear()}getPermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint.getValue()}getPermissionPoint$(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint}composePermission$(permissionIdList){const subjectList=permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.asObservable()});return rxjs.combineLatest(subjectList).pipe(operators.map(list=>list))}composePermission(permissionIdList){return permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.getValue()})}getAllPermissionPoint(){const cacheMap=new Map;return this._permissionPointMap.forEach((v,key)=>{cacheMap.set(key,v)}),cacheMap}};__name(_PermissionService,"PermissionService");let PermissionService=_PermissionService;const _ResourceManagerService=class _ResourceManagerService extends Disposable{constructor(){super(...arguments);__publicField(this,"_resourceMap",new Map);__publicField(this,"_register$",new rxjs.Subject);__publicField(this,"register$",this._register$.asObservable())}getAllResourceHooks(){return[...this._resourceMap.values()]}getResources(unitId){return this.getAllResourceHooks().map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}getResourcesByType(unitId,type2){return this.getAllResourceHooks().filter(hook=>hook.businesses.includes(type2)).map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}registerPluginResource(hook){const resourceName=hook.pluginName;if(this._resourceMap.has(resourceName))throw new Error(`the pluginName is registered {${resourceName}}`);return this._resourceMap.set(resourceName,hook),this._register$.next(hook),toDisposable(()=>this._resourceMap.delete(resourceName))}disposePluginResource(pluginName){this._resourceMap.delete(pluginName)}loadResources(unitId,resources){this.getAllResourceHooks().forEach(hook=>{var _a13;const data=(_a13=resources==null?void 0:resources.find(resource=>resource.name===hook.pluginName))==null?void 0:_a13.data;if(data)try{const model=hook.parseJson(data);hook.onLoad(unitId,model)}catch{console.error("LoadResources Error!")}})}unloadResources(unitId){this.getAllResourceHooks().forEach(hook=>{hook.onUnLoad(unitId)})}dispose(){this._register$.complete(),this._resourceMap.clear()}};__name(_ResourceManagerService,"ResourceManagerService");let ResourceManagerService=_ResourceManagerService;const IResourceManagerService=createIdentifier("resource-manager-service");var __defProp$4=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$4(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$4(target,key,result),result},"__decorateClass$4"),__decorateParam$3=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$3"),_a7;let ResourceLoaderService=(_a7=class extends Disposable{constructor(_resourceManagerService,_univerInstanceService){super();__publicField(this,"saveWorkbook",__name(workbook=>{const unitId=workbook.getUnitId(),resources=this._resourceManagerService.getResources(unitId)||[],snapshot=workbook.getSnapshot();return snapshot.resources=resources,snapshot},"saveWorkbook"));this._resourceManagerService=_resourceManagerService,this._univerInstanceService=_univerInstanceService,this._init()}_init(){const handleHookAdd=__name(hook=>{hook.businesses.forEach(business=>{switch(business){case I.UNRECOGNIZED:case I.UNIVER_UNKNOWN:case I.UNIVER_SLIDE:case I.UNIVER_DOC:{this._univerInstanceService.getAllUnitsForType(I.UNIVER_DOC).forEach(doc=>{const plugin=(doc.getSnapshot().resources||[]).find(r=>r.name===hook.pluginName);if(plugin)try{const data=hook.parseJson(plugin.data);hook.onLoad(doc.getUnitId(),data)}catch{console.error(`Load Document{${doc.getUnitId()}} Resources{${hook.pluginName}} Data Error.`)}});break}case I.UNIVER_SHEET:this._univerInstanceService.getAllUnitsForType(I.UNIVER_SHEET).forEach(workbook=>{const plugin=(workbook.getSnapshot().resources||[]).find(r=>r.name===hook.pluginName);if(plugin)try{const data=hook.parseJson(plugin.data);hook.onLoad(workbook.getUnitId(),data)}catch{console.error(`Load Workbook{${workbook.getUnitId()}} Resources{${hook.pluginName}} Data Error.`)}})}})},"handleHookAdd");this._resourceManagerService.getAllResourceHooks().forEach(hook=>{handleHookAdd(hook)}),this.disposeWithMe(this._resourceManagerService.register$.subscribe(hook=>{handleHookAdd(hook)})),this.disposeWithMe(toDisposable(this._univerInstanceService.getTypeOfUnitAdded$(I.UNIVER_SHEET).subscribe(workbook=>{this._resourceManagerService.loadResources(workbook.getUnitId(),workbook.getSnapshot().resources)}))),this.disposeWithMe(toDisposable(this._univerInstanceService.getTypeOfUnitDisposed$(I.UNIVER_SHEET).subscribe(workbook=>{this._resourceManagerService.unloadResources(workbook.getUnitId())})))}saveDoc(doc){const unitId=doc.getUnitId(),resources=this._resourceManagerService.getResourcesByType(unitId,I.UNIVER_DOC)||[],snapshot=doc.getSnapshot();return snapshot.resources=resources,snapshot}},__name(_a7,"ResourceLoaderService"),_a7);ResourceLoaderService=__decorateClass$4([__decorateParam$3(0,Inject(IResourceManagerService)),__decorateParam$3(1,Inject(IUniverInstanceService))],ResourceLoaderService);const IResourceLoaderService=createIdentifier("resource-loader-service");runOnLifecycle(LifecycleStages.Ready,IResourceLoaderService);const _ThemeService=class _ThemeService extends Disposable{constructor(){super();__publicField(this,"_currentTheme");__publicField(this,"_currentTheme$",new rxjs.BehaviorSubject({}));__publicField(this,"currentTheme$",this._currentTheme$.asObservable());this.disposeWithMe(toDisposable(()=>this._currentTheme$.complete()))}getCurrentTheme(){if(!this._currentTheme)throw new Error("[ThemeService]: current theme is not set!");return this._currentTheme}setTheme(theme){this._currentTheme=theme,this._currentTheme$.next(theme)}};__name(_ThemeService,"ThemeService");let ThemeService=_ThemeService;const PREFIX="__INTERNAL_EDITOR__",DOCS_NORMAL_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_NORMAL`,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_FORMULA_BAR`,DOCS_ZEN_EDITOR_UNIT_ID_KEY="__defaultDocumentZenEditorSpecialUnitId_20231218__",DEFAULT_EMPTY_DOCUMENT_VALUE=`\r
9
+ `;function createInternalEditorID(id){return`${PREFIX}${id}`}__name(createInternalEditorID,"createInternalEditorID");function isInternalEditorID(id){return id.startsWith(PREFIX)}__name(isInternalEditorID,"isInternalEditorID");var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$2=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$2");const IUndoRedoService=createIdentifier("univer.undo-redo.service"),STACK_CAPACITY=20,_MultiImplementationCommand=class _MultiImplementationCommand{dispose(){}async dispatchToHandlers(){return!1}};__name(_MultiImplementationCommand,"MultiImplementationCommand");let MultiImplementationCommand=_MultiImplementationCommand;const RedoCommandId="univer.command.redo",UndoCommandId="univer.command.undo",UndoCommand=new class extends MultiImplementationCommand{constructor(){super(...arguments);__publicField(this,"type",CommandType.COMMAND);__publicField(this,"id",UndoCommandId)}async handler(accessor){const undoRedoService=accessor.get(IUndoRedoService),element=undoRedoService.pitchTopUndoElement();if(!element)return!1;const commandService=accessor.get(ICommandService);return sequenceExecute(element.undoMutations,commandService)?(undoRedoService.popUndoToRedo(),!0):!1}},RedoCommand=new class extends MultiImplementationCommand{constructor(){super(...arguments);__publicField(this,"type",CommandType.COMMAND);__publicField(this,"id",RedoCommandId)}async handler(accessor){const undoRedoService=accessor.get(IUndoRedoService),element=undoRedoService.pitchTopRedoElement();if(!element)return!1;const commandService=accessor.get(ICommandService);return sequenceExecute(element.redoMutations,commandService)?(undoRedoService.popRedoToUndo(),!0):!1}};var _a8;exports.LocalUndoRedoService=(_a8=class extends Disposable{constructor(_univerInstanceService,_commandService,_contextService){super();__publicField(this,"undoRedoStatus$");__publicField(this,"_undoRedoStatus$",new rxjs.BehaviorSubject({undos:0,redos:0}));__publicField(this,"_undoStacks",new Map);__publicField(this,"_redoStacks",new Map);__publicField(this,"_batchingStatus",new Map);this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._contextService=_contextService,this.undoRedoStatus$=this._undoRedoStatus$.asObservable(),this.disposeWithMe(this._commandService.registerCommand(UndoCommand)),this.disposeWithMe(this._commandService.registerCommand(RedoCommand)),this.disposeWithMe(toDisposable(()=>this._undoRedoStatus$.complete())),this.disposeWithMe(toDisposable(this._univerInstanceService.focused$.subscribe(()=>this._updateStatus())))}pushUndoRedo(item){const{unitID}=item,redoStack=this._getRedoStack(unitID,!0),undoStack=this._getUndoStack(unitID,!0);if(redoStack.length=0,this._batchingStatus.has(item.unitID)){const batchingStatus=this._batchingStatus.get(item.unitID),lastItem=this._pitchUndoElement(item.unitID);batchingStatus===0||!lastItem?(appendNewItem(item),this._batchingStatus.set(item.unitID,1)):this._tryBatchingElements(lastItem,item)}else appendNewItem(item);function appendNewItem(item2){undoStack.push(item2),undoStack.length>STACK_CAPACITY&&undoStack.splice(0,1)}__name(appendNewItem,"appendNewItem"),this._updateStatus()}clearUndoRedo(unitID){const redoStack=this._getRedoStack(unitID);redoStack&&(redoStack.length=0);const undoStack=this._getUndoStack(unitID);undoStack&&(undoStack.length=0),this._updateStatus()}pitchTopUndoElement(){const unitID=this._getFocusedUnitId();return this._pitchUndoElement(unitID)}pitchTopRedoElement(){const unitID=this._getFocusedUnitId();return this._pitchRedoElement(unitID)}_pitchUndoElement(unitId){const stack=this._getUndoStack(unitId);return stack!=null&&stack.length?stack[stack.length-1]:null}_pitchRedoElement(unitId){const stack=this._getRedoStack(unitId);return stack!=null&&stack.length?stack[stack.length-1]:null}popUndoToRedo(){const element=this._getUndoStackForFocused().pop();element&&(this._getRedoStackForFocused().push(element),this._updateStatus())}popRedoToUndo(){const element=this._getRedoStackForFocused().pop();element&&(this._getUndoStackForFocused().push(element),this._updateStatus())}__tempBatchingUndoRedo(unitId){if(this._batchingStatus.has(unitId))throw new Error("[LocalUndoRedoService]: cannot batching undo redo twice at the same time!");return this._batchingStatus.set(unitId,0),toDisposable(()=>this._batchingStatus.delete(unitId))}_updateStatus(){var _a13,_b2;const unitID=this._getFocusedUnitId(),undos=unitID&&((_a13=this._undoStacks.get(unitID))==null?void 0:_a13.length)||0,redos=unitID&&((_b2=this._redoStacks.get(unitID))==null?void 0:_b2.length)||0;this._undoRedoStatus$.next({undos,redos})}_getUndoStack(unitId,createAsNeeded=!1){let stack=this._undoStacks.get(unitId);return!stack&&createAsNeeded&&(stack=[],this._undoStacks.set(unitId,stack)),stack||null}_getRedoStack(unitId,createAsNeeded=!1){let stack=this._redoStacks.get(unitId);return!stack&&createAsNeeded&&(stack=[],this._redoStacks.set(unitId,stack)),stack||null}_getUndoStackForFocused(){const unitID=this._getFocusedUnitId();if(!unitID)throw new Error("No focused univer instance!");return this._getUndoStack(unitID,!0)}_getRedoStackForFocused(){const unitID=this._getFocusedUnitId();if(!unitID)throw new Error("No focused univer instance!");return this._getRedoStack(unitID,!0)}_tryBatchingElements(item,newItem){item.redoMutations.push(...newItem.redoMutations),item.undoMutations.push(...newItem.undoMutations)}_getFocusedUnitId(){var _a13,_b2,_c,_d;let unitID="";const isFocusSheet=this._contextService.getContextValue(FOCUSING_SHEET),isFocusFormulaEditor=this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR),isFocusEditor=this._contextService.getContextValue(EDITOR_ACTIVATED);return isFocusSheet?isFocusFormulaEditor?unitID=DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY:isFocusEditor?unitID=DOCS_NORMAL_EDITOR_UNIT_ID_KEY:unitID=(_b2=(_a13=this._univerInstanceService.getFocusedUnit())==null?void 0:_a13.getUnitId())!=null?_b2:"":unitID=(_d=(_c=this._univerInstanceService.getFocusedUnit())==null?void 0:_c.getUnitId())!=null?_d:"",unitID}},__name(_a8,"LocalUndoRedoService"),_a8);exports.LocalUndoRedoService=__decorateClass$3([__decorateParam$2(0,IUniverInstanceService),__decorateParam$2(1,ICommandService),__decorateParam$2(2,IContextService)],exports.LocalUndoRedoService);const DependentOnSymbol=Symbol("DependentOn"),_Plugin=class _Plugin extends Disposable{onStarting(_injector){}onReady(){}onRendered(){}onSteady(){}getUniverInstanceType(){return this.constructor.type}getPluginName(){return this.constructor.pluginName}};__name(_Plugin,"Plugin"),__publicField(_Plugin,"pluginName"),__publicField(_Plugin,"type",I.UNIVER_UNKNOWN);let Plugin=_Plugin;const _PluginStore=class _PluginStore{constructor(){__publicField(this,"_plugins",[])}addPlugin(plugin){this._plugins.push(plugin)}removePlugins(){const plugins=this._plugins.slice();return this._plugins.length=0,plugins}forEachPlugin(callback){this._plugins.forEach(callback)}};__name(_PluginStore,"PluginStore");let PluginStore=_PluginStore;const _PluginRegistry=class _PluginRegistry{constructor(){__publicField(this,"_pluginsRegistered",[])}registerPlugin(pluginCtor,options){this._pluginsRegistered.push({plugin:pluginCtor,options})}getRegisterPlugins(){return this._pluginsRegistered.slice()}removePlugins(){this._pluginsRegistered=[]}};__name(_PluginRegistry,"PluginRegistry");let PluginRegistry=_PluginRegistry;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$1=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$1");const INIT_LAZY_PLUGINS_TIMEOUT=4;function DependentOn(...plugins){return function(target){target[DependentOnSymbol]=plugins}}__name(DependentOn,"DependentOn");var _a9;exports.PluginService=(_a9=class{constructor(_injector){__publicField(this,"_pluginHolderForUniver");__publicField(this,"_pluginHoldersForTypes",new Map);__publicField(this,"_seenPlugins",new Set);__publicField(this,"_flushTimer");this._injector=_injector,this._pluginHolderForUniver=this._injector.createInstance(PluginHolder,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this)),this._pluginHolderForUniver.start()}dispose(){this._clearFlushTimer();for(const holder of this._pluginHoldersForTypes.values())holder.dispose();this._pluginHolderForUniver.dispose()}registerPlugin(ctor,config){this._assertPluginValid(ctor),this._scheduleInitPlugin();const{type:type2}=ctor;type2===I.UNIVER_UNKNOWN?(this._pluginHolderForUniver.register(ctor,config),this._pluginHolderForUniver.flush()):this._ensurePluginHolderForType(type2).register(ctor,config)}startPluginForType(type2){this._ensurePluginHolderForType(type2).start()}_ensurePluginHolderForType(type2){if(!this._pluginHoldersForTypes.has(type2)){const pluginHolder=this._injector.createInstance(PluginHolder,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this));return this._pluginHoldersForTypes.set(type2,pluginHolder),pluginHolder}return this._pluginHoldersForTypes.get(type2)}_immediateInitPlugin(ctor){this._seenPlugins.add(ctor.pluginName),this._ensurePluginHolderForType(ctor.type).immediateInitPlugin(ctor)}_checkPluginSeen(ctor){return this._seenPlugins.has(ctor.pluginName)}_assertPluginValid(ctor){const{type:type2,pluginName}=ctor;if(type2===I.UNRECOGNIZED)throw new Error(`[PluginService]: invalid plugin type for ${ctor}. Please assign a "type" to your plugin.`);if(pluginName==="")throw new Error(`[PluginService]: no plugin name for ${ctor}. Please assign a "pluginName" to your plugin.`);if(this._seenPlugins.has(pluginName))throw new Error(`[PluginService]: duplicated plugin name for "${pluginName}". Maybe a plugin that dependents on "${pluginName} has already registered it. In that case please register "${pluginName}" before the that plugin.`);this._seenPlugins.add(ctor.pluginName)}_scheduleInitPlugin(){this._flushTimer===void 0&&(this._flushTimer=setTimeout(()=>{this._pluginHolderForUniver.started||this._pluginHolderForUniver.start(),this._flushPlugins(),this._clearFlushTimer()},INIT_LAZY_PLUGINS_TIMEOUT))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_flushPlugins(){this._pluginHolderForUniver.flush();for(const[_,holder]of this._pluginHoldersForTypes)holder.started&&holder.flush()}},__name(_a9,"PluginService"),_a9);exports.PluginService=__decorateClass$2([__decorateParam$1(0,Inject(Injector))],exports.PluginService);var _a10;let PluginHolder=(_a10=class extends Disposable{constructor(_checkPluginRegistered,_registerPlugin,_logService,_injector,_lifecycleService,_lifecycleInitializerService){super();__publicField(this,"_started",!1);__publicField(this,"_warnedAboutOnStartingDeprecation",!1);__publicField(this,"_pluginRegistry",new PluginRegistry);__publicField(this,"_pluginStore",new PluginStore);__publicField(this,"_awaitingPlugins",[]);this._checkPluginRegistered=_checkPluginRegistered,this._registerPlugin=_registerPlugin,this._logService=_logService,this._injector=_injector,this._lifecycleService=_lifecycleService,this._lifecycleInitializerService=_lifecycleInitializerService,this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(rxjs.skip(1)).subscribe(stage=>{this._awaitingPlugins.forEach(plugins=>this._runStage(plugins,stage))}))}get started(){return this._started}dispose(){super.dispose(),this._pluginStore.forEachPlugin(plugin=>plugin.dispose()),this._pluginStore.removePlugins(),this._pluginRegistry.removePlugins(),this._awaitingPlugins.length=0}register(pluginCtor,config){this._pluginRegistry.registerPlugin(pluginCtor,config)}immediateInitPlugin(plugin){const p=this._initPlugin(plugin,void 0);this._pluginsRunLifecycle([p])}start(){this._started||(this._started=!0,this.flush())}flush(){if(!this._started)return;const plugins=this._pluginRegistry.getRegisterPlugins().map(({plugin,options})=>this._initPlugin(plugin,options));plugins.length&&(this._pluginsRunLifecycle(plugins),this._pluginRegistry.removePlugins())}_initPlugin(plugin,options){const dependents=plugin[DependentOnSymbol];if(dependents){const exhaustUnregisteredDependents=__name(()=>{const NotRegistered=dependents.find(d=>!this._checkPluginRegistered(d));return NotRegistered?(this._logService.debug("[PluginService]",`plugin "${plugin.pluginName}" depends on "${NotRegistered.pluginName}" which is not registered. Univer will automatically register it with default configuration.`),this._registerPlugin(NotRegistered,void 0),!0):!1},"exhaustUnregisteredDependents");for(;exhaustUnregisteredDependents(););}const pluginInstance=this._injector.createInstance(plugin,options);return this._pluginStore.addPlugin(pluginInstance),pluginInstance}_pluginsRunLifecycle(plugins){getLifecycleStagesAndBefore(this._lifecycleService.stage).subscribe(stage=>this._runStage(plugins,stage)),this._awaitingPlugins.push(plugins)}_runStage(plugins,stage){plugins.forEach(p=>{switch(stage){case LifecycleStages.Starting:p.onStarting.length>0&&p.onStarting!==Plugin.prototype.onStarting&&!this._warnedAboutOnStartingDeprecation&&(this._logService.warn("[PluginService]",p.onStarting.length,`Plugin "${p.getPluginName()}" is using deprecated "onStarting" method with arguments. Please use "this._injector" instead.`),this._warnedAboutOnStartingDeprecation=!0),p.onStarting(this._injector);break;case LifecycleStages.Ready:p.onReady();break;case LifecycleStages.Rendered:p.onRendered();break;case LifecycleStages.Steady:p.onSteady();break}}),this._lifecycleInitializerService.initModulesOnStage(stage)}},__name(_a10,"PluginHolder"),_a10);PluginHolder=__decorateClass$2([__decorateParam$1(2,ILogService),__decorateParam$1(3,Inject(Injector)),__decorateParam$1(4,Inject(exports.LifecycleService)),__decorateParam$1(5,Inject(exports.LifecycleInitializerService))],PluginHolder);function mergeOverrideWithDependencies(dependencies,override){if(!override)return dependencies;const result=[];for(const dependency of dependencies){const overrideItem=override.find(([identifier])=>identifier===dependency[0]);if(overrideItem){if(overrideItem[1]===null)continue;result.push([dependency[0],overrideItem[1]])}else result.push(dependency)}return result}__name(mergeOverrideWithDependencies,"mergeOverrideWithDependencies");const nameMap={[l.Editor]:"Editor",[l.Owner]:"Owner",[l.Reader]:"Reader",[l.UNRECOGNIZED]:"UNRECOGNIZED"},createDefaultUser=__name(type2=>type2?{userID:`${nameMap[type2]}_${Tools.generateRandomId(8)}`,name:nameMap[type2],avatar:""}:{userID:"",name:"",avatar:"",anonymous:!0,canBindAnonymous:!1},"createDefaultUser"),isDevRole=__name((userId,type2)=>userId.startsWith(nameMap[type2]),"isDevRole");var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),_a11;exports.UserManagerService=(_a11=class{constructor(){__publicField(this,"_model",new Map);__publicField(this,"_userChange$",new rxjs.Subject);__publicField(this,"userChange$",this._userChange$.asObservable());__publicField(this,"_currentUser$",new rxjs.BehaviorSubject(createDefaultUser()));__publicField(this,"currentUser$",this._currentUser$.asObservable())}getCurrentUser(){return this._currentUser$.getValue()}setCurrentUser(user){this.addUser(user),this._currentUser$.next(user)}addUser(user){this._model.set(user.userID,user),this._userChange$.next({type:"add",user})}getUser(userId,callBack){const user=this._model.get(userId);if(user)return user;callBack&&callBack()}delete(userId){const user=this.getUser(userId);this._model.delete(userId),user&&this._userChange$.next({type:"delete",user})}clear(){this._model.clear(),this._userChange$.next({type:"clear"})}list(){return Array.from(this._model.values())}},__name(_a11,"UserManagerService"),_a11);exports.UserManagerService=__decorateClass$1([OnLifecycle(LifecycleStages.Starting,exports.UserManagerService)],exports.UserManagerService);var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam"),_a12;exports.AuthzIoLocalService=(_a12=class{constructor(_resourceManagerService,_userManagerService){__publicField(this,"_permissionMap",new Map([]));this._resourceManagerService=_resourceManagerService,this._userManagerService=_userManagerService,this._initSnapshot(),this._initDefaultUser()}_initDefaultUser(){const currentUser=this._userManagerService.getCurrentUser();currentUser&&currentUser.userID||this._userManagerService.setCurrentUser(createDefaultUser(l.Owner))}_getRole(type2){const user=this._userManagerService.getCurrentUser();return user?isDevRole(user.userID,type2):!1}_initSnapshot(){this._resourceManagerService.registerPluginResource({toJson:__name(_unitId=>{const obj=[...this._permissionMap.keys()].reduce((r,k)=>{const v=this._permissionMap.get(k);return r[k]=v,r},{});return JSON.stringify(obj)},"toJson"),parseJson:__name(json=>JSON.parse(json),"parseJson"),pluginName:"SHEET_AuthzIoMockService_PLUGIN",businesses:[I.UNIVER_SHEET,I.UNIVER_DOC,I.UNIVER_SLIDE],onLoad:__name((_unitId,resource)=>{for(const key in resource)this._permissionMap.set(key,resource[key])},"onLoad"),onUnLoad:__name(()=>{this._permissionMap.clear()},"onUnLoad")})}async create(config){const id=Tools.generateRandomId(8);switch(config.objectType){case G.SelectRange:{const params=config.selectRangeObject;this._permissionMap.set(id,{...params,objectType:config.objectType});break}case G.Worksheet:{const params=config.worksheetObject;this._permissionMap.set(id,{...params,objectType:config.objectType,readScope:L.SomeCollaborator})}}return id}async allowed(config){var _a13;if(this._permissionMap.has(config.objectID)){const rule=this._permissionMap.get(config.objectID);if(rule&&rule.objectType===G.Worksheet)return(_a13=rule==null?void 0:rule.strategies)==null?void 0:_a13.map(s=>({action:s.action,allowed:s.role===l.Editor}))}return config.actions.map(a=>({action:a,allowed:this._getRole(l.Owner)||this._getRole(l.Editor)}))}async batchAllowed(config){const user=this._userManagerService.getCurrentUser(),defaultValue=config.map(item=>({unitID:item.unitID,objectID:item.objectID,actions:item.actions.map(action=>({action,allowed:!1}))}));return user&&(isDevRole(user.userID,l.Owner)||isDevRole(user.userID,l.Editor))?config.map(item=>({unitID:item.unitID,objectID:item.objectID,actions:item.actions.map(action=>({action,allowed:!0}))})):defaultValue}async list(config){const result=[];return config.objectIDs.forEach(objectID=>{const rule=this._permissionMap.get(objectID);if(rule){const item={objectID,unitID:config.unitID,objectType:rule.objectType,name:rule.name,shareOn:!1,shareRole:l.Owner,shareScope:-1,creator:createDefaultUser(l.Owner),strategies:[],actions:config.actions.map(a=>({action:a,allowed:this._getRole(l.Owner)||this._getRole(l.Editor)}))};result.push(item)}}),result}async listCollaborators(){return[]}async listRoles(){return{roles:[],actions:[]}}async deleteCollaborator(){}async update(config){}async updateCollaborator(){}async createCollaborator(){}async putCollaborators(config){}},__name(_a12,"AuthzIoLocalService"),_a12);exports.AuthzIoLocalService=__decorateClass([__decorateParam(0,IResourceManagerService),__decorateParam(1,Inject(exports.UserManagerService))],exports.AuthzIoLocalService);const IAuthzIoService=createIdentifier("IAuthzIoIoService"),_Univer=class _Univer{constructor(config={},parentInjector){__publicField(this,"_startedTypes",new Set);__publicField(this,"_injector");const injector=this._injector=createUniverInjector(parentInjector,config==null?void 0:config.override),{theme,locale,locales,logLevel}=config;theme&&this._injector.get(ThemeService).setTheme(theme),locales&&this._injector.get(LocaleService).load(locales),locale&&this._injector.get(LocaleService).setLocale(locale),logLevel&&this._injector.get(ILogService).setLogLevel(logLevel),this._init(injector)}get _univerInstanceService(){return this._injector.get(IUniverInstanceService)}get _pluginService(){return this._injector.get(exports.PluginService)}__getInjector(){return this._injector}dispose(){this._injector.dispose()}setLocale(locale){this._injector.get(LocaleService).setLocale(locale)}createUnit(type2,data){return this._univerInstanceService.createUnit(type2,data)}createUniverSheet(data){return this._univerInstanceService.createUnit(I.UNIVER_SHEET,data)}createUniverDoc(data){return this._univerInstanceService.createUnit(I.UNIVER_DOC,data)}createUniverSlide(data){return this._univerInstanceService.createUnit(I.UNIVER_SLIDE,data)}_init(injector){this._univerInstanceService.registerCtorForType(I.UNIVER_SHEET,exports.Workbook),this._univerInstanceService.registerCtorForType(I.UNIVER_DOC,DocumentDataModel),this._univerInstanceService.registerCtorForType(I.UNIVER_SLIDE,SlideDataModel);const univerInstanceService=injector.get(IUniverInstanceService);univerInstanceService.__setCreateHandler((type2,data,ctor)=>{if(!this._startedTypes.has(type2)){this._pluginService.startPluginForType(type2),this._startedTypes.add(type2);const model2=injector.createInstance(ctor,data);return univerInstanceService.__addUnit(model2),this._tryProgressToReady(),model2}const model=injector.createInstance(ctor,data);return univerInstanceService.__addUnit(model),model})}_tryProgressToReady(){this._injector.get(exports.LifecycleService).stage<LifecycleStages.Ready&&(this._injector.get(exports.LifecycleService).stage=LifecycleStages.Ready)}registerPlugin(plugin,config){this._pluginService.registerPlugin(plugin,config)}};__name(_Univer,"Univer");let Univer=_Univer;function createUniverInjector(parentInjector,override){const dependencies=mergeOverrideWithDependencies([[ErrorService],[LocaleService],[ThemeService],[exports.LifecycleService],[exports.LifecycleInitializerService],[exports.PluginService],[exports.UserManagerService],[IUniverInstanceService,{useClass:exports.UniverInstanceService}],[IPermissionService,{useClass:PermissionService}],[ILogService,{useClass:DesktopLogService,lazy:!0}],[ICommandService,{useClass:exports.CommandService}],[IUndoRedoService,{useClass:exports.LocalUndoRedoService,lazy:!0}],[IConfigService,{useClass:ConfigService}],[IContextService,{useClass:ContextService}],[IResourceManagerService,{useClass:ResourceManagerService,lazy:!0}],[IResourceLoaderService,{useClass:ResourceLoaderService,lazy:!0}],[IAuthzIoService,{useClass:exports.AuthzIoLocalService,lazy:!0}]],override);return parentInjector?parentInjector.createChild(dependencies):new Injector(dependencies)}__name(createUniverInjector,"createUniverInjector");const isRangesEqual=__name((oldRanges,ranges)=>ranges.length===oldRanges.length&&!oldRanges.some(oldRange=>ranges.some(range=>!Rectangle.equals(range,oldRange))),"isRangesEqual"),isUnitRangesEqual=__name((oldRanges,ranges)=>ranges.length===oldRanges.length&&oldRanges.every((oldRange,i)=>{const current=ranges[i];return current.unitId===oldRange.unitId&&current.sheetId===oldRange.sheetId&&Rectangle.equals(oldRange.range,current.range)}),"isUnitRangesEqual");function shallowEqual(objA,objB){if(Object.is(objA,objB))return!0;if(typeof objA!="object"||!objA||typeof objB!="object"||!objB)return!1;const keysA=Object.keys(objA),keysB=Object.keys(objB);if(keysA.length!==keysB.length)return!1;const bHasOwnProperty=Object.prototype.hasOwnProperty.bind(objB);for(let idx=0;idx<keysA.length;idx++){const key=keysA[idx];if(!bHasOwnProperty(key))return!1;const valueA=objA[key],valueB=objB[key];if(valueA!==valueB)return!1}return!0}__name(shallowEqual,"shallowEqual");function isNumeric(str){return/^-?\d+(\.\d+)?$/.test(str)}__name(isNumeric,"isNumeric");function isSafeNumeric(str){return isNumeric(str)?Number(str)<=Number.MAX_SAFE_INTEGER:!1}__name(isSafeNumeric,"isSafeNumeric");function isBooleanString(str){return["true","false"].includes(str.toLowerCase())}__name(isBooleanString,"isBooleanString");function mergeSets(s1,s2){return s2.forEach(s=>s1.add(s)),s1}__name(mergeSets,"mergeSets");function throttle(fn,wait=16){let lastTime=0,timer=null;return __name(function(...args){const now=Date.now();now-lastTime<wait?(timer&&clearTimeout(timer),timer=setTimeout(()=>{lastTime=now,fn.apply(this,args)},wait)):(lastTime=now,fn.apply(this,args))},"throttled")}__name(throttle,"throttle");function requestImmediateMacroTask(callback){const channel=new MessageChannel;let cancelled=!1;const hanlder=__name(()=>{cancelled||callback()},"hanlder");return channel.port1.onmessage=hanlder,channel.port2.postMessage(null),()=>{cancelled=!0,channel.port1.close(),channel.port2.close()}}__name(requestImmediateMacroTask,"requestImmediateMacroTask");var DataValidationRenderMode=(DataValidationRenderMode2=>(DataValidationRenderMode2[DataValidationRenderMode2.TEXT=0]="TEXT",DataValidationRenderMode2[DataValidationRenderMode2.ARROW=1]="ARROW",DataValidationRenderMode2[DataValidationRenderMode2.CUSTOM=2]="CUSTOM",DataValidationRenderMode2))(DataValidationRenderMode||{});function replaceInDocumentBody(body,query,target){if(query==="")return body;const mockDocumentData={id:"mock-id",body,documentStyle:{}},documentDataModel=new DocumentDataModel(mockDocumentData),queryLen=query.length;let index2;for(;(index2=documentDataModel.getBody().dataStream.indexOf(query))>=0;){const textX=new TextX,jsonX=JSONX.getInstance();if(index2>0&&textX.retain(index2),target.length>0){const sliceBody=documentDataModel.sliceBody(index2,index2+queryLen),replaceBody={dataStream:target};Array.isArray(sliceBody==null?void 0:sliceBody.textRuns)&&sliceBody.textRuns.length&&(replaceBody.textRuns=[{...sliceBody.textRuns[0],st:0,ed:target.length}]),textX.insert(target.length,replaceBody)}textX.delete(queryLen),documentDataModel.apply(jsonX.editOp(textX.serialize()))}const newBody=documentDataModel.getBody();return documentDataModel.dispose(),newBody}__name(replaceInDocumentBody,"replaceInDocumentBody");const _EventState=class _EventState{constructor(){__publicField(this,"skipNextObservers",!1);__publicField(this,"lastReturnValue");__publicField(this,"isStopPropagation",!1)}stopPropagation(){this.isStopPropagation=!0}};__name(_EventState,"EventState");let EventState=_EventState;const _EventSubject=class _EventSubject extends rxjs.Subject{constructor(){super(...arguments);__publicField(this,"_sortedObservers",[])}subscribe(){throw new Error("[EventSubject]: please use `subscribeEvent` instead of `subscribe` method for `EventSubject`.")}next(){throw new Error("[EventSubject]: please use `emitEvent` instead of `next` method for `EventSubject`.")}unsubscribe(){super.unsubscribe(),this._sortedObservers.length=0}complete(){super.complete(),this._sortedObservers.length=0}subscribeEvent(observer){let ob;typeof observer=="function"?ob={next:__name(([evt,state])=>observer(evt,state),"next")}:ob=observer;const subscription=super.subscribe(ob);return this._sortedObservers.push(ob),this._sortedObservers.sort((a,b)=>{var _a13,_b2;return((_a13=a.priority)!=null?_a13:0)-((_b2=b.priority)!=null?_b2:0)}),subscription.add(()=>this._sortedObservers=this._sortedObservers.filter(o=>o!==ob)),subscription}clearObservers(){this._sortedObservers.forEach(observer=>{var _a13;return(_a13=observer.complete)==null?void 0:_a13.call(observer)}),this._sortedObservers.length=0}emitEvent(event){var _a13;if(!this.closed){const state=new EventState;state.lastReturnValue=event;for(const observer of this._sortedObservers){const value=(_a13=observer.next)==null?void 0:_a13.call(observer,[event,state]);if(state.lastReturnValue=value,state.skipNextObservers)return{handled:!0,lastReturnValue:state.lastReturnValue,stopPropagation:state.isStopPropagation}}return{handled:this._sortedObservers.length>0,lastReturnValue:state.lastReturnValue,stopPropagation:state.isStopPropagation}}throw new Error("[EventSubject]: cannot emit event on a closed subject.")}};__name(_EventSubject,"EventSubject");let EventSubject=_EventSubject;function fromEventSubject(subject$){return new rxjs.Observable(subscriber=>{const ob=subject$.subscribeEvent(evt=>{subscriber.next(evt)});return()=>ob.unsubscribe()})}__name(fromEventSubject,"fromEventSubject");const ILocalStorageService=createIdentifier("ILocalStorageService");function createInterceptorKey(key){return`sheet_interceptor_${key}`}__name(createInterceptorKey,"createInterceptorKey");const composeInterceptors=__name(interceptors=>function(initialValue,context){let index2=-1;function passThrough(i,v){if(i<=index2)throw new Error("[SheetInterceptorService]: next() called multiple times!");return index2=i,i===interceptors.length?v:interceptors[i].handler(v,context,passThrough.bind(null,i+1))}return __name(passThrough,"passThrough"),passThrough(0,initialValue)},"composeInterceptors"),_InterceptorManager=class _InterceptorManager{constructor(interceptorPoints){__publicField(this,"_interceptorsByName",new Map);__publicField(this,"_interceptorPoints");this._interceptorPoints=interceptorPoints}fetchThroughInterceptors(name){const key=name,interceptors=this._interceptorsByName.get(key);return composeInterceptors(interceptors||[])}intercept(name,interceptor){const key=name;this._interceptorsByName.has(key)||this._interceptorsByName.set(key,[]);const interceptors=this._interceptorsByName.get(key);return interceptors.push(interceptor),this._interceptorsByName.set(key,interceptors.sort((a,b)=>{var _a13,_b2;return((_a13=b.priority)!=null?_a13:0)-((_b2=a.priority)!=null?_b2:0)})),()=>remove(this._interceptorsByName.get(key),interceptor)}getInterceptPoints(){return this._interceptorPoints}};__name(_InterceptorManager,"InterceptorManager");let InterceptorManager=_InterceptorManager;const ISnapshotServerService=createIdentifier("univer.snapshot-server-service"),_ClientSnapshotServerService=class _ClientSnapshotServerService{constructor(){__publicField(this,"_sheetBlockCache",new Map)}getUnitOnRev(context,params){return Promise.resolve({snapshot:{unitID:"",type:I.UNIVER_SHEET,rev:0,workbook:void 0,doc:void 0},changesets:[],error:{code:N.OK,message:""}})}getSheetBlock(context,params){const block=this._sheetBlockCache.get(params.blockID);return Promise.resolve({block,error:{code:N.OK,message:""}})}fetchMissingChangesets(context,params){return Promise.resolve({changesets:[],error:{code:N.OK,message:""}})}getResourcesRequest(context,params){return Promise.resolve({resources:{},error:{code:N.OK,message:""}})}saveSnapshot(context,params){return Promise.resolve({error:{code:N.OK,message:""}})}saveSheetBlock(context,params){const{block}=params;return block?(this._sheetBlockCache.set(block.id,block),Promise.resolve({error:{code:N.OK,message:""},blockID:block.id})):Promise.resolve({error:{code:N.UNDEFINED,message:"block is required"},blockID:""})}saveChangeset(context,params){return Promise.resolve({error:{code:N.OK,message:""},concurrent:[]})}};__name(_ClientSnapshotServerService,"ClientSnapshotServerService");let ClientSnapshotServerService=_ClientSnapshotServerService;function b64EncodeUnicode(str){return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,(match,p1)=>String.fromCharCode(Number.parseInt(p1,16))))}__name(b64EncodeUnicode,"b64EncodeUnicode");function b64DecodeUnicode(str){return decodeURIComponent(Array.prototype.map.call(atob(str),c=>`%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}__name(b64DecodeUnicode,"b64DecodeUnicode");const textEncoder=new TextEncoder,textDecoder=new TextDecoder;function encodeWorksheetOtherMetas(worksheet){const cloned=Tools.deepClone(worksheet);return delete cloned.id,delete cloned.name,delete cloned.rowCount,delete cloned.columnCount,delete cloned.cellData,textEncoder.encode(JSON.stringify(cloned))}__name(encodeWorksheetOtherMetas,"encodeWorksheetOtherMetas");function encodeWorkbookOtherMetas(workbook){const cloned=Tools.deepClone(workbook);return delete cloned.id,delete cloned.rev,delete cloned.name,delete cloned.sheetOrder,delete cloned.sheets,textEncoder.encode(JSON.stringify(cloned))}__name(encodeWorkbookOtherMetas,"encodeWorkbookOtherMetas");function encodeDocOriginalMeta(document2){const cloned=Tools.deepClone(document2);return delete cloned.id,delete cloned.rev,delete cloned.title,delete cloned.resources,textEncoder.encode(JSON.stringify(cloned))}__name(encodeDocOriginalMeta,"encodeDocOriginalMeta");function decodeWorksheetOtherMetas(buffer){return JSON.parse(typeof buffer=="string"?b64DecodeUnicode(buffer):textDecoder.decode(buffer))}__name(decodeWorksheetOtherMetas,"decodeWorksheetOtherMetas");function decodePartOfCellData(buffer){return JSON.parse(typeof buffer=="string"?b64DecodeUnicode(buffer):textDecoder.decode(buffer))}__name(decodePartOfCellData,"decodePartOfCellData");function decodeDocOriginalMeta(buffer){return JSON.parse(typeof buffer=="string"?b64DecodeUnicode(buffer):textDecoder.decode(buffer))}__name(decodeDocOriginalMeta,"decodeDocOriginalMeta");const FRAGMENT_ROW_COUNT=256*20;function splitCellDataToBlocks(cellData,maxColumn){const utilObjectMatrix=new ObjectMatrix(cellData),length=utilObjectMatrix.getLength(),blocks=[];let i=0;for(;i<length;){const endRow=Math.min(i+FRAGMENT_ROW_COUNT,length-1),slice=utilObjectMatrix.getSlice(i,Math.min(i+FRAGMENT_ROW_COUNT,length-1),0,maxColumn),data=serializeCellDataSlice(slice);blocks.push({id:Tools.generateRandomId(19,"0123456789"),startRow:i,endRow,data}),i+=FRAGMENT_ROW_COUNT}return blocks}__name(splitCellDataToBlocks,"splitCellDataToBlocks");function serializeCellDataSlice(slice){const data=slice.getData();return textEncoder.encode(JSON.stringify(data))}__name(serializeCellDataSlice,"serializeCellDataSlice");async function generateTemporarySnap(context,workbook,unitID,rev,snapshotService){const blockMeta={},sheetMetas={};if(!await Promise.all(Object.entries(workbook.sheets).map(async([sheetID,worksheet])=>{const sheetMeta={id:worksheet.id,type:SheetTypes.GRID,name:worksheet.name,rowCount:worksheet.rowCount,columnCount:worksheet.columnCount,originalMeta:encodeWorksheetOtherMetas(worksheet)};if(sheetMetas[sheetID]=sheetMeta,worksheet.cellData){const sheetBlocks=splitCellDataToBlocks(worksheet.cellData,worksheet.rowCount),responses=await Promise.all(sheetBlocks.map(block=>snapshotService.saveSheetBlock(context,{unitID,type:I.UNIVER_SHEET,block})));if(responses.some(response=>{var _a13;return((_a13=response.error)==null?void 0:_a13.code)!==N.OK}))return!1;blockMeta[sheetID]={sheetID,blocks:responses.map(response=>response.blockID)}}return!0})))throw new Error("[transformWorkbookDataToSnapshot()]: Failed to save sheet blocks.");const originalMeta=encodeWorkbookOtherMetas(workbook),workbookMeta={unitID:workbook.id,rev,creator:"",name:workbook.name,sheetOrder:workbook.sheetOrder,sheets:sheetMetas,blockMeta,resources:workbook.resources||[],originalMeta};return{snapshotRes:{unitID,rev:workbookMeta.rev,type:I.UNIVER_SHEET,workbook:workbookMeta,doc:void 0}}}__name(generateTemporarySnap,"generateTemporarySnap");async function transformWorkbookDataToSnapshot(context,workbook,unitID,rev,snapshotService){var _a13,_b2;const blockMeta={},sheetMetas={};if(!await Promise.all(Object.entries(workbook.sheets).map(async([sheetID,worksheet])=>{const sheetMeta={id:worksheet.id,type:SheetTypes.GRID,name:worksheet.name,rowCount:worksheet.rowCount,columnCount:worksheet.columnCount,originalMeta:encodeWorksheetOtherMetas(worksheet)};if(sheetMetas[sheetID]=sheetMeta,worksheet.cellData){const sheetBlocks=splitCellDataToBlocks(worksheet.cellData,worksheet.rowCount),responses=await Promise.all(sheetBlocks.map(block=>snapshotService.saveSheetBlock(context,{unitID,type:I.UNIVER_SHEET,block})));if(responses.some(response=>{var _a14;return((_a14=response.error)==null?void 0:_a14.code)!==N.OK}))return!1;blockMeta[sheetID]={sheetID,blocks:responses.map(response=>response.blockID)}}return!0})))throw new Error("[transformWorkbookDataToSnapshot()]: Failed to save sheet blocks.");const originalMeta=encodeWorkbookOtherMetas(workbook),workbookMeta={unitID:workbook.id,rev,creator:"",name:workbook.name,sheetOrder:workbook.sheetOrder,sheets:sheetMetas,blockMeta,resources:workbook.resources||[],originalMeta},snapshot={unitID,rev:workbookMeta.rev,type:I.UNIVER_SHEET,workbook:workbookMeta,doc:void 0},saveResult=await snapshotService.saveSnapshot(context,{unitID,type:I.UNIVER_SHEET,snapshot});if(T(saveResult.error))throw new Error(`transformWorkbookDataToSnapshot(): Failed to save snapshot.
10
+ ErrorCode: ${(_a13=saveResult.error)==null?void 0:_a13.code}:${(_b2=saveResult.error)==null?void 0:_b2.message}`);return{snapshot}}__name(transformWorkbookDataToSnapshot,"transformWorkbookDataToSnapshot");function transformSnapshotToWorkbookData(snapshot,sheetBlocks,_context){const workbookMeta=snapshot.workbook;if(!workbookMeta)throw new Error("");const sheetMap={};Object.entries(workbookMeta.sheets).forEach(([sheetID,sheetMeta])=>{const otherMeta2=decodeWorksheetOtherMetas(sheetMeta.originalMeta);sheetMap[sheetID]={id:sheetMeta.id,name:sheetMeta.name,rowCount:sheetMeta.rowCount,columnCount:sheetMeta.columnCount,...otherMeta2}});const sheetBlocksMap=new Map;sheetBlocks.forEach(block=>{sheetBlocksMap.set(block.id,block)}),workbookMeta.blockMeta&&Object.entries(workbookMeta.blockMeta).forEach(([sheetID,blocksOfSheet])=>{var _a13;const worksheetConfig=sheetMap[sheetID];worksheetConfig.cellData={};const blocks=[];(_a13=blocksOfSheet.blocks)==null||_a13.forEach(blockID=>{const block=sheetBlocksMap.get(blockID);if(block)blocks.push(block);else throw new Error("")}),blocks.forEach(block=>{const partOfCellData=decodePartOfCellData(block.data);Object.entries(partOfCellData).forEach(([rowNumber,rowData])=>{const row=worksheetConfig.cellData[+rowNumber]={};Object.entries(rowData).forEach(([columnNumber,cellData])=>{row[+columnNumber]=cellData})})})});const otherMeta=decodeWorksheetOtherMetas(workbookMeta.originalMeta);return{id:snapshot.unitID||workbookMeta.unitID,rev:snapshot.rev||workbookMeta.rev,name:workbookMeta.name,sheetOrder:workbookMeta.sheetOrder,appVersion:"",locale:LocaleType.EN_US,sheets:sheetMap,styles:{},resources:workbookMeta.resources||[],...otherMeta}}__name(transformSnapshotToWorkbookData,"transformSnapshotToWorkbookData");function transformSnapshotToDocumentData(snapshot){const documentMeta=snapshot.doc;if(documentMeta==null)throw new Error("transformSnapshotToDocumentData(): snapshot.doc is undefined.");const{unitID,rev,name,originalMeta,resources=[]}=documentMeta,{body,documentStyle={},settings={},drawings={},drawingsOrder=[]}=decodeDocOriginalMeta(originalMeta);return{id:unitID,rev,locale:LocaleType.EN_US,title:name,body,documentStyle,settings,drawings,drawingsOrder,resources}}__name(transformSnapshotToDocumentData,"transformSnapshotToDocumentData");async function transformDocumentDataToSnapshot(context,document2,unitID,rev,snapshotService){var _a13,_b2,_c;const documentMeta={unitID:document2.id,rev,creator:"",name:(_a13=document2.title)!=null?_a13:"",resources:document2.resources||[],originalMeta:encodeDocOriginalMeta(document2)},snapshot={unitID,rev:documentMeta.rev,type:I.UNIVER_DOC,workbook:void 0,doc:documentMeta},saveResult=await snapshotService.saveSnapshot(context,{unitID,type:I.UNIVER_DOC,snapshot});if(T(saveResult.error))throw new Error(`transformDocumentDataToSnapshot(): Failed to save snapshot.
11
+ ErrorCode: ${(_b2=saveResult.error)==null?void 0:_b2.code}:${(_c=saveResult.error)==null?void 0:_c.message}`);return{snapshot}}__name(transformDocumentDataToSnapshot,"transformDocumentDataToSnapshot");async function getSheetBlocksFromSnapshot(snapshot,snapshotService){const workbookMeta=snapshot.workbook;if(!workbookMeta)throw new Error("Workbook metadata is not available");const blocks=[],promises=[];return Object.entries(workbookMeta.blockMeta).forEach(([sheetID,blocksOfSheet])=>{const blockPromises=blocksOfSheet.blocks.map(async blockID=>{const params={unitID:workbookMeta.unitID,type:I.UNIVER_SHEET,blockID},{block}=await snapshotService.getSheetBlock({},params);if(block)blocks.push(block);else throw new Error("Block not found")});promises.push(...blockPromises)}),await Promise.all(promises),blocks}__name(getSheetBlocksFromSnapshot,"getSheetBlocksFromSnapshot");var DataValidationErrorStyle=(DataValidationErrorStyle2=>(DataValidationErrorStyle2[DataValidationErrorStyle2.INFO=0]="INFO",DataValidationErrorStyle2[DataValidationErrorStyle2.STOP=1]="STOP",DataValidationErrorStyle2[DataValidationErrorStyle2.WARNING=2]="WARNING",DataValidationErrorStyle2))(DataValidationErrorStyle||{}),DataValidationImeMode=(DataValidationImeMode2=>(DataValidationImeMode2[DataValidationImeMode2.DISABLED=0]="DISABLED",DataValidationImeMode2[DataValidationImeMode2.FULL_ALPHA=1]="FULL_ALPHA",DataValidationImeMode2[DataValidationImeMode2.FULL_HANGUL=2]="FULL_HANGUL",DataValidationImeMode2[DataValidationImeMode2.FULL_KATAKANA=3]="FULL_KATAKANA",DataValidationImeMode2[DataValidationImeMode2.HALF_ALPHA=4]="HALF_ALPHA",DataValidationImeMode2[DataValidationImeMode2.HALF_HANGUL=5]="HALF_HANGUL",DataValidationImeMode2[DataValidationImeMode2.HALF_KATAKANA=6]="HALF_KATAKANA",DataValidationImeMode2[DataValidationImeMode2.HIRAGANA=7]="HIRAGANA",DataValidationImeMode2[DataValidationImeMode2.NO_CONTROL=8]="NO_CONTROL",DataValidationImeMode2[DataValidationImeMode2.OFF=9]="OFF",DataValidationImeMode2[DataValidationImeMode2.ON=10]="ON",DataValidationImeMode2))(DataValidationImeMode||{}),DataValidationOperator=(DataValidationOperator2=>(DataValidationOperator2.BETWEEN="between",DataValidationOperator2.EQUAL="equal",DataValidationOperator2.GREATER_THAN="greaterThan",DataValidationOperator2.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",DataValidationOperator2.LESS_THAN="lessThan",DataValidationOperator2.LESS_THAN_OR_EQUAL="lessThanOrEqual",DataValidationOperator2.NOT_BETWEEN="notBetween",DataValidationOperator2.NOT_EQUAL="notEqual",DataValidationOperator2))(DataValidationOperator||{}),DataValidationType=(DataValidationType2=>(DataValidationType2.CUSTOM="custom",DataValidationType2.LIST="list",DataValidationType2.LIST_MULTIPLE="listMultiple",DataValidationType2.NONE="none",DataValidationType2.TEXT_LENGTH="textLength",DataValidationType2.DATE="date",DataValidationType2.TIME="time",DataValidationType2.WHOLE="whole",DataValidationType2.DECIMAL="decimal",DataValidationType2.CHECKBOX="checkbox",DataValidationType2))(DataValidationType||{}),DataValidationStatus=(DataValidationStatus2=>(DataValidationStatus2.VALID="valid",DataValidationStatus2.INVALID="invalid",DataValidationStatus2.VALIDATING="validating",DataValidationStatus2))(DataValidationStatus||{});const skipParseTagNames=["script","style","meta","comment","link"];function nameCharacterCheck(name){return!(name.length===0||name.length>31||name.startsWith("'")||name.endsWith("'")||/[:\\\/\?\*\[\]]/.test(name))}__name(nameCharacterCheck,"nameCharacterCheck");installShims();exports.ABCToNumber=ABCToNumber;exports.AbsoluteRefType=AbsoluteRefType;exports.ActionIterator=ActionIterator;exports.AlignTypeH=AlignTypeH;exports.AlignTypeV=AlignTypeV;exports.ArrangeTypeEnum=ArrangeTypeEnum;exports.ArrowsAndMarkersShapes=ArrowsAndMarkersShapes;exports.AutoFillSeries=AutoFillSeries;exports.BaselineOffset=BaselineOffset;exports.BasicShapes=BasicShapes;exports.BlockType=BlockType;exports.BooleanNumber=BooleanNumber;exports.BorderStyleTypes=BorderStyleTypes;exports.BorderType=BorderType;exports.BulletAlignment=BulletAlignment;exports.COLORS=COLORS;exports.CellValueType=CellValueType;exports.ClientSnapshotServerService=ClientSnapshotServerService;exports.Color=Color;exports.ColorBuilder=ColorBuilder;exports.ColorKit=ColorKit;exports.ColorType=ColorType;exports.ColumnSeparatorType=ColumnSeparatorType;exports.CommandType=CommandType;exports.CommonHideTypes=CommonHideTypes;exports.ConfigService=ConfigService;exports.ContentAlignment=ContentAlignment;exports.ContextService=ContextService;exports.CopyPasteType=CopyPasteType;exports.CustomDecorationType=CustomDecorationType;exports.CustomRangeType=CustomRangeType;exports.DEFAULT_CELL=DEFAULT_CELL;exports.DEFAULT_DOC=DEFAULT_DOC;exports.DEFAULT_DOCUMENT_SUB_COMPONENT_ID=DEFAULT_DOCUMENT_SUB_COMPONENT_ID;exports.DEFAULT_EMPTY_DOCUMENT_VALUE=DEFAULT_EMPTY_DOCUMENT_VALUE;exports.DEFAULT_RANGE=DEFAULT_RANGE;exports.DEFAULT_RANGE_ARRAY=DEFAULT_RANGE_ARRAY;exports.DEFAULT_SELECTION=DEFAULT_SELECTION;exports.DEFAULT_SLIDE=DEFAULT_SLIDE;exports.DEFAULT_STYLES=DEFAULT_STYLES;exports.DEFAULT_WORKSHEET_COLUMN_COUNT=DEFAULT_WORKSHEET_COLUMN_COUNT;exports.DEFAULT_WORKSHEET_COLUMN_COUNT_KEY=DEFAULT_WORKSHEET_COLUMN_COUNT_KEY;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY=DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH=DEFAULT_WORKSHEET_COLUMN_WIDTH;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY=DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY;exports.DEFAULT_WORKSHEET_ROW_COUNT=DEFAULT_WORKSHEET_ROW_COUNT;exports.DEFAULT_WORKSHEET_ROW_COUNT_KEY=DEFAULT_WORKSHEET_ROW_COUNT_KEY;exports.DEFAULT_WORKSHEET_ROW_HEIGHT=DEFAULT_WORKSHEET_ROW_HEIGHT;exports.DEFAULT_WORKSHEET_ROW_HEIGHT_KEY=DEFAULT_WORKSHEET_ROW_HEIGHT_KEY;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=DEFAULT_WORKSHEET_ROW_TITLE_WIDTH;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY=DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY;exports.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;exports.DOCS_NORMAL_EDITOR_UNIT_ID_KEY=DOCS_NORMAL_EDITOR_UNIT_ID_KEY;exports.DOCS_ZEN_EDITOR_UNIT_ID_KEY=DOCS_ZEN_EDITOR_UNIT_ID_KEY;exports.DashStyleType=DashStyleType;exports.DataStreamTreeNodeType=DataStreamTreeNodeType;exports.DataStreamTreeTokenType=DataStreamTreeTokenType;exports.DataValidationErrorStyle=DataValidationErrorStyle;exports.DataValidationImeMode=DataValidationImeMode;exports.DataValidationOperator=DataValidationOperator;exports.DataValidationRenderMode=DataValidationRenderMode;exports.DataValidationStatus=DataValidationStatus;exports.DataValidationType=DataValidationType;exports.DependentOn=DependentOn;exports.DesktopLogService=DesktopLogService;exports.DeveloperMetadataVisibility=DeveloperMetadataVisibility;exports.Dimension=Dimension;exports.Direction=Direction;exports.Disposable=Disposable;exports.DisposableCollection=DisposableCollection;exports.DocStyleType=DocStyleType;exports.DocumentDataModel=DocumentDataModel;exports.DocumentFlavor=DocumentFlavor;exports.DrawingTypeEnum=DrawingTypeEnum;exports.EDITOR_ACTIVATED=EDITOR_ACTIVATED;exports.EXTENSION_NAMES=EXTENSION_NAMES;exports.Entry=Entry;exports.EntryIterator=EntryIterator;exports.ErrorService=ErrorService;exports.EventState=EventState;exports.EventSubject=EventSubject;exports.FOCUSING_COMMON_DRAWINGS=FOCUSING_COMMON_DRAWINGS;exports.FOCUSING_DOC=FOCUSING_DOC;exports.FOCUSING_EDITOR_BUT_HIDDEN=FOCUSING_EDITOR_BUT_HIDDEN;exports.FOCUSING_EDITOR_INPUT_FORMULA=FOCUSING_EDITOR_INPUT_FORMULA;exports.FOCUSING_EDITOR_STANDALONE=FOCUSING_EDITOR_STANDALONE;exports.FOCUSING_FORMULA_EDITOR=FOCUSING_FORMULA_EDITOR;exports.FOCUSING_SHEET=FOCUSING_SHEET;exports.FOCUSING_SLIDE=FOCUSING_SLIDE;exports.FOCUSING_UNIVER_EDITOR=FOCUSING_UNIVER_EDITOR;exports.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE=FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE;exports.FollowNumberWithType=FollowNumberWithType;exports.FontItalic=FontItalic;exports.FontStyleType=FontStyleType;exports.FontWeight=FontWeight;exports.FormatType=FormatType;exports.GlyphType=GlyphType;exports.GridType=GridType;exports.HLSColor=HLSColor;exports.HorizontalAlign=HorizontalAlign;exports.IAuthzIoService=IAuthzIoService;exports.ICommandService=ICommandService;exports.IConfigService=IConfigService;exports.IContextService=IContextService;exports.ILocalStorageService=ILocalStorageService;exports.ILogService=ILogService;exports.IPermissionService=IPermissionService;exports.IResourceLoaderService=IResourceLoaderService;exports.IResourceManagerService=IResourceManagerService;exports.ISnapshotServerService=ISnapshotServerService;exports.IUndoRedoService=IUndoRedoService;exports.IUniverInstanceService=IUniverInstanceService;exports.Inject=Inject;exports.Injector=Injector;exports.InterceptorManager=InterceptorManager;exports.InterpolationPointType=InterpolationPointType;exports.JSON1=index$1;exports.JSONX=JSONX;exports.KeyIterator=KeyIterator;exports.LRUHelper=LRUHelper;exports.LRUMap=LRUMap;exports.LifecycleStages=LifecycleStages;exports.LocaleService=LocaleService;exports.LocaleType=LocaleType;exports.LogLevel=LogLevel;exports.MOVE_BUFFER_VALUE=MOVE_BUFFER_VALUE;exports.Many=Many;exports.MemoryCursor=MemoryCursor;exports.NamedStyleType=NamedStyleType;exports.NilCommand=NilCommand;exports.NumberUnitType=NumberUnitType;exports.ObjectMatrix=ObjectMatrix;exports.ObjectRelativeFromH=ObjectRelativeFromH;exports.ObjectRelativeFromV=ObjectRelativeFromV;exports.OnLifecycle=OnLifecycle;exports.Optional=Optional;exports.OtherShapes=OtherShapes;exports.PRESET_LIST_TYPE=PRESET_LIST_TYPE;exports.PageElementType=PageElementType;exports.PageOrientType=PageOrientType;exports.PageType=PageType;exports.ParagraphElementType=ParagraphElementType;exports.PermissionService=PermissionService;exports.PermissionStatus=PermissionStatus;exports.Plugin=Plugin;exports.PositionedObjectLayoutType=PositionedObjectLayoutType;exports.PresetListType=PresetListType;exports.ProtectionType=ProtectionType;exports.RANGE_TYPE=RANGE_TYPE;exports.RCDisposable=RCDisposable;exports.RGBA_PAREN=RGBA_PAREN;exports.RGB_PAREN=RGB_PAREN;exports.ROTATE_BUFFER_VALUE=ROTATE_BUFFER_VALUE;exports.Range=Range;exports.Rectangle=Rectangle;exports.RediConsumer=RediConsumer;exports.RediContext=RediContext;exports.RediError=RediError;exports.RediProvider=RediProvider;exports.RedoCommand=RedoCommand;exports.RedoCommandId=RedoCommandId;exports.RefAlias=RefAlias;exports.Registry=Registry;exports.RegistryAsMap=RegistryAsMap;exports.RelativeDate=RelativeDate;exports.RelativeSlideLink=RelativeSlideLink;exports.ResourceManagerService=ResourceManagerService;exports.RgbColor=RgbColor;exports.RxDisposable=RxDisposable;exports.SectionType=SectionType;exports.Self=Self;exports.SheetTypes=SheetTypes;exports.SheetViewModel=SheetViewModel;exports.SkipSelf=SkipSelf;exports.SliceBodyType=SliceBodyType;exports.SlideDataModel=SlideDataModel;exports.SpacingRule=SpacingRule;exports.SpecialShapes=SpecialShapes;exports.Styles=Styles;exports.THEME_COLORS=THEME_COLORS;exports.TabStopAlignment=TabStopAlignment;exports.TextDecoration=TextDecoration;exports.TextDirection=TextDirection;exports.TextDirectionType=TextDirectionType;exports.TextX=TextX;exports.TextXActionType=TextXActionType;exports.ThemeColor=ThemeColor;exports.ThemeColorType=ThemeColorType;exports.ThemeColors=ThemeColors;exports.ThemeService=ThemeService;exports.Tools=Tools;exports.UndoCommand=UndoCommand;exports.UndoCommandId=UndoCommandId;exports.UnitModel=UnitModel;exports.Univer=Univer;exports.UniverInstanceType=I;exports.UpdateDocsAttributeType=UpdateDocsAttributeType;exports.ValueIterator=ValueIterator;exports.VerticalAlign=VerticalAlign;exports.WidthType=WidthType;exports.WithDependency=WithDependency;exports.WithNew=WithNew;exports.Worksheet=Worksheet;exports.WrapStrategy=WrapStrategy;exports.WrapTextType=WrapTextType;exports.afterInitApply=afterInitApply;exports.b64DecodeUnicode=b64DecodeUnicode;exports.b64EncodeUnicode=b64EncodeUnicode;exports.binarySearchArray=binarySearchArray;exports.cellToRange=cellToRange;exports.characterSpacingControlType=characterSpacingControlType;exports.checkForSubstrings=checkForSubstrings;exports.checkIfMove=checkIfMove;exports.checkParagraphHasBullet=checkParagraphHasBullet;exports.checkParagraphHasIndent=checkParagraphHasIndent;exports.checkParagraphHasIndentByStyle=checkParagraphHasIndentByStyle;exports.codeToBlob=codeToBlob;exports.composeBody=composeBody;exports.composeInterceptors=composeInterceptors;exports.concatMatrixArray=concatMatrixArray;exports.connectDependencies=connectDependencies;exports.connectInjector=connectInjector;exports.convertBodyToHtml=convertBodyToHtml;exports.covertTextRunToHtml=covertTextRunToHtml;exports.createDefaultUser=createDefaultUser;exports.createIdentifier=createIdentifier;exports.createInterceptorKey=createInterceptorKey;exports.createInternalEditorID=createInternalEditorID;exports.createRowColIter=createRowColIter;exports.debounce=debounce;exports.dedupe=dedupe;exports.deepCompare=deepCompare;exports.deleteContent=deleteContent;exports.extractPureTextFromCell=extractPureTextFromCell;exports.forwardRef=forwardRef;exports.fromCallback=fromCallback;exports.fromEventSubject=fromEventSubject;exports.fromObservable=fromObservable;exports.generateRandomId=generateRandomId;exports.generateTemporarySnap=generateTemporarySnap;exports.getArrayLength=getArrayLength;exports.getBodySlice=getBodySlice;exports.getBodySliceHtml=getBodySliceHtml;exports.getBorderStyleType=getBorderStyleType;exports.getCellInfoInMergeData=getCellInfoInMergeData;exports.getCellValueType=getCellValueType;exports.getColorStyle=getColorStyle;exports.getCustomDecorationSlice=getCustomDecorationSlice;exports.getCustomRangeSlice=getCustomRangeSlice;exports.getDocsUpdateBody=getDocsUpdateBody;exports.getReverseDirection=getReverseDirection;exports.getSheetBlocksFromSnapshot=getSheetBlocksFromSnapshot;exports.getWorksheetUID=getWorksheetUID;exports.groupBy=groupBy;exports.handleStyleToString=handleStyleToString;exports.hashAlgorithm=hashAlgorithm;exports.horizontalLineSegmentsSubtraction=horizontalLineSegmentsSubtraction;exports.insertMatrixArray=insertMatrixArray;exports.insertTextToContent=insertTextToContent;exports.isAsyncDependencyItem=isAsyncDependencyItem;exports.isAsyncHook=isAsyncHook;exports.isBlackColor=isBlackColor;exports.isBooleanString=isBooleanString;exports.isCellCoverable=isCellCoverable;exports.isCellV=isCellV;exports.isClassDependencyItem=isClassDependencyItem;exports.isCtor=isCtor;exports.isDisposable=isDisposable;exports.isEmptyCell=isEmptyCell;exports.isFactoryDependencyItem=isFactoryDependencyItem;exports.isFormulaId=isFormulaId;exports.isFormulaString=isFormulaString;exports.isICellData=isICellData;exports.isInternalEditorID=isInternalEditorID;exports.isNullCell=isNullCell;exports.isNumeric=isNumeric;exports.isRangesEqual=isRangesEqual;exports.isRealNum=isRealNum;exports.isSafeNumeric=isSafeNumeric;exports.isSameStyleTextRun=isSameStyleTextRun;exports.isUnitRangesEqual=isUnitRangesEqual;exports.isValidRange=isValidRange;exports.isValueDependencyItem=isValueDependencyItem;exports.isWhiteColor=isWhiteColor;exports.makeArray=makeArray;exports.makeCellRangeToRangeData=makeCellRangeToRangeData;exports.makeCellToSelection=makeCellToSelection;exports.mergeOverrideWithDependencies=mergeOverrideWithDependencies;exports.mergeSets=mergeSets;exports.mergeWorksheetSnapshotWithDefault=mergeWorksheetSnapshotWithDefault;exports.moveMatrixArray=moveMatrixArray;exports.moveRangeByOffset=moveRangeByOffset;exports.nameCharacterCheck=nameCharacterCheck;exports.normalizeBody=normalizeBody;exports.normalizeTextRuns=normalizeTextRuns;exports.numberToABC=numberToABC;exports.numberToListABC=numberToListABC;exports.orderSearchArray=orderSearchArray;exports.queryObjectMatrix=queryObjectMatrix;exports.remove=remove;exports.repeatStringNumTimes=repeatStringNumTimes;exports.replaceInDocumentBody=replaceInDocumentBody;exports.requestImmediateMacroTask=requestImmediateMacroTask;exports.rotate=rotate;exports.runOnLifecycle=runOnLifecycle;exports.searchArray=searchArray;exports.selectionToArray=selectionToArray;exports.sequence=sequence;exports.sequenceAsync=sequenceAsync;exports.sequenceExecute=sequenceExecute;exports.sequenceExecuteAsync=sequenceExecuteAsync;exports.setDependencies=setDependencies;exports.shallowEqual=shallowEqual;exports.skipParseTagNames=skipParseTagNames;exports.sliceMatrixArray=sliceMatrixArray;exports.sortRules=sortRules;exports.sortRulesByDesc=sortRulesByDesc;exports.sortRulesFactory=sortRulesFactory;exports.spliceArray=spliceArray;exports.takeAfter=takeAfter;exports.textDecoder=textDecoder;exports.textEncoder=textEncoder;exports.throttle=throttle;exports.toDisposable=toDisposable;exports.transformDocumentDataToSnapshot=transformDocumentDataToSnapshot;exports.transformSnapshotToDocumentData=transformSnapshotToDocumentData;exports.transformSnapshotToWorkbookData=transformSnapshotToWorkbookData;exports.transformWorkbookDataToSnapshot=transformWorkbookDataToSnapshot;exports.updateAttributeByDelete=updateAttributeByDelete;exports.updateAttributeByInsert=updateAttributeByInsert;exports.useDependency=useDependency;exports.useDependencyContext=useDependencyContext;exports.useDependencyContextValue=useDependencyContextValue;exports.useDependencyValue=useDependencyValue;exports.useInjector=useInjector;exports.useObservable=useObservable;exports.useUpdateBinder=useUpdateBinder;