@odoo/o-spreadsheet 19.3.20 → 19.3.21
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.
|
@@ -111,7 +111,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
111
111
|
offset="offset"
|
|
112
112
|
direction="'vertical'"
|
|
113
113
|
onScroll.bind="onScroll"
|
|
114
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Am()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},lI=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:iI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},uI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=JP(this.env);setup(){sk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Rm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let dI={ROW:GP,COL:RP,CELL:TP,GROUP_HEADERS:UP,UNGROUP_HEADERS:WP};var fI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:CF,GridOverlay:VF,GridPopover:HF,HeadersOverlay:JF,MenuPopover:Oy,Autofill:XP,ClientTag:QP,Highlight:iI,Popover:wy,VerticalScrollBar:cI,HorizontalScrollBar:sI,TableResizer:uI,Selection:lI};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=JP(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(fT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Iy),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(py),this.sidePanel=O(YM),this.paintFormatStore=O(LF),this.clientFocusStore=O(qP),O(KP),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),XF({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=eI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),QF(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>GE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Lu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"Ctrl+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>bE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?IE(this.env):i&&!r&&PE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{RD.execute?.(this.env)},"Alt+T":()=>{TD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),JE(this.env)},"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey(`right`),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey(`left`),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey(`up`),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey(`down`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}zw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}zw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{..._m(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Rw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Tm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=dI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?kN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>JT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===$T(r.content[`text/html`]))yw(this.env,i);else{let e=QT(r.content);await bw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!DN(this.env,`COL`)&&!DN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(SM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}get clientsToDisplay(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getClientsToDisplay(e)}};let pI=new A;pI.add(`SPREADSHEET`,!1);var mI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(RF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=kd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},hI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:My};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=Sy();figureRegistry=Py;setup(){this.fullScreenFigureStore=O(fy);let e=O(Gd),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Py.get(this.figureUI.tag).Component}},gI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:BT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Og(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},_I=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},vI=class extends _I{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},yI=class extends vI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of ud(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=cd(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=ld(e)}e.borders=t}exportForExcel(e){this.export(e)}},bI=class extends vI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:if(!this.carousels[e.sheetId]?.[e.figureId])return`InvalidFigureId`;for(let t of e.definition.items)if(t.type===`chart`&&!this.getters.getChart(t.chartId))return`ChartDoesNotExist`;return`Success`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},xI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;baseNumberFormat=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Bc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}resetBaseNumber(){this.baseNumber=void 0,this.baseNumberFormat=void 0}squish(e,t){if(e.isFormula){if(Lo.getAll().some(t=>e.compiledFormula.usesSymbol(t)))return this.resetBaseFormula(),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions);let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0||e.format!==this.baseNumberFormat)return this.baseNumber=t,this.baseNumberFormat=e.format,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishCommand(e){if(e.content){let t=Bu(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:nc(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function SI(e){return[sn(e)]}function*CI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var wI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;e==null||e===``?(this.rebase(),n=`NOT_A_FORMULA`):n=this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=CI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``){this.rebase(),i=void 0;continue}else i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?SI(a):CI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Bc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break;case`COMBINE_OFFSET`:case`OFFSET_NUMBER`:break;default:throw Error(`Cannot unsquish an offset without a preceding base cell: ${i}`)}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Bc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Bc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=Vu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Bc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},TI=class extends vI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new ZM,i=new wI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of ud(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new xI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=cd(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=cd(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=ld(a),i.formats=ld(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Uu(a,i,r,n):Bu(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])au(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Bc||(r=Bc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Bu(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},EI=class extends vI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=tk.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=tk.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=tk.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=tk.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return tk.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function DI(e){return e===``?NaN:Number(e)}var OI=class extends vI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Gh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Bc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&DI(t)>=DI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&DI(t)>=DI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&DI(t)>=DI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Bc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},kI=class extends vI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>rc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of ac(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Bc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},AI=class extends vI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},jI=class extends vI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=vc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=yc(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Bb(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Bb(t,e,n.end+1);r.collapsed=!0}}}}}},MI=class extends vI{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},NI=class extends vI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},PI=class extends vI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},FI=class extends vI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:LI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...II(e))}}exportForExcel(e){this.export(e)}};function II(e){return Object.entries(e).map(([e,t])=>t?LI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function LI(e,t){return{...t.zone,id:e}}let RI=/^[\p{L}\p{N}_.]+$/u;var zI=class extends vI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!RI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Go.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},BI=class extends vI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new Dj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=zj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Bc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Ag(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Cg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},VI=class extends vI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Jy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===db(e)&&(n=db(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},HI=class extends vI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,Sc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[Sc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:_c(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[Sc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return bc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:_c(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>Cc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[Sc(n)],r[Sc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[Sc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return xc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[Sc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return mu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:pu(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},UI=class extends vI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},WI=class extends vI{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!oC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=sC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:WS.styleId}});break}}getTableStyle(e){if(pM[e])return pM[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!aC[e]&&!pM[e]}import(e){for(let e in aC)this.styles[e]=aC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=sC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)aC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},GI=class extends vI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||WS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Wj(Bc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return xM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return xM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=xM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||WS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,WS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},KI=class extends _I{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let qI=Io.mapping;function JI(e,t,n){return new YI(e,t,n).getParameters()}var YI=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(qI),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=this.getters.clipRangeToSheet(e)?.zone;if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},XI=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},ZI=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(QI),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)QI(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new XI(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function QI(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var $I=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},eL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new $I),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(sc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(sc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(sc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},tL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new eL){t=t.copy();let n=t.copy(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop();t.add(e);let i=e.zone,a=this.forest[e.sheetId];if(!a)continue;let o=new eL;for(let e=i.left;e<=i.right;e++){let t=a[e];if(!t)continue;let n=t.query(i);for(let e of n)o.add(e.dependents)}r.push(...o.difference(t)),n=n.difference(o)}for(let e of n)t.delete(e);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new ZI,this.forest[e][t]=n),n}},nL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=rL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function rL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var iL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=nL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},aL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),oL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new sL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new sL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},sL=class extends aL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},cL=class{resultsToArrayFormulas=new oL;arrayFormulasToResults=new ZM;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||lL}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let lL=[],uL=new A;uL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let dL=Object.freeze(Gu({value:null}));var fL=class{context;getters;compilationParams;evaluatedCells=new ZM;formulaDependencies=xt(new tL);blockedArrayFormulas=new iL({});spreadingRelations=new cL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||dL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,this.getters.clipRangesToSheet(t))}addDependencies(e,t){this.formulaDependencies().addDependencies(e,this.getters.clipRangesToSheet(t)),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new iL(e)}evaluateCells(e){let t=performance.now(),n=new eL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new eL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new cL,this.formulaDependencies=xt(()=>{let e=new tL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id),r=this.getters.clipRangesToSheet(n.compiledFormula.rangeDependencies);e.addDependencies(t,r)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new ZM;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Bc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=gL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?lo(r,mL):mL(r)}catch(e){return Ao(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new eL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new eL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new eL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}uL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...dL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?_L(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):zu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||No,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Gu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=gL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Gu(hL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Gu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Gu(hL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),pL(r,i,this.checkCollision(e)),pL(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Gu(hL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Gu(hL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return _L(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function pL(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function mL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function hL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:mL(e)}function gL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function _L(e){return Gu({...new Ii,origin:void 0},void 0,e)}var vL=class extends KI{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new fL(e.custom,this.getters)}beforeHandle(e){(_u.has(e.type)||yu.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?lo(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=cd(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let yL=new A;yL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Ab:Ob,hoverSvg:n?Ab:kb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),yL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:Tb(i),hoverSvg:Db(i),priority:2,horizontalAlign:`right`,size:kd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),yL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Nb[n].svg,priority:1,horizontalAlign:`left`,size:kd(r),margin:4,position:t}}}),yL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??_g.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?jb(s,!1):void 0,hoverSvg:o?jb(s,!0):void 0,position:t,onClick:Kg}}}),yL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:kd(r),margin:0,svg:n===`asc`?Eb(r):Tb(r),position:t,onClick:void 0}});var bL=class extends KI{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=yL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let xL=/"(#[0-9a-fA-F]{6})"/g;function SL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=CL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function CL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var wL=class extends KI{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return SL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(xL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},TL=class extends KI{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=xM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=cd(i,e.styles);t.styles[o]=n}if(a){let n=cd(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function EL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!If(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Ff(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var DL=class extends KI{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(_u.has(e.type)||bu.has(e.type)||vu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:wf(e)};if(!t)return{background:oe,fontColor:wf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||wf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ch(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=EL(e)}return r}},OL=class extends KI{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(_u.has(e.type)||bu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Bc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Wu(t,V));if(o.some(Eh))return!1;let s={...t,type:t.operator,values:o.map(wh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let kL={isValid:!0};var AL=class extends KI{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(_u.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:Wy.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return kL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:kL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Bc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||kL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of ac(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?kL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Eh))return;let c={...i,values:s.map(wh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Wu(r,V);let i=Bc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let jL=[`SUBTOTAL`,`PIVOT`];var ML=class extends KI{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of jL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of jL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of jL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},NL=class extends KI{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=_d();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return vd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let PL=`0.00%`;function FL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Sg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Ao(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=uj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=uj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=uj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=jg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Ao(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:PL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:PL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:PL}}asPercentOfParentRowTotal(e,t,n){let r=cj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:PL}}asPercentOfParentColumnTotal(e,t,n){let r=lj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:PL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!vj(i,n))return{value:``};let a=gj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:PL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=uj(this,n),u=xj(l),d=xj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:PL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:PL}:s===void 0?{value:M.NullError}:{value:s/o,format:PL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:PL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!vj(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=uj(this,n),u=xj(l),d=xj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=yj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=xj(dj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:dj(this,i,t.domain)})).filter(e=>vj(t,e.rowDomain)),l=Object.groupBy(c,e=>Cj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=xj(dj(this,i,e.domain)),a=l[Cj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=yj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=xj(dj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:dj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>vj(t,e.rowDomain));for(let e of l){let n=xj(e.rowDomain),i=wj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=xj(n),a=wj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=yj(this,e),{rowDomain:a,colDomain:o}=uj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=xj(c),d=wj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=wj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=xj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&rg.contains(n)){let t=ig(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=uj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=uj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?bj(this,t,n,r):_j(t,n,r);if(T(i,t))return`sameValue`;if(!i||!pj(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;zg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let IL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function LL(e){return IL.includes(e.type)}var RL=class extends KI{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new ZM;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(_u.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(LL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:$g();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new ZM,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=Gj(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=_F(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||Kj(t.compiledFormula,this.getters)===0)return Oj;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Oj;let{functionName:i,args:a}=r,o=a[0];if(!o)return Oj;let s=this.getters.getPivotId(o.toString());if(!s)return Oj;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Oj;try{if(i===`PIVOT`){let t=qg(this.getters.getPivotCoreDefinition(s),wh(a[1]),wh(a[2]),wh(a[3]),wh(a[4]),wh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:uj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Oj}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&zj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=uj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=FL(zj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:qg(this.getters.getPivotCoreDefinition(i),wh(n.args[1]),wh(n.args[2]),wh(n.args[3]),wh(n.args[4]),wh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},zL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},BL=class extends zL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of ZT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},VL=class extends BL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Ag(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of ZT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:ZT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
|
|
114
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Am()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},lI=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:iI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},uI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=JP(this.env);setup(){sk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Rm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let dI={ROW:GP,COL:RP,CELL:TP,GROUP_HEADERS:UP,UNGROUP_HEADERS:WP};var fI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:CF,GridOverlay:VF,GridPopover:HF,HeadersOverlay:JF,MenuPopover:Oy,Autofill:XP,ClientTag:QP,Highlight:iI,Popover:wy,VerticalScrollBar:cI,HorizontalScrollBar:sI,TableResizer:uI,Selection:lI};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=JP(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(fT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Iy),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(py),this.sidePanel=O(YM),this.paintFormatStore=O(LF),this.clientFocusStore=O(qP),O(KP),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),XF({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=eI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),QF(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>GE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Lu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"Ctrl+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>bE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?IE(this.env):i&&!r&&PE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{RD.execute?.(this.env)},"Alt+T":()=>{TD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),JE(this.env)},"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey(`right`),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey(`left`),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey(`up`),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey(`down`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}zw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}zw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{..._m(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Rw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Tm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=dI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?kN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>JT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===$T(r.content[`text/html`]))yw(this.env,i);else{let e=QT(r.content);await bw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!DN(this.env,`COL`)&&!DN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(SM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}get clientsToDisplay(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getClientsToDisplay(e)}};let pI=new A;pI.add(`SPREADSHEET`,!1);var mI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(RF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=kd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},hI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:My};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=Sy();figureRegistry=Py;setup(){this.fullScreenFigureStore=O(fy);let e=O(Gd),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Py.get(this.figureUI.tag).Component}},gI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:BT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Og(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},_I=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},vI=class extends _I{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},yI=class extends vI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of ud(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=cd(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=ld(e)}e.borders=t}exportForExcel(e){this.export(e)}},bI=class extends vI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:if(!this.carousels[e.sheetId]?.[e.figureId])return`InvalidFigureId`;for(let t of e.definition.items)if(t.type===`chart`&&!this.getters.getChart(t.chartId))return`ChartDoesNotExist`;return`Success`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},xI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;baseNumberFormat=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Bc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}resetBaseNumber(){this.baseNumber=void 0,this.baseNumberFormat=void 0}squish(e,t){if(e.isFormula){if(Lo.getAll().some(t=>e.compiledFormula.usesSymbol(t)))return this.resetBaseFormula(),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions);let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0||e.format!==this.baseNumberFormat)return this.baseNumber=t,this.baseNumberFormat=e.format,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishCommand(e){if(e.content){let t=Bu(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:nc(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function SI(e){return[sn(e)]}function*CI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var wI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;e==null||e===``?(this.rebase(),n=`NOT_A_FORMULA`):n=this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=CI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``){this.rebase(),i=void 0;continue}else i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?SI(a):CI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Bc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break;case`COMBINE_OFFSET`:case`OFFSET_NUMBER`:break;default:throw Error(`Cannot unsquish an offset without a preceding base cell: ${i}`)}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Bc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Bc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=Vu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Bc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},TI=class extends vI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new ZM,i=new wI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of ud(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new xI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=cd(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=cd(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=ld(a),i.formats=ld(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Uu(a,i,r,n):Bu(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])au(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Bc||(r=Bc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Bu(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},EI=class extends vI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=tk.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=tk.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=tk.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=tk.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return tk.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function DI(e){return e===``?NaN:Number(e)}var OI=class extends vI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Gh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Bc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&DI(t)>=DI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&DI(t)>=DI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&DI(t)>=DI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Bc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},kI=class extends vI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>rc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of ac(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Bc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},AI=class extends vI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},jI=class extends vI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=vc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=yc(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Bb(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Bb(t,e,n.end+1);r.collapsed=!0}}}}}},MI=class extends vI{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},NI=class extends vI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},PI=class extends vI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},FI=class extends vI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:LI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...II(e))}}exportForExcel(e){this.export(e)}};function II(e){return Object.entries(e).map(([e,t])=>t?LI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function LI(e,t){return{...t.zone,id:e}}let RI=/^[\p{L}\p{N}_.]+$/u;var zI=class extends vI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!RI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Go.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},BI=class extends vI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new Dj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=zj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Bc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Ag(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Cg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},VI=class extends vI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Jy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===db(e)&&(n=db(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},HI=class extends vI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,Sc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[Sc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:_c(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[Sc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return bc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:_c(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>Cc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[Sc(n)],r[Sc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[Sc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return xc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[Sc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return mu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:pu(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},UI=class extends vI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},WI=class extends vI{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!oC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=sC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:WS.styleId}});break}}getTableStyle(e){if(pM[e])return pM[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!aC[e]&&!pM[e]}import(e){for(let e in aC)this.styles[e]=aC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=sC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)aC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},GI=class extends vI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||WS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Wj(Bc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return xM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return xM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=xM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||WS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,WS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},KI=class extends _I{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let qI=Io.mapping;function JI(e,t,n){return new YI(e,t,n).getParameters()}var YI=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(qI),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=this.getters.clipRangeToSheet(e)?.zone;if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},XI=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},ZI=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(QI),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)QI(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new XI(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function QI(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var $I=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},eL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new $I),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(sc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(sc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(sc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},tL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new eL){t=t.copy();let n=t.copy(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop();t.add(e);let i=e.zone,a=this.forest[e.sheetId];if(!a)continue;let o=new eL;for(let e=i.left;e<=i.right;e++){let t=a[e];if(!t)continue;let n=t.query(i);for(let e of n)o.add(e.dependents)}r.push(...o.difference(t)),n=n.difference(o)}for(let e of n)t.delete(e);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new ZI,this.forest[e][t]=n),n}},nL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=rL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function rL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var iL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=nL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},aL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),oL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new sL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new sL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},sL=class extends aL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},cL=class{resultsToArrayFormulas=new oL;arrayFormulasToResults=new ZM;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||lL}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let lL=[],uL=new A;uL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let dL=Object.freeze(Gu({value:null}));var fL=class{context;getters;compilationParams;evaluatedCells=new ZM;formulaDependencies=xt(new tL);blockedArrayFormulas=new iL({});spreadingRelations=new cL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||dL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,this.getters.clipRangesToSheet(t))}addDependencies(e,t){this.formulaDependencies().addDependencies(e,this.getters.clipRangesToSheet(t)),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=JI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new iL(e)}evaluateCells(e){let t=performance.now(),n=new eL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new eL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new cL,this.formulaDependencies=xt(()=>{let e=new tL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id),r=this.getters.clipRangesToSheet(n.compiledFormula.rangeDependencies);e.addDependencies(t,r)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new ZM;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Bc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=gL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?lo(r,mL):mL(r)}catch(e){return Ao(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new eL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new eL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new eL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}uL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...dL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?_L(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):zu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||No,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Gu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=gL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Gu(hL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Gu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Gu(hL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),pL(r,i,this.checkCollision(e)),pL(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Gu(hL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Gu(hL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return _L(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function pL(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function mL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function hL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:mL(e)}function gL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function _L(e){return Gu({...new Ii,origin:void 0},void 0,e)}var vL=class extends KI{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new fL(e.custom,this.getters)}beforeHandle(e){(_u.has(e.type)||yu.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?lo(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=cd(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let yL=new A;yL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Ab:Ob,hoverSvg:n?Ab:kb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),yL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:Tb(i),hoverSvg:Db(i),priority:2,horizontalAlign:`right`,size:kd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),yL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Nb[n].svg,priority:1,horizontalAlign:`left`,size:kd(r),margin:4,position:t}}}),yL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??_g.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?jb(s,!1):void 0,hoverSvg:o?jb(s,!0):void 0,position:t,onClick:Kg}}}),yL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:kd(r),margin:0,svg:n===`asc`?Eb(r):Tb(r),position:t,onClick:void 0}});var bL=class extends KI{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=yL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let xL=/"(#[0-9a-fA-F]{6})"/g;function SL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=CL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function CL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var wL=class extends KI{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return SL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(xL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},TL=class extends KI{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=xM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=cd(i,e.styles);t.styles[o]=n}if(a){let n=cd(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function EL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!If(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Ff(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var DL=class extends KI{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(_u.has(e.type)||bu.has(e.type)||vu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:wf(e)};if(!t)return{background:oe,fontColor:wf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||wf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ch(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=EL(e)}return r}},OL=class extends KI{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(_u.has(e.type)||bu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Bc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Wu(t,V));if(o.some(Eh))return!1;let s={...t,type:t.operator,values:o.map(wh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let kL={isValid:!0};var AL=class extends KI{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(_u.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:Wy.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return kL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:kL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Bc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||kL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of ac(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?kL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Eh))return;let c={...i,values:s.map(wh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Wu(r,V);let i=Bc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let jL=[`SUBTOTAL`,`PIVOT`];var ML=class extends KI{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of jL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of jL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of jL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},NL=class extends KI{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=_d();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return vd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let PL=`0.00%`;function FL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Sg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Ao(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=uj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=uj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=uj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=jg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Ao(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:PL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:PL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:PL}}asPercentOfParentRowTotal(e,t,n){let r=cj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:PL}}asPercentOfParentColumnTotal(e,t,n){let r=lj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:PL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!vj(i,n))return{value:``};let a=gj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:PL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=uj(this,n),u=xj(l),d=xj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:PL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:PL}:s===void 0?{value:M.NullError}:{value:s/o,format:PL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!vj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:PL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!vj(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=uj(this,n),u=xj(l),d=xj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=yj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=xj(dj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:dj(this,i,t.domain)})).filter(e=>vj(t,e.rowDomain)),l=Object.groupBy(c,e=>Cj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=xj(dj(this,i,e.domain)),a=l[Cj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=yj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=xj(dj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:dj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>vj(t,e.rowDomain));for(let e of l){let n=xj(e.rowDomain),i=wj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=xj(n),a=wj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=yj(this,e),{rowDomain:a,colDomain:o}=uj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=xj(c),d=wj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=wj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=xj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&rg.contains(n)){let t=ig(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=uj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=uj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?bj(this,t,n,r):_j(t,n,r);if(T(i,t))return`sameValue`;if(!i||!pj(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getExpandedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;zg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let IL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function LL(e){return IL.includes(e.type)}var RL=class extends KI{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new ZM;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(_u.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(LL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:$g();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new ZM,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=Gj(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=_F(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||Kj(t.compiledFormula,this.getters)===0)return Oj;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Oj;let{functionName:i,args:a}=r,o=a[0];if(!o)return Oj;let s=this.getters.getPivotId(o.toString());if(!s)return Oj;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Oj;try{if(i===`PIVOT`){let t=qg(this.getters.getPivotCoreDefinition(s),wh(a[1]),wh(a[2]),wh(a[3]),wh(a[4]),wh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:uj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Oj}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&zj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=uj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=FL(zj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:qg(this.getters.getPivotCoreDefinition(i),wh(n.args[1]),wh(n.args[2]),wh(n.args[3]),wh(n.args[4]),wh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},zL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},BL=class extends zL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of ZT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},VL=class extends BL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Ag(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of ZT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:ZT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
|
|
115
115
|
`).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Qy(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},HL=class extends _I{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},UL=class extends HL{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Ln(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new VL(this.getters,this.dispatch),c=s.copy(YT(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of C(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>T(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:j(`%s duplicate rows found and removed.
|
|
116
116
|
%s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptySelectedRange`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=cn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Bn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=Rt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?j(`Trimmed whitespace from %s cells.`,n):j(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let WL=new A;WL.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=z(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=ga(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?zu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let GL=new A,KL=/(\d+)$/,qL=/^(.*\D+)/,JL=/^(.*\D+)(\d+)$/,YL=/^0*/;function XL(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:zu(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function ZL(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function QL(e){let t=1;return e.length>=2&&(t=ZL(e)*e.length),t}function $L(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function eR(e){if(e.length<2)return 1;let t=e.map(e=>z(e,V)),n=$L(tR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}GL.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Rl(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`&&JL.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(KL)[0]),i=e.content.match(qL)[0],a=XL(e,t,e=>e.type===`text`&&JL.test(e.value)).filter(e=>i===(e.value??``).toString().match(qL)[0]).map(e=>(e.value??``).toString().match(KL)[0]),o=a.reduce((e,t)=>{let n=t.match(YL)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=QL(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&zu(e,{locale:V}).type===`number`&&!!e.format&&Rl(e.format),generateRule:(e,t)=>{let n=eR(XL(e,t,e=>e.type===`number`&&!!e.format&&Rl(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=zu(e,{locale:V});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=XL(e,t,e=>e.type===`number`&&!Rl(e.format||``)).map(e=>Number(e.value)),i=QL(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=zu(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function tR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=P.fromTimestamp(e[n-1].getTime()),i=wa(r,t),a=Sa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ca(r,t)}}).slice(1)}var nR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=WL.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},rR=class extends HL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:cn(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(yn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=cn(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Fn(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=GL.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=sn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new nR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},iR=class extends HL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Fn(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Rn(kn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,kn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Vt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=rt(i.filter(e=>this.isNumber(r[e])))[0]||[];return Vt(o)<a?1/0:Ht(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Rl(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Rn(t)?(n.add(Ln(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Bn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Bn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},aR=class extends HL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(sR(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}computeTableStyle(e,t){return xt(()=>{let n=this.getters.getTableStyle(t.config.styleId),r=this.getTableMetaData(e,t);if(!r)return{borders:{},styles:{}};let{tableMetaData:i,config:a}=r,o=CM(a,n,i),s=this.getTableMapping(e,t),c={borders:{},styles:{}};for(let e=0;e<i.numberOfCols;e++){let t=s.colMapping[e];c.borders[t]={},c.styles[t]={};for(let n=0;n<i.numberOfRows;n++){let r=s.rowMapping[n];c.borders[t][r]=o.borders[e][n],c.styles[t][r]=o.styles[e][n]}}return c})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId);if(!s.isValid())return;let c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let oR=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`,`DELETE_CONTENT`]);function sR(e){return oR.has(e.type)}var cR=class extends HL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new ZM;borders=new ZM;handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new ZM,this.borders=new ZM;return}if(sR(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new ZM,this.borders=new ZM);return}if(bu.has(e.type)){this.styles=new ZM;return}if(xu.has(e.type)){this.borders=new ZM;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Dt(r),...Dt(i),...Dt(t?.style),...Dt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...sn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>In(yn(e),yn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(yn),s=cn([yn(r)],o);delete t.styles[r];for(let e of s)t.styles[wn(e)]=n;let c=cd({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...sn(n)});t.styles[n]=cd({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Dt(this.getters.getCellTableBorder(e)||{}),...Dt(t)};return gt(n)?null:n}},lR=class extends HL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function uR(e){let t=lc.get(e.type)?.(e),n=pR(e);if(!t&&!n)return;let r=t||fR(),i=n||(e=>e),a=dR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>Ec(e,t,r),adaptFormulaString:(e,t)=>wc(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function dR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Sn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function fR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function pR(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let mR=new class extends A{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},hR=new class extends A{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};mR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],OR),mR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],OR),mR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],yR),mR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],bR),mR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],xR),mR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],SR),mR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],CR),mR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],wR),mR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],TR),mR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],TR),mR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],ER),mR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],ER),mR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],DR),mR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],kR),mR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],kR),mR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],vR),mR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],_R),mR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],gR),mR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],gR),mR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],AR);function gR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=sr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function _R(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function vR(e,t){if(e.pivotId!==t.pivotId)return e}function yR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function bR(e,t){if(e.figureId!==t.figureId)return e}function xR(e,t){if(e.chartId!==t.chartId)return e}function SR(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function CR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function wR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Nn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function TR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function ER(e,t){if(e.sheetId!==t.sheetId)return e;let n=sr(e.zone,t);if(!n)return;let r=e.newTableRange?cr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function DR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:WS.styleId}}:e}function OR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=yc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=vc(Ct(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function kR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function AR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function jR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}hR.add(`UPDATE_CELL`,jR);function MR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}hR.add(`ADD_CONDITIONAL_FORMAT`,MR);function NR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}hR.add(`ADD_DATA_VALIDATION_RULE`,NR);function PR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}hR.add(`ADD_PIVOT`,PR),hR.add(`UPDATE_PIVOT`,PR),hR.add(`CREATE_CHART`,FR),hR.add(`UPDATE_CHART`,FR);function FR(e,t){return{...e,definition:tk.transformDefinition(e.sheetId,e.definition,t)}}let IR=[{match:du,fn:VR},{match:pu,fn:HR},{match:gu,fn:UR},{match:hu,fn:KR},{match:fu,fn:GR},{match:mu,fn:WR}];function LR(e,t){let n=mR.getTransformation(e.type,t.type),r=n?n(e,t):BR(e,t);return r&&RR(r,t)}function RR(e,t){let n=hR.get(e.type);if(!n)return e;let r=uR(t);return r?n(e,r):e}function zR(e,t){let n=[...e],r=new Set(mR.getKeys());for(let e of t)(r.has(e.type)||lc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=LR(n,e);return r&&t.push(r),t},[]));return n}function BR(e,t){for(let{match:n,fn:r}of IR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function VR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function HR(e,t){let n=VR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=sr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function UR(e,t){let n=VR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=sr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function WR(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>cr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function GR(e,t){let n=VR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function KR(e,t){let n=VR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?qR(e,t):t.type===`ADD_MERGE`?JR(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function qR(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function JR(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Fn(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var YR=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},XR=class extends Error{},ZR=class extends lr{revisions;transportService;serverRevisionId;commandSquisher;shouldVerifySquish;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Bd;lastLocalOperation;constructor(e,t,n=ke,r,i=!0){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r,this.shouldVerifySquish=i}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new YR(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new XR(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new YR(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:zR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new YR(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId));let n=this.commandSquisher.squish(t.commands);e=n.some(e=>e.type===`SQUISHED_UPDATE_CELL`)?this.shouldVerifySquish&&!T(t.commands,this.commandSquisher.unsquish(n))?{...e,commands:t.commands,squishedFailed:!0}:{...e,commands:n}:{...e,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
117
117
|
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof XR))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},QR=class extends HL{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new fi(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(e){try{this.getters.getCurrentClient()}catch(e){if(e instanceof XR)return[];throw e}let t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e;for(let e of this.getClientsToDisplay(i)){let{row:a,col:o}=e.position,s=this.getters.expandZone(i,{top:a,bottom:a,left:o,right:o}),{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);if(u<=0||d<=0)continue;let f=e.color;t.fillStyle=`${f}10`,t.lineWidth=4*n,t.strokeStyle=f,t.globalCompositeOperation=`multiply`,t.fillRect(c,l,u,d),t.globalCompositeOperation=`source-over`,t.strokeRect(c,l,u,d),t.font=`bold ${Ee+1}px ${De}`}}},$R=class extends HL{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of ac(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.isFormula&&!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if((t?.isFormula||t?.content)&&n.type===`empty`){let n;if(t.isFormula){let r=this.getters.evaluateCompiledFormula(e.sheetId,t.compiledFormula);n=(Je(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!at(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},ez=class extends HL{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},tz=class extends HL{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=cn(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:cn(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of cn(t))for(let t of Bn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=tu(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=cn(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Rl(e.format)))return e.format||Hl(e.value)}}},nz=class extends HL{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`,`loadUsedGeoJsonFeatures`];geoJsonService;geoJsonCache={};initialRegions={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.trackInitialRegion(t);break;case`CREATE_CHART`:this.trackInitialRegion(e.chartId);break;case`UPDATE_CHART_REGION`:{let t=this.getters.getChart(e.chartId),n=this.getters.getChartDefinition(e.chartId);if(!t||n.type!==`geo`)break;this.dispatch(`UPDATE_CHART`,{chartId:e.chartId,sheetId:t.sheetId,figureId:this.getters.getFigureIdFromChartId(e.chartId),definition:{...n,region:e.region}});break}}}trackInitialRegion(e){let t=this.getters.getChartDefinition(e);if(t?.type===`geo`){let n=this.getGeoChartAvailableRegions();this.initialRegions[e]=t.region||n[0]?.id||``}}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getAvailableChartRegions(e){if(!this.geoJsonService)return[];let t=this.getters.getChartDefinition(e);if(!t||t.type!==`geo`)return[];let n=this.initialRegions[e];return n&&this.geoJsonService.getAlternativeRegions?.(n)||[]}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}loadUsedGeoJsonFeatures(){let e=this.getters.getSheetIds().flatMap(e=>this.getters.getChartIds(e).map(e=>{let t=this.getters.getChartDefinition(e);return t.type===`geo`?t.region||this.getters.getGeoChartAvailableRegions()[0]?.id:void 0})).filter(w),t=Array.from(new Set(e));if(t.length&&!this.geoJsonService)return console.error(`No geoJsonService provided to the model`),Promise.resolve();for(let e of t)this.getGeoJsonFeatures(e);let n=t.map(e=>{let t=this.geoJsonCache[e];return t instanceof Promise?t:Promise.resolve()});return Promise.all(n).then(()=>{})}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},rz=class extends HL{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1)||this.findVisibleHeader(e,`COL`,t,0)||0,row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)||this.findVisibleHeader(e,`ROW`,n,0)||0}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return C(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},iz=class extends HL{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Xn(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:Ve}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:j(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:j(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(j(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Kt(nt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new Dj(o,s,c,l||{}),d=u.columns.length-1;if(this.resizeSheet(e,t,n,u),a===`dynamic`)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${this.getters.getPivotFormulaId(r)})`});else{this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()});let i={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length};this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,i)],config:{...Be,numberOfHeaders:d}})}}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i={sheetId:e,col:t,row:n},a=this.getters.getSpreadZone(i),o=this.getters.getTable(i);if(!a)return;let s=this.getters.getPivotFormulaId(r),c=this.getters.getPivotStyleAtPosition(i);if(!c)return;let l={...c.pivotStyle,tabularForm:!1},u=this.getters.getPivot(r).getCollapsedTableStructure(),d=u.getPivotCells(l),{numberOfCols:f,numberOfRows:p}=u.getPivotTableDimensions(l);if(!(p===0||f===0)){for(let t of C(0,f))for(let n of C(0,p)){let r=d[t][n];if(r){let i={sheetId:e,col:a.left+t,row:a.top+n};this.dispatch(`UPDATE_CELL`,{...i,content:Ag(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[D(i)]}),o?.isPivotTable){let t=this.getters.getRangeDataFromZone(e,{left:a.left,right:a.left+f-1,top:a.top,bottom:a.top+p-1});this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[t],config:{...o.config,styleId:_M(o.config.styleId)}})}}}};let az=new A,oz=new A;function sz(e,t){if(t&&az.contains(t.type))return az.get(t.type)(e,t)}function cz(e,t,n){if(oz.contains(t.type))return oz.get(t.type)(e,t,n)}function lz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Eu(e.rootCommand)?az.contains(e.rootCommand.type):oz.contains(e.rootCommand.type)}function uz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Eu(e.rootCommand)?sz(t,e.rootCommand):cz(t,e.rootCommand,e.commands)}var dz=class extends HL{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=uz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:lz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},fz=class extends HL{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return wu.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Eu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},pz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,L(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},mz=class extends HL{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new pz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}};let hz=[`number`,`error`,`text`,`boolean`];function gz(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=hz.indexOf(e.type)-hz.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function _z(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(gz(t))}var vz=class extends HL{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Fn(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Bn(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>Nn(e,t)),r=Ln(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Bn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!T(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=_z(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula)}else e=s.content;p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=C(t.left,t.right+1,n),o=C(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},yz=class extends HL{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
|
|
@@ -953,4 +953,4 @@ If you meant to create a named range, named range cannot have the same name as a
|
|
|
953
953
|
<Relationships xmlns="${rf.Relationships}">
|
|
954
954
|
<Relationship ${q(e)} />
|
|
955
955
|
</Relationships>
|
|
956
|
-
`),`_rels/.rels`)}function HU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function UU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var WU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Bd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=ow(e,n);let o=QC(e,i);this.state=new rH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new eH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.clipRangesToSheet=this.range.clipRangesToSheet.bind(this.range),this.coreGetters.clipRangeToSheet=this.range.clipRangeToSheet.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new nH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Fz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Rz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Lz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Iz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new ZR(ZV({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new HV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new qB,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new UV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Ro));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Eu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ou(e.flat()):Ou.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(GU(e,t));dispatch=(e,t)=>{let n=GU(e,t),r=this.status;if(this.getters.isReadonly()&&!Du(n))return new Ou(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ou(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Eu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Eu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Eu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ou.Success};dispatchFromCorePlugin=(e,t)=>{let n=GU(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ou.Success};dispatchToHandlers(e,t){let n=Eu(t);for(let r of e)!n&&r instanceof vI||r.beforeHandle(t);for(let r of e)!n&&r instanceof vI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new qB};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=pw();for(let n of this.handlers)n instanceof vI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=hw();for(let t of this.handlers)t instanceof _I&&await t.exportForExcel(e);return e=x(e),NU(e)}};function GU(e,t={}){let n=x(t);return n.type=e,n}let KU=Object.freeze({value:null}),qU=Object.freeze({value:1}),JU={supportedChartTypes:Uh,fromExternalDefinition(e,t,n){let r=bf(n,t,e),i=ic(n,t,e.labelRange);return{...e,dataSets:r,labelRange:i}},fromContextCreation(e){return{type:`range`,dataSets:[],dataSetsHaveTitle:!1,labelRange:e.auxiliaryRange,...e.dataSource}},fromHierarchicalContextCreation(e){if(e.dataSource?.type!==`range`||e.hierarchicalDataSource!==void 0&&e.hierarchicalDataSource.type!==`range`)return{type:`range`,dataSets:[],dataSetsHaveTitle:!1};let t={type:`range`,dataSets:[],dataSetsHaveTitle:e.dataSource?.dataSetsHaveTitle??!1,labelRange:e.dataSource?.dataSets?.[0]?.dataRange};return e.hierarchicalDataSource?.dataSets.length?t=e.hierarchicalDataSource:e.auxiliaryRange&&(t={...t,dataSets:[{dataRange:e.auxiliaryRange,dataSetId:`0`}]}),t},validate:(e,t)=>t.checkValidations(e,Ef,Df),transform(e,t,{adaptRangeString:n}){let r;if(e.labelRange){let{changeType:i,range:a}=n(t,e.labelRange);i!==`REMOVE`&&(r=a)}let i=[];for(let r of e.dataSets){let e={...r},{changeType:a,range:o}=n(t,r.dataRange);a!==`REMOVE`&&(e.dataRange=o,i.push(e))}return{...e,dataSets:i,labelRange:r}},extractData:(e,t,n)=>YU(n,e),extractHierarchicalData(e,t,n){let r=e.dataSets,i=e.labelRange,a=ZU(n,r,i),o=QU(n,r),s={labelValues:a,dataSetsValues:o};return Of(a.length,o[0]?.data.length+(o[0]?.label===void 0?0:1),e.dataSetsHaveTitle||!1)&&a.shift(),s},adaptRanges(e,{applyChange:t}){let n=e.dataSets.map(e=>{let{range:n,changeType:r}=t(e.dataRange);if(r===`REMOVE`)return;let i;if(e.labelCell){let{range:n,changeType:r}=t(e.labelCell);r!==`REMOVE`&&(i=n)}return{...e,dataRange:n,labelCell:i}}).filter(w),r=e.labelRange;if(r){let{range:e,changeType:n}=t(r);r=n===`REMOVE`?void 0:e}let i=n;return{...e,dataSets:i,labelRange:r?.invalidSheetName||r?.invalidXc?void 0:r}},getDefinition(e,t,n){return{labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,type:`range`,dataSets:e.dataSets.map(e=>({dataSetId:e.dataSetId,dataRange:n.getRangeString(e.dataRange,t)})),dataSetsHaveTitle:e.dataSetsHaveTitle}},duplicateInDuplicatedSheet(e,t,n,r){return{...e,labelRange:vf(t,n,e.labelRange),dataSets:e.dataSets.map(e=>({...e,dataRange:rc(t,n,e.dataRange)}))}},getContextCreation:e=>({auxiliaryRange:e.labelRange,dataSource:e}),getHierarchicalContextCreation(e){let t=e.dataSets.at(-1)?.dataRange,n=e.dataSetsHaveTitle;return{auxiliaryRange:t,hierarchicalDataSource:e,dataSource:e.labelRange?{type:`range`,dataSets:[{dataRange:e.labelRange,dataSetId:`0`}],dataSetsHaveTitle:n}:{type:`range`,dataSets:[],dataSetsHaveTitle:n}}},toExcelDataSets(e,t,n){let r=e.dataSets,i=e.labelRange,a=r.map(e=>Sf(n,t,e)).filter(e=>e.range!==``&&e.range!==M.InvalidReference),o=r[0]?Xn(r[0].dataRange.zone):void 0;return{dataSets:a,labelRange:Cf(n,i,Of(i?Xn(i.zone):0,o,e.dataSetsHaveTitle))}}};function YU(e,t){let n=t.dataSets,r=t.labelRange,i=ZU(e,n,r),a=XU(e,n),o={labelValues:i,dataSetsValues:a},s=a.length?a[0]?.data.length+(a[0]?.label===void 0?0:1):0;return Of(i.length,s,t.dataSetsHaveTitle||!1)&&i.shift(),o}function XU(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${Ry.Series} ${parseInt(r)+1}`,a=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){let{sheetId:n,zone:r}=i.labelCell,a=e.getEvaluatedCell({sheetId:n,col:r.left,row:r.top});a&&(t=a.formattedValue)}let o=i.dataRange?$U(e,i):[];o.every(e=>!e.value||qu(e))&&o.filter(qu).length>1?o=o.map(e=>e.value&&!Ju(e)?qU:KU):o.every(e=>!U(e))&&(a=!0),n.push({data:o,label:t,hidden:a,dataSetId:i.dataSetId})}return n}function ZU(e,t,n){if(n){let{left:t}=n.zone;if(!n.invalidXc&&!n.invalidSheetName&&!e.isColHidden(n.sheetId,t))return e.getVisibleRangeValues(n)}if(t[0]){let n=$U(e,t[0]).length;return Array.from({length:n},()=>({value:``}))}return[]}function QU(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));let n=t.map(e=>({data:[],label:``,dataSetId:e.dataSetId})),r=e.getLocale(),i=t.map(t=>$U(e,t)).map(e=>e.map(({value:e,format:t})=>e===null?KU:{value:H(e,{format:t,locale:r})}));if(!i.length)return n;let a=Math.min(...i.map(e=>e.length)),o=[],s=t.length-1;for(let e=0;e<a;e++)for(let t=0;t<i.length;t++){let r=i[t][e];(r===void 0||r.value===null)&&t!==s&&(r=o[t]),r?.value!==o[t]?.value&&(o=o.slice(0,t),o[t]=r),n[t].data.push(r??KU)}return n.filter(e=>e.data.some(e=>e.value!==null))}function $U(e,t){if(t.dataRange){let n=t.labelCell?[t.labelCell.zone]:[],r=cn([t.dataRange.zone],n)[0];if(r===void 0)return[];let i=e.getRangeFromZone(t.dataRange.sheetId,r);return e.getVisibleRangeValues(i).map(e=>e.value===``?KU:e)}return[]}uS.add(`range`,JU),uS.add(`none`,{supportedChartTypes:[],fromExternalDefinition:()=>({type:`none`}),fromContextCreation:()=>({type:`none`}),fromHierarchicalContextCreation:()=>({type:`none`}),validate:()=>`Success`,transform:()=>({type:`none`}),extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]}),adaptRanges:e=>e,getDefinition:e=>e,duplicateInDuplicatedSheet:e=>e,getContextCreation:()=>({}),getHierarchicalContextCreation:()=>({}),toExcelDataSets:()=>({dataSets:[],labelRange:void 0})});function eW(e){return!CO.includes(e.horizontalGroupBy)||!CO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let tW={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,eW)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=a_(t,n(),e),{labels:i,datasets:a}=gp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...sh,indexAxis:`x`,layout:L_(t,r),scales:Qf(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:sv(t,r),chartShowValuesPlugin:Z_(t,r),chartColorScalePlugin:$f(t,r),background:{color:t.background}}}}}}},nW={sequence:15,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:xp(t,a)},options:{...sh,layout:I_(t,a),scales:Zf(t,a),plugins:{title:nv(t,e),legend:U_(t,a),tooltip:ov(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:wp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:cp(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:mv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}}}}},iW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=u_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Cp(t,a)},options:{...sh,layout:I_(t,a),scales:sp(t,a),plugins:{title:nv(t,e),tooltip:pv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},aW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=o_(t,YU(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:ap(t,a),plugins:{title:nv(t,e),legend:z_(t,a),tooltip:dv(t,a),chartShowValuesPlugin:$_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},oW={sequence:80,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=l_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...sh,layout:I_(t,a),scales:op(t,a),plugins:{title:nv(t,e),legend:G_(t,a),tooltip:fv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sW={sequence:60,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:yp(t,a)},options:{...sh,layout:I_(t,a),scales:rp(t,a),plugins:{title:nv(t,e),legend:H_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cW={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:Ep(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:K_(t,a),tooltip:hv(t,a),sunburstLabelsPlugin:Q_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},lW={sequence:100,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:jp(t,a)},options:{...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:gv(t,a),background:{color:t.background}},...i}}}}};dS.add(`bar`,xv),dS.add(`combo`,nW),dS.add(`line`,Mv),dS.add(`pie`,Nv),dS.add(`scorecard`,im),dS.add(`gauge`,Dv),dS.add(`scatter`,sW),dS.add(`waterfall`,Pv),dS.add(`pyramid`,aW),dS.add(`radar`,oW),dS.add(`geo`,iW),dS.add(`funnel`,rW),dS.add(`sunburst`,cW),dS.add(`treemap`,lW),dS.add(`calendar`,tW),Kv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var uW=class extends BL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},dW=class extends zL{copy(e){}},fW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Bd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=tk.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=tk.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=tk.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Bd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mW=class extends BL{uuidGenerator=new Bd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},hW=class extends BL{uuidGenerator=new Bd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},gW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Bd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},_W=class extends BL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},vW=class extends BL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},yW=class extends BL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(ZT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},bW=class extends BL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};FF.figureHandlers.add(`chart`,pW).add(`image`,gW).add(`carousel`,fW),FF.cellHandlers.add(`dataValidation`,hW).add(`cell`,VL).add(`sheet`,yW).add(`merge`,_W).add(`border`,uW).add(`table`,bW).add(`conditionalFormat`,mW).add(`references`,vW);var xW=l({ARRAYTOTEXT:()=>XW,ARRAY_CONSTRAIN:()=>wW,ARRAY_LITERAL:()=>TW,ARRAY_ROW:()=>EW,CHOOSECOLS:()=>DW,CHOOSEROWS:()=>OW,EXPAND:()=>kW,FLATTEN:()=>AW,FREQUENCY:()=>jW,HSTACK:()=>MW,MDETERM:()=>NW,MINVERSE:()=>PW,MMULT:()=>FW,SUMPRODUCT:()=>IW,SUMX2MY2:()=>RW,SUMX2PY2:()=>zW,SUMXMY2:()=>BW,TOCOL:()=>UW,TOROW:()=>WW,TRANSPOSE:()=>GW,VSTACK:()=>KW,WRAPCOLS:()=>qW,WRAPROWS:()=>JW});function SW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function CW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=co(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let wW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return co(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},TW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},EW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},DW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},OW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?co(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},kW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):co(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},AW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[To(e,e=>e===void 0?{value:``}:e)]},isExported:!1},jW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=To([e],e=>e.value).filter(e=>typeof e==`number`),r=To([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},MW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e)},isExported:!0},NW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return vh(t)?xh(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},PW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!vh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=xh(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},FW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Ch(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},IW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!_h(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function LW(e,t,n){if(!_h(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let RW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2-t**2)},isExported:!0},zW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2+t**2)},isExported:!0},BW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>(e-t)**2)},isExported:!0},VW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function HW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let UW={description:j(`Transforms a range of cells into a single column.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},WW={description:j(`Transforms a range of cells into a single row.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},GW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return co(n,r,(e,n)=>t[n][e])},isExported:!0},KW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e)},isExported:!0},qW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},JW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},YW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],XW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),YW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return sT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return fo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:Xa(e,this.locale))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var ZW=l({ABS:()=>$W,ACOS:()=>eG,ACOSH:()=>tG,ACOT:()=>nG,ACOTH:()=>rG,ASIN:()=>iG,ASINH:()=>aG,ATAN:()=>oG,ATAN2:()=>sG,ATANH:()=>cG,CEILING:()=>lG,CEILING_MATH:()=>dG,CEILING_PRECISE:()=>fG,COS:()=>pG,COSH:()=>mG,COT:()=>hG,COTH:()=>gG,COUNTBLANK:()=>_G,COUNTIF:()=>vG,COUNTIFS:()=>yG,COUNTUNIQUE:()=>bG,COUNTUNIQUEIFS:()=>xG,CSC:()=>SG,CSCH:()=>CG,DECIMAL:()=>wG,DEGREES:()=>TG,EXP:()=>EG,FLOOR:()=>DG,FLOOR_MATH:()=>kG,FLOOR_PRECISE:()=>AG,INT:()=>fK,ISEVEN:()=>jG,ISODD:()=>NG,ISO_CEILING:()=>MG,LN:()=>PG,LOG:()=>FG,MOD:()=>LG,MUNIT:()=>RG,ODD:()=>zG,PI:()=>BG,POWER:()=>VG,PRODUCT:()=>HG,RAND:()=>UG,RANDARRAY:()=>WG,RANDBETWEEN:()=>GG,ROUND:()=>KG,ROUNDDOWN:()=>qG,ROUNDUP:()=>JG,SEC:()=>YG,SECH:()=>XG,SEQUENCE:()=>ZG,SIN:()=>QG,SINH:()=>$G,SQRT:()=>eK,SUBTOTAL:()=>iK,SUM:()=>aK,SUMIF:()=>oK,SUMIFS:()=>sK,TAN:()=>cK,TANH:()=>lK,TRUNC:()=>dK});let QW=/^-?[a-z0-9]+$/i,$W={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},eG={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},tG={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},nG={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},rG={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},iG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},aG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},oG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},sG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},cG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},lG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function uG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let dG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:uG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},fG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:uG(I(e,this.locale),n),format:e?.format}},isExported:!0},pG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},mG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},hG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},gG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},_G={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ao(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},vG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},yG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},bG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return tg(e)}},xG={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return yo(t,(t,r)=>{let i=e[t]?.[r];Eo(i)&&n.add(i.value)},this.locale),n.size}},SG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},CG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},wG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!QW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},TG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},EG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},DG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function OG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let kG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:OG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},AG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:OG(I(e,this.locale),n),format:e?.format}},isExported:!0},jG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},MG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:uG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},NG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},PG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},FG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function IG(e,t){hh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let LG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:IG(I(e,this.locale),n),format:e?.format}},isExported:!0},RG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):bh(t)},isExported:!0},zG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},BG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},VG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},HG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},UG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},WG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},GG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},KG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},qG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},JG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},YG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},XG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},ZG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):co(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},QG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},$G={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},eK={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},tK={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},nK=Object.entries(tK).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),rK=Object.entries(tK).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),iK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...nK,...rK]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[tK[n]].apply(this,[[i]])},isExported:!0},aK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:eg(e,this.locale),format:za(t)}},isExported:!0},oK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return yo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},sK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},cK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},lK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function uK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let dK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:uK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},fK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var pK=l({AVEDEV:()=>CK,AVERAGE:()=>wK,AVERAGEA:()=>OK,AVERAGEIF:()=>kK,AVERAGEIFS:()=>AK,AVERAGE_WEIGHTED:()=>DK,CORREL:()=>QK,COUNT:()=>jK,COUNTA:()=>MK,COVAR:()=>NK,COVARIANCE_P:()=>PK,COVARIANCE_S:()=>FK,FORECAST:()=>IK,GROWTH:()=>LK,INTERCEPT:()=>RK,LARGE:()=>zK,LINEST:()=>BK,LOGEST:()=>VK,MATTHEWS:()=>HK,MAX:()=>UK,MAXA:()=>WK,MAXIFS:()=>GK,MEDIAN:()=>KK,MIN:()=>qK,MINA:()=>JK,MINIFS:()=>YK,PEARSON:()=>ZK,PERCENTILE:()=>$K,PERCENTILE_EXC:()=>eq,PERCENTILE_INC:()=>tq,POLYFIT_COEFFS:()=>nq,POLYFIT_FORECAST:()=>rq,QUARTILE:()=>iq,QUARTILE_EXC:()=>aq,QUARTILE_INC:()=>oq,RANK:()=>sq,RSQ:()=>cq,SLOPE:()=>lq,SMALL:()=>uq,SPEARMAN:()=>dq,STDEV:()=>fq,STDEVA:()=>hq,STDEVP:()=>gq,STDEVPA:()=>_q,STDEV_P:()=>pq,STDEV_S:()=>mq,STEYX:()=>vq,TREND:()=>yq,VAR:()=>bq,VARA:()=>Cq,VARP:()=>wq,VARPA:()=>Tq,VAR_P:()=>xq,VAR_S:()=>Sq});let mK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],hK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],gK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],_K=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],vK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function yK(e,t){let n=[],r=[],i=0,a=0;no([e],e=>{n.push(e),i+=1}),no([t],e=>{r.push(e),a+=1}),mh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function bK(e,t,n){let{flatDataX:r,flatDataY:i}=yK(e,t),a=i.length;hh(a),n&&hh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function xK(e,t,n,r){let i=0,a=n?so:oo,o=a(e,(e,t)=>(i+=1,e+t),0,r);hh(i),t&&hh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function SK(e,t,n,r){let i=I(t,r);mh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return no(e,e=>{let t=e?.value;typeof t==`number`&&(o=bo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),mh(s!==0,Do),n||mh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let CK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return oo(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},wK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Oh(e,this.locale),format:za(e[0])}},isExported:!0},TK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),EK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),DK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!_h(i,a))return new N(TK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(EK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(EK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},OK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=so(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},kK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return yo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},AK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return yo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},jK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Ah(e,this.locale)},isExported:!0},MK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return jh(e)},isExported:!0},NK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},PK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},FK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!0)},isExported:!0},IK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=yK(t,n);return r.length===0||i.length===0?new Ri(Do):Vh([i],[r],lo(B(e),e=>I(e,this.locale)),!0)},isExported:!0},LK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):zh(Vh(Bh(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},RK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[],[i]]=Fh([n],[r]);return i},isExported:!0},zK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},BK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Oo(`data_y`)):Fh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},VK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Oo(`data_y`));let i=Fh(Ka(t,`data_x`),Bh(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},HK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Dh(n,r),n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},UK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Mh(e,this.locale)},isExported:!0},WK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},KK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return ro(e,e=>{t.push(e)},this.locale),{value:SK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},qK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return Nh(e,this.locale)},isExported:!0},JK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},YK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function XK(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let ZK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return XK(e,t)},isExported:!0},QK=ZK,$K={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return tq.compute.bind(this)(e,t)},isExported:!0},eq={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!1,this.locale),format:za(e)}},isExported:!0},tq={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!0,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=yK(e,t);return i.length===0||a.length===0?new Ri(Do):Ih(a,i,I(n,this.locale),R(r))},isExported:!1},rq={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=yK(t,n);if(o.length===0||s.length===0)return new Ri(Do);let c=Ih(s,o,a,R(i)).flat();return lo(B(e),e=>Rh(c,I(e,this.locale),a))},isExported:!1},iq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){return oq.compute.bind(this)(e,t)},isExported:!0},aq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!1,this.locale),format:za(e)}},isExported:!0},oq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!0,this.locale),format:za(e)}},isExported:!0},sq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},cq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=XK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},lq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[i]]=Fh([n],[r]);return i},isExported:!0},uq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},dq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(t,e);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},fq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Sq.compute.bind(this)(...e))},isExported:!0},hq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Cq.compute.bind(this)(...e))},isExported:!0},gq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(wq.compute.bind(this)(...e))},isExported:!0},_q={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Tq.compute.bind(this)(...e))},isExported:!0},vq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);return n.length===0||r.length===0?new Ri(Do):Fh([n],[r],!0,!0)[1][2]},isExported:!0},yq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):Vh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},bq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Sq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},Cq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!0,this.locale)},isExported:!0},wq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Tq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!0,this.locale)},isExported:!0};var Eq=l({DAVERAGE:()=>kq,DCOUNT:()=>Aq,DCOUNTA:()=>jq,DGET:()=>Mq,DMAX:()=>Nq,DMIN:()=>Pq,DPRODUCT:()=>Fq,DSTDEV:()=>Iq,DSTDEVP:()=>Lq,DSUM:()=>Rq,DVAR:()=>zq,DVARP:()=>Bq});function Dq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)yo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Oq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],kq={description:j(`Average of a set of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Counts values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return jK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Counts values and text from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return MK.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Single value from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},Nq={description:j(`Maximum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Minimum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return qK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Product of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return HG.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Standard deviation of population sample from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Lq={description:j(`Standard deviation of entire population from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Rq={description:j(`Sum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return aK.compute.bind(this)([r])},isExported:!0},zq={description:j(`Variance of population sample from table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Bq={description:j(`Variance of a population from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wq.compute.bind(this)([r])},isExported:!0},Vq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hq=j(`There must be both positive and negative values in cashflow_amounts.`),Uq=e=>j(`The cost (%s) must be positive or null.`,e),Wq=e=>j(`The cost (%s) must be strictly positive.`,e),Gq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Jq=e=>j(`The discount (%s) must be different from -1.`,e),Yq=e=>j(`The discount (%s) must be strictly positive.`,e),Xq=e=>j(`The discount (%s) must be smaller than 1.`,e),Zq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Qq=e=>j(`The end_period (%s) must be positive or null.`,e),$q=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),eJ=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),tJ=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),nJ=e=>j(`The first_period (%s) must be strictly positive.`,e),rJ=e=>j(`The future_value (%s) must be strictly positive.`,e),iJ=e=>j(`The investment (%s) must be strictly positive.`,e),aJ=e=>j(`The issue (%s) must be positive or null.`,e),oJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),sJ=e=>j(`The last_period (%s) must be strictly positive.`,e),cJ=e=>j(`The life (%s) must be strictly positive.`,e),lJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),uJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),dJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),fJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),pJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),mJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),hJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),gJ=e=>j(`The period (%s) must be positive or null.`,e),_J=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),yJ=e=>j(`The period (%s) must be strictly positive.`,e),bJ=e=>j(`The present_value (%s) must be strictly positive.`,e),xJ=e=>j(`The price (%s) must be strictly positive.`,e),SJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),CJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),wJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),TJ=e=>j(`The rate (%s) must be positive or null.`,e),EJ=e=>j(`The rate (%s) must be strictly positive.`,e),DJ=e=>j(`The redemption (%s) must be strictly positive.`,e),OJ=e=>j(`The salvage (%s) must be positive or null.`,e),kJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),AJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),jJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),MJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),NJ=e=>j(`The start_period (%s) must be positive or null.`,e),PJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),FJ=e=>j(`The unit (%s) must be strictly positive.`,e),IJ=e=>j(`The yield (%s) must be positive or null.`,e);function LJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function RJ(e){return![0,1,2,3,4].includes(e)}function zJ(e){return![1,2,4].includes(e)}function BJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let VJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var HJ=l({DATE:()=>WJ,DATEDIF:()=>GJ,DATEVALUE:()=>KJ,DAY:()=>qJ,DAYS:()=>JJ,DAYS360:()=>YJ,EDATE:()=>XJ,EOMONTH:()=>ZJ,HOUR:()=>QJ,ISOWEEKNUM:()=>$J,MINUTE:()=>eY,MONTH:()=>tY,MONTH_END:()=>vY,MONTH_START:()=>_Y,NETWORKDAYS:()=>nY,NETWORKDAYS_INTL:()=>aY,NOW:()=>oY,QUARTER:()=>yY,QUARTER_END:()=>xY,QUARTER_START:()=>bY,SECOND:()=>sY,TIME:()=>cY,TIMEVALUE:()=>lY,TODAY:()=>uY,WEEKDAY:()=>dY,WEEKNUM:()=>fY,WORKDAY:()=>pY,WORKDAY_INTL:()=>mY,YEAR:()=>hY,YEARFRAC:()=>gY,YEAR_END:()=>CY,YEAR_START:()=>SY}),UJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(UJ||{});let WJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},GJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(UJ).includes(r))return new N(Wa(Object.values(UJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},KJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},qJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},JJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},YJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},XJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ZJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},QJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},$J={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},eY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},tY={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},nY={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return aY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function rY(e){let t=e?.value;if(typeof t==`string`){mh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return mh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let iY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],aY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},oY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:db(this.locale)}},isExported:!0},sY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},cY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},lY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},uY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},fY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return $J.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},pY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return mY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},mY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},hY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},gY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},_Y={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},vY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return ZJ.compute.bind(this)(e,{value:0})}},yY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},bY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},xY={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},SY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},CY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var wY=l({DELTA:()=>TY});let TY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var EY=l({FILTER:()=>OY,SORT:()=>kY,SORTN:()=>AY,UNIQUE:()=>jY});function DY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;mh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(wh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))mh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(wh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:gz(`desc`),asc:gz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let OY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>lo(B(e),e=>e.value));for(let e of r)if(!gh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!_h(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?fo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?fo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},kY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return fo(DY(fo(e),this.locale,...t))},isExported:!0},AY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=DY(fo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return fo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return fo(o.slice(0,e));return fo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return fo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return fo(e)}}},isExported:!1},jY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=fo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:fo(o):new N(j(`No unique values found`))},isExported:!0};var MY=l({ACCRINTM:()=>LY,AMORLINC:()=>RY,COUPDAYBS:()=>BY,COUPDAYS:()=>zY,COUPDAYSNC:()=>VY,COUPNCD:()=>HY,COUPNUM:()=>UY,COUPPCD:()=>WY,CUMIPMT:()=>GY,CUMPRINC:()=>KY,DB:()=>qY,DDB:()=>YY,DISC:()=>XY,DOLLARDE:()=>ZY,DOLLARFR:()=>QY,DURATION:()=>$Y,EFFECT:()=>eX,FV:()=>nX,FVSCHEDULE:()=>rX,INTRATE:()=>iX,IPMT:()=>oX,IRR:()=>cX,ISPMT:()=>lX,MDURATION:()=>uX,MIRR:()=>dX,NOMINAL:()=>fX,NPER:()=>pX,NPV:()=>hX,PDURATION:()=>gX,PMT:()=>vX,PPMT:()=>bX,PRICE:()=>SX,PRICEDISC:()=>CX,PRICEMAT:()=>wX,PV:()=>xX,RATE:()=>EX,RECEIVED:()=>DX,RRI:()=>OX,SLN:()=>kX,SYD:()=>AX,TBILLEQ:()=>NX,TBILLPRICE:()=>MX,TBILLYIELD:()=>PX,VDB:()=>FX,XIRR:()=>IX,XNPV:()=>LX,YIELD:()=>RX,YIELDDISC:()=>zX,YIELDMAT:()=>BX});let NY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],PY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],FY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)];function IY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){mh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,mh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let LY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(aJ(a));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(DJ(s));if(c<=0)return new N(EJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},RY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Wq(s));if(c<0)return new N(CJ(c));if(u<0)return new N(OJ(u));if(u>s)return new N(kJ(u,s));if(d<0)return new N(gJ(d));if(f<=0)return new N(EJ(f));if(RJ(p))return new N(Kq(p));if(c>l)return new N(SJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},zY={description:j(`Days in coupon period containing settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));if(s===1){let i=WY.compute.bind(this)(e,t,n,r).value,a=HY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},BY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=WY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},VY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=HY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=BY.compute.bind(this)(e,t,n,r);return I(zY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},HY={description:j(`Next coupon date after the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},UY={description:j(`Number of coupons between settlement and maturity.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},WY={description:j(`Last coupon date prior to or on the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},GY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=aX(c,e,u,l,0,d);return f},isExported:!0},KY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=yX(c,e,u,l,0,d);return f},isExported:!0},qY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(1>l||l>12)return new N(uJ(l));if(c>u)return new N(hJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},JY=`#,##0.00`,YY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(c>s)return new N(vJ(c,s));if(l<=0)return new N(qq(l));if(a===0||o>=a)return{value:0,format:JY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:JY};if(c<=1)return{value:a*u,format:JY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:JY}},isExported:!0},XY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},ZY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},QY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},$Y={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(zJ(u))return new N(Gq(u));if(RJ(d))return new N(Kq(d));if(c<0)return new N(TJ(c));if(l<0)return new N(IJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},eX={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(dJ(n)):r<=0?new N(_J(r)):(1+n/r)**+r-1},isExported:!0};function tX(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let nX={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},rX={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return ao([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},iX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(c<=0)return new N(iJ(c));if(s<=0)return new N(DJ(s));if(RJ(l))return new N(Kq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function aX(e,t,n,r,i,a){return _X(e,n,r,i,a)-yX(e,t,n,r,i,a)}let oX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:aX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},sX=.1,cX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${sX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:sX}){let n=I(t,this.locale);if(n<=-1)return new N(wJ(n));let r=!1,i=!1,a=[];if(ro([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Hq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:IY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},lX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(fJ(o)):-1*(s-a/o*s)*i},isExported:!0},uX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=$Y.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},dX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=fo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Hq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},fX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(Zq(n)):r<=0?new N(_J(r)):((n+1)**(1/r)-1)*r},isExported:!0},pX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function mX(e,t,n,r){let i=0;return oo(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let hX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Jq(n)):{value:mX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},gX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(EJ(r)):i<=0?new N(bJ(i)):a<=0?new N(rJ(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function _X(e,t,n,r,i){if(t<=0)throw new N(pJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let vX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:_X(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function yX(e,t,n,r,i,a){if(n<=0)throw new N(pJ(n));if(t<=0||t>n)throw new N(mJ(n));let o=_X(e,n,r,i,a);return a===1&&t===1?o:o+-tX(e,a===0?t-1:t-2,o,r+o*a,0)*e}let bX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:yX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},xX={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},SX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},CX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(Yq(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},wX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(MJ(o,c));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},TX=.1,EX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:TX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||TX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(pJ(o)):LJ([s,d,u])?l<=-1?new N(wJ(l)):(u-=s*c,d+=s*c,{value:IY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},DX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(lJ(a,o)):RJ(l)?new N(Kq(l)):s<=0?new N(iJ(s)):c<=0?new N(Yq(c)):s/(1-c*xa(a,o,l))},isExported:!0},OX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(pJ(r)):(a/i)**(1/r)-1},isExported:!0},kX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},AX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(yJ(s));if(o<=0)return new N(cJ(o));if(s>o)return new N(vJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function jX(e,t,n){return 100*(1-n*xa(e,t,2))}let MX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(lJ(r,i)):BJ(r,i,this.locale)?a<=0?new N(Yq(a)):a>=1?new N(Xq(a)):jX(r,i,a):new N(jJ(r,i))},isExported:!0},NX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(Yq(a));if(a>=1)return new N(Xq(a));let o=JJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=jX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},PX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(xJ(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},FX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(Uq(s));if(c<0)return new N(OJ(c));if(l<=0)return new N(cJ(l));if(u<0)return new N(NJ(u));if(d<0)return new N(Qq(d));if(u>d)return new N(PJ(u,d));if(d>l)return new N($q(d,l));if(f<=0)return new N(qq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},IX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:TX}){let r=I(n,this.locale);if(!_h(e,t))return new N(Vq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!LJ(i))return new N(Hq);if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=-1)return new N(wJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return IY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},LX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!_h(t,n))return new N(Vq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=0)return new N(EJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},RX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(IY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},zX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},BX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(o<c)return new N(AJ(o,c));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var VX=l({CELL:()=>UX,ISBLANK:()=>ZX,ISERR:()=>WX,ISERROR:()=>GX,ISFORMULA:()=>$X,ISLOGICAL:()=>KX,ISNA:()=>qX,ISNONTEXT:()=>JX,ISNUMBER:()=>YX,ISTEXT:()=>XX,NA:()=>QX});let HX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],UX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),HX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!HX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,HX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:ou(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},WX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},GX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},KX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},qX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},JX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!XX.compute.bind(this)(e)},isExported:!0},YX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},XX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},ZX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},QX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},$X={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var eZ=l({AND:()=>tZ,FALSE:()=>nZ,IF:()=>rZ,IFERROR:()=>iZ,IFNA:()=>aZ,IFS:()=>oZ,NOT:()=>sZ,OR:()=>cZ,SWITCH:()=>lZ,TRUE:()=>uZ,XOR:()=>dZ});let tZ={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Qh(e);return n?t:new N(Do)},isExported:!0},nZ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rZ={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Eh(e)?po(rZ.compute,[e,t,n]):(R(wh(e))?t:n)??{value:0}},isExported:!0},iZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Eh(e)?po(iZ.compute,[e,t]):(F(wh(e)?.value)?t:e)??{value:0}},isExported:!0},aZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Eh(e)?po(aZ.compute,[e,t]):(wh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},oZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Eh(e[0]))return po(oZ.compute,e);let t=R(wh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},sZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},cZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=$h(e);return n?t:new N(Do)},isExported:!0},lZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},uZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},dZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return ho(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Do)},isExported:!0};function fZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function pZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function mZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function hZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var gZ=l({ADDRESS:()=>yZ,CHOOSE:()=>IZ,COLUMN:()=>bZ,COLUMNS:()=>xZ,DROP:()=>LZ,FORMULATEXT:()=>zZ,HLOOKUP:()=>SZ,INDEX:()=>CZ,INDIRECT:()=>wZ,LOOKUP:()=>TZ,MATCH:()=>EZ,OFFSET:()=>FZ,PIVOT:()=>PZ,PIVOT_HEADER:()=>NZ,PIVOT_VALUE:()=>MZ,ROW:()=>DZ,ROWS:()=>OZ,TAKE:()=>RZ,VLOOKUP:()=>kZ,XLOOKUP:()=>jZ});let _Z=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],vZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],yZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),_Z),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(yh(a));if(o<1)return new N(yh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Qo(L(i),l)},isExported:!0},bZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:co(t.length,1,e=>({value:r+e+1}))},isExported:!0},xZ={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},SZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?bo(a,e,`nextSmaller`,`asc`,a.length,o):xo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},CZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},wZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),_Z)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},TZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=bo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},EZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=bo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=xo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=bo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},DZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:co(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},OZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},kZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?bo(a,e,`nextSmaller`,`asc`,a[0].length,o):xo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},AZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},jZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=AZ[o],m=s===-1,h=s===2||s===-2?bo(c,e,p,s===2?`asc`:`desc`,f,d):xo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},MZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=fZ(r,this.getters);pZ(a,i,this.getters),mZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);hZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},NZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=fZ(n,this.getters);mZ(t);let i=this.getters.getPivot(r);hZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},PZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=fZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=qg(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));hZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(qy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Rg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},FZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),co(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},IZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},LZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},RZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},zZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var BZ=l({ADD:()=>VZ,CONCAT:()=>HZ,DIVIDE:()=>UZ,EQ:()=>qZ,GT:()=>YZ,GTE:()=>XZ,LT:()=>ZZ,LTE:()=>QZ,MINUS:()=>$Z,MULTIPLY:()=>eQ,NE:()=>tQ,POW:()=>nQ,SPILLED_RANGE:()=>rQ,UMINUS:()=>iQ,UNARY_PERCENT:()=>aQ,UPLUS:()=>oQ});let VZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},HZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return Xa(e,this.locale)+Xa(t,this.locale)},isExported:!0},UZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function WZ(e){return e===void 0||e.value===null}let GZ={number:0,string:``,boolean:!1};function KZ(e,t,n=2e-16){return Math.abs(e-t)<n}let qZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=WZ(e)?GZ[typeof t?.value]:e?.value,r=WZ(t)?GZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:KZ(n,r)}:{value:n===r}}};function JZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=WZ(e)?GZ[typeof t?.value]:e?.value,i=WZ(t)?GZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let YZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!KZ(e,t)&&e>t:e>t)}},XZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?KZ(e,t)||e>t:e>=t)}},ZZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=XZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=YZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},$Z={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},eQ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},tQ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=qZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},nQ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return VG.compute.bind(this)(e,t)}},rQ={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),co(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},iQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},aQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},oQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),sQ={transform:e=>e,inverseTransform:e=>e},cQ=1e-10,lQ=.0254,uQ=lQ/72,dQ=.3048,fQ=.9144,pQ=1609.34,mQ=1852,hQ=946073047258e4,gQ={g:{...sQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...sQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(cQ),category:`distance`},Picapt:{...$(uQ),category:`distance`},pica:{...$(lQ/6),category:`distance`},in:{...$(lQ),category:`distance`},ft:{...$(dQ),category:`distance`},yd:{...$(fQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(pQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(mQ),category:`distance`},ly:{...$(hQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...sQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...sQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...sQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...sQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...sQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...sQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...sQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...sQ,category:`volume`,order:3},"ang^3":{...$(cQ**3),category:`volume`,order:3},"Picapt^3":{...$(uQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(lQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(dQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(fQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(pQ**3),category:`volume`,order:3},"Nmi^3":{...$(mQ**3),category:`volume`,order:3},"ly^3":{...$(hQ**3),category:`volume`,order:3},"m^2":{...sQ,category:`area`,order:2},"ang^2":{...$(cQ**2),category:`area`,order:2},"Picapt^2":{...$(uQ**2),category:`area`,order:2},"in^2":{...$(lQ**2),category:`area`,order:2},"ft^2":{...$(dQ**2),category:`area`,order:2},"yd^2":{...$(fQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(pQ**2),category:`area`,order:2},"Nmi^2":{...$(mQ**2),category:`area`,order:2},"ly^2":{...$(hQ**2),category:`area`,order:2},bit:{...sQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...sQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},_Q={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},vQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},yQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},bQ=Object.entries(gQ).map(([e,t])=>({value:e,label:xQ(t.category)}));function xQ(e){return yQ[e]??``}function SQ(e){for(let[t,n]of Object.entries(vQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=gQ[r];if(!i&&_Q[r]&&(i=gQ[_Q[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var CQ=l({CONVERT:()=>wQ});let wQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),bQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),bQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=SQ(i),s=SQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,xQ(o.category),xQ(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var TQ=l({CHAR:()=>kQ,CLEAN:()=>AQ,CONCATENATE:()=>jQ,EXACT:()=>MQ,FIND:()=>NQ,FORMAT_LARGE_NUMBER:()=>PQ,JOIN:()=>FQ,LEFT:()=>IQ,LEN:()=>LQ,LOWER:()=>RQ,MID:()=>zQ,PROPER:()=>BQ,REGEXEXTRACT:()=>HQ,REGEXREPLACE:()=>UQ,REGEXTEST:()=>VQ,REPLACE:()=>WQ,RIGHT:()=>GQ,SEARCH:()=>KQ,SPLIT:()=>qQ,SUBSTITUTE:()=>JQ,TEXT:()=>$Q,TEXTAFTER:()=>t$,TEXTBEFORE:()=>n$,TEXTJOIN:()=>YQ,TEXTSPLIT:()=>XQ,TRIM:()=>ZQ,UPPER:()=>QQ,VALUE:()=>e$});let EQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,DQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],OQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],kQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},AQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=Xa(e,this.locale),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},jQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ao(e,(e,t)=>e+Xa(t,this.locale),``)},isExported:!0},MQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return Xa(e,this.locale)===Xa(t,this.locale)},isExported:!0},NQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale),i=Xa(t,this.locale),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},PQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Ql(e,t,this.locale)}}},FQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=Xa(e,this.locale);return ao(t,(e,t)=>(e?e+n:``)+Xa(t,this.locale),``)}},IQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):Xa(e,this.locale).substring(0,n)},isExported:!0},LQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return Xa(e,this.locale).length},isExported:!0},RQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return Xa(e,this.locale).toLowerCase()},isExported:!0},zQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=Xa(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},BQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return Xa(e,this.locale).replace(EQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},VQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},HQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},UQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},WQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=Xa(e,this.locale),o=I(n,this.locale),s=Xa(r,this.locale);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},GQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=Xa(e,this.locale),i=r.length;return r.substring(i-n,i)},isExported:!0},KQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale).toLowerCase(),i=Xa(t,this.locale).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},qQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=Xa(e,this.locale),a=Ze(Xa(t,this.locale)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),fo([l])},isExported:!1},JQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=Xa(e,this.locale),o=Xa(t,this.locale);if(o===``)return a;let s=Xa(n,this.locale),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},YQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=Xa(e,this.locale),i=R(t),a=0;return ao(n,(e,t)=>i&&Xa(t,this.locale)===``?e:(a++?e+r:``)+Xa(t,this.locale),``)},isExported:!0},XQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return fo(d)},isExported:!0},ZQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(Xa(e,this.locale))},isExported:!0},QQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return Xa(e,this.locale).toUpperCase()},isExported:!0},$Q={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},e$={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},t$={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},n$={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var r$=l({HYPERLINK:()=>i$});let i$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=Xa(t,this.locale)||n;return n===``?r:ut(r,n)},isExported:!0},a$=[{name:j(`Array`),functions:xW},{name:j(`Database`),functions:Eq},{name:j(`Date`),functions:HJ},{name:j(`Filter`),functions:EY},{name:j(`Financial`),functions:MY},{name:j(`Info`),functions:VX},{name:j(`Lookup`),functions:gZ},{name:j(`Logical`),functions:eZ},{name:j(`Math`),functions:ZW},{name:j(`Operator`),functions:BZ},{name:j(`Statistical`),functions:pK},{name:j(`Text`),functions:TQ},{name:j(`Engineering`),functions:wY},{name:j(`Web`),functions:r$},{name:j(`Parser`),functions:CQ}];for(let e of a$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Io.add(n,{isExported:!1,...r})}}let o$={},s$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},c$={autoCompleteProviders:uT,autofillModifiersRegistry:WL,autofillRulesRegistry:GL,cellMenuRegistry:TP,colMenuRegistry:RP,errorTypes:Pi,functionRegistry:Io,featurePluginRegistry:Iz,iconsOnCellRegistry:yL,statefulUIPluginRegistry:Lz,coreViewsPluginRegistry:Rz,corePluginRegistry:Fz,rowMenuRegistry:GP,sidePanelRegistry:qM,figureRegistry:Py,chartSidePanelComponentRegistry:QO,chartDataSourceSidePanelComponentRegistry:QD,chartComponentRegistry:dy,chartTypeRegistry:dS,chartSubtypeRegistry:Kv,chartDataSourceRegistry:uS,topbarMenuRegistry:EB,topbarComponentRegistry:KB,clickableCellRegistry:Gz,otRegistry:mR,inverseCommandRegistry:Jz,urlRegistry:Mu,cellPopoverRegistry:xw,numberFormatMenuRegistry:fB,repeatLocalCommandTransformRegistry:oz,repeatCommandTransformRegistry:az,clipboardHandlersRegistries:FF,pivotRegistry:zj,pivotTimeAdapterRegistry:rg,pivotSidePanelRegistry:eM,pivotNormalizationValueRegistry:Fg,supportedPivotPositionalFormulaRegistry:pI,pivotToFunctionValueRegistry:Ig,migrationStepRegistry:qC,chartJsExtensionRegistry:Vd,NonSquishableFunctionRegistry:Lo},l$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:jg,toFunctionPivotValue:Ng,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Bd,formatValue:H,createCurrencyFormat:Gl,ColorGenerator:ui,computeTextWidth:Sd,createEmptyWorkbookData:pw,createEmptySheet:fw,createEmptyExcelSheet:mw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:GB,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:Cg,getFirstPivotFunction:Wj,getNumberOfPivotFunctions:Kj,parseDimension:Eg,isDateOrDatetimeField:Dg,makeFieldProposal:qj,periodYearToComparable:ng,insertTokenAfterArgSeparator:Yj,insertTokenAfterLeftParenthesis:Xj,mergeContiguousZones:ar,getPivotHighlights:KA,pivotTimeAdapter:ig,UNDO_REDO_PIVOT_COMMANDS:IL,createPivotFormula:Ag,areDomainArgsFieldsValid:kg,splitReference:Zo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Hg,schemeToColorScale:Wh,isDateTimeFormat:Rl,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:cl,isFormula:qt,domainToColRowDomain:uj,collapseHierarchicalDisplayName:Jg,PositionMap:ZM},u$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Lu,urlRepresentation:Iu},d$={Checkbox:BT,Section:Z,Select:ky,RoundColorPicker:ET,ChartDataSeries:eO,ChartErrorSection:iO,ChartLabelRange:tO,ChartRangeDataSourceComponent:SO,ChartTitle:uO,ChartPanel:rk,ChartFigure:My,ChartJsComponent:qp,ClickableCellSortIcon:mI,ZoomableChartJsComponent:ry,Grid:fI,GridOverlay:VF,ScorecardChart:Hm,GaugeChartComponent:ly,LineConfigPanel:LO,BarConfigPanel:oO,PieChartDesignPanel:BO,GenericChartConfigPanel:aO,ChartWithAxisDesignPanel:yO,GenericZoomableChartDesignPanel:bO,LineChartDesignPanel:RO,GaugeChartConfigPanel:jO,GaugeChartDesignPanel:MO,ScorecardChartConfigPanel:UO,ScorecardChartDesignPanel:WO,GeoChartDesignPanel:FO,RadarChartDesignPanel:VO,WaterfallChartDesignPanel:ZO,ComboChartDesignPanel:OO,FunnelChartDesignPanel:AO,SunburstChartDesignPanel:GO,TreeMapChartDesignPanel:XO,ChartTypePicker:ek,FigureComponent:Fy,MenuPopover:Oy,Popover:wy,SelectionInput:FT,ValidationMessages:rO,AddDimensionButton:ZA,PivotDimensionGranularity:$A,PivotDimensionOrder:ej,PivotDimension:QA,PivotLayoutConfigurator:ij,PivotHTMLRenderer:gI,PivotDeferUpdate:JA,PivotTitleSection:aj,CogWheelMenu:XD,TextInput:WD,SidePanelCollapsible:Ow,RadioSelection:fO,GeoChartRegionSelectSection:NO,ChartDashboardMenu:Ay,FullScreenFigure:hI,NumberInput:sO,TopBar:RV,Composer:Qw},f$={useDragAndDropListItems:OT,useHighlights:sk,useHighlightsOnHover:ok},p$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:Sw,ComposerFocusStore:Er,CellComposerStore:xF,FindAndReplaceStore:Dk,HighlightStore:fT,DelayedHoveredCellStore:Iy,HoveredTableStore:RF,ModelStore:yr,NotificationStore:pT,RendererStore:Cr,SelectionInputStore:PT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:YM,PivotSidePanelStore:Qj,PivotMeasureDisplayPanelStore:WA,ClientFocusStore:qP,GridRenderer:YF};function m$(e,t){return Io.add(e,t),{addFunction:(e,t)=>m$(e,t)}}let h$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Ry,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:Uh},g$={...Fv,...bv};e.AbstractCellClipboardHandler=BL,e.AbstractChart=Jp,e.AbstractFigureClipboardHandler=dW,e.CellErrorType=M,e.ClientDisconnectedError=XR,e.CommandResult=Au,e.CompiledFormula=Bc,e.CorePlugin=vI,e.CoreViewPlugin=KI,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ro,e.DispatchResult=Ou,e.EvaluationError=N,e.LocalTransportService=qB,e.Model=WU,e.PivotRuntimeDefinition=oj,e.Registry=A,e.Revision=YR,e.SPREADSHEET_DIMENSIONS=s$,e.Spreadsheet=VV,e.SpreadsheetPivotTable=Dj,e.UIPlugin=HL,e.__info__=o$,e.addFunction=m$,e.addRenderingLayer=Sr,e.astToFormula=_F,e.canExecuteInReadonly=Du,e.categories=a$,e.chartHelpers=g$,e.components=d$,e.constants=h$,e.convertAstNodes=Ks,e.coreTypes=Tu,e.createAutocompleteArgumentsProvider=zz,e.findCellInNewZone=Kn,e.functionCache=Rc,e.getCaretDownSvg=Tb,e.getCaretUpSvg=Eb,e.helpers=l$,e.hooks=f$,e.invalidateCFEvaluationCommands=bu,e.invalidateChartEvaluationCommands=vu,e.invalidateDependenciesCommands=yu,e.invalidateEvaluationCommands=_u,e.isCoreCommand=Eu,e.isSheetDependent=du,e.iterateAstNodes=qs,e.links=u$,e.load=QC,e.lockedSheetAllowedCommands=wu,e.parse=Ws,e.parseTokens=Gs,e.readonlyAllowedCommands=Cu,e.registries=c$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=p$,e.tokenColors=Ke,e.tokenize=ls,o$.version=`19.3.20`,o$.date=`2026-09-10T05:38:03.233Z`,o$.hash=`e488e8d`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
956
|
+
`),`_rels/.rels`)}function HU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function UU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var WU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Bd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=ow(e,n);let o=QC(e,i);this.state=new rH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new eH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.clipRangesToSheet=this.range.clipRangesToSheet.bind(this.range),this.coreGetters.clipRangeToSheet=this.range.clipRangeToSheet.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new nH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Fz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Rz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Lz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Iz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new ZR(ZV({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new HV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new qB,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new UV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Ro));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Eu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ou(e.flat()):Ou.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(GU(e,t));dispatch=(e,t)=>{let n=GU(e,t),r=this.status;if(this.getters.isReadonly()&&!Du(n))return new Ou(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ou(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Eu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Eu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Eu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ou.Success};dispatchFromCorePlugin=(e,t)=>{let n=GU(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ou.Success};dispatchToHandlers(e,t){let n=Eu(t);for(let r of e)!n&&r instanceof vI||r.beforeHandle(t);for(let r of e)!n&&r instanceof vI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new qB};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=pw();for(let n of this.handlers)n instanceof vI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=hw();for(let t of this.handlers)t instanceof _I&&await t.exportForExcel(e);return e=x(e),NU(e)}};function GU(e,t={}){let n=x(t);return n.type=e,n}let KU=Object.freeze({value:null}),qU=Object.freeze({value:1}),JU={supportedChartTypes:Uh,fromExternalDefinition(e,t,n){let r=bf(n,t,e),i=ic(n,t,e.labelRange);return{...e,dataSets:r,labelRange:i}},fromContextCreation(e){return{type:`range`,dataSets:[],dataSetsHaveTitle:!1,labelRange:e.auxiliaryRange,...e.dataSource}},fromHierarchicalContextCreation(e){if(e.dataSource?.type!==`range`||e.hierarchicalDataSource!==void 0&&e.hierarchicalDataSource.type!==`range`)return{type:`range`,dataSets:[],dataSetsHaveTitle:!1};let t={type:`range`,dataSets:[],dataSetsHaveTitle:e.dataSource?.dataSetsHaveTitle??!1,labelRange:e.dataSource?.dataSets?.[0]?.dataRange};return e.hierarchicalDataSource?.dataSets.length?t=e.hierarchicalDataSource:e.auxiliaryRange&&(t={...t,dataSets:[{dataRange:e.auxiliaryRange,dataSetId:`0`}]}),t},validate:(e,t)=>t.checkValidations(e,Ef,Df),transform(e,t,{adaptRangeString:n}){let r;if(e.labelRange){let{changeType:i,range:a}=n(t,e.labelRange);i!==`REMOVE`&&(r=a)}let i=[];for(let r of e.dataSets){let e={...r},{changeType:a,range:o}=n(t,r.dataRange);a!==`REMOVE`&&(e.dataRange=o,i.push(e))}return{...e,dataSets:i,labelRange:r}},extractData:(e,t,n)=>YU(n,e),extractHierarchicalData(e,t,n){let r=e.dataSets,i=e.labelRange,a=ZU(n,r,i),o=QU(n,r),s={labelValues:a,dataSetsValues:o};return Of(a.length,o[0]?.data.length+(o[0]?.label===void 0?0:1),e.dataSetsHaveTitle||!1)&&a.shift(),s},adaptRanges(e,{applyChange:t}){let n=e.dataSets.map(e=>{let{range:n,changeType:r}=t(e.dataRange);if(r===`REMOVE`)return;let i;if(e.labelCell){let{range:n,changeType:r}=t(e.labelCell);r!==`REMOVE`&&(i=n)}return{...e,dataRange:n,labelCell:i}}).filter(w),r=e.labelRange;if(r){let{range:e,changeType:n}=t(r);r=n===`REMOVE`?void 0:e}let i=n;return{...e,dataSets:i,labelRange:r?.invalidSheetName||r?.invalidXc?void 0:r}},getDefinition(e,t,n){return{labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,type:`range`,dataSets:e.dataSets.map(e=>({dataSetId:e.dataSetId,dataRange:n.getRangeString(e.dataRange,t)})),dataSetsHaveTitle:e.dataSetsHaveTitle}},duplicateInDuplicatedSheet(e,t,n,r){return{...e,labelRange:vf(t,n,e.labelRange),dataSets:e.dataSets.map(e=>({...e,dataRange:rc(t,n,e.dataRange)}))}},getContextCreation:e=>({auxiliaryRange:e.labelRange,dataSource:e}),getHierarchicalContextCreation(e){let t=e.dataSets.at(-1)?.dataRange,n=e.dataSetsHaveTitle;return{auxiliaryRange:t,hierarchicalDataSource:e,dataSource:e.labelRange?{type:`range`,dataSets:[{dataRange:e.labelRange,dataSetId:`0`}],dataSetsHaveTitle:n}:{type:`range`,dataSets:[],dataSetsHaveTitle:n}}},toExcelDataSets(e,t,n){let r=e.dataSets,i=e.labelRange,a=r.map(e=>Sf(n,t,e)).filter(e=>e.range!==``&&e.range!==M.InvalidReference),o=r[0]?Xn(r[0].dataRange.zone):void 0;return{dataSets:a,labelRange:Cf(n,i,Of(i?Xn(i.zone):0,o,e.dataSetsHaveTitle))}}};function YU(e,t){let n=t.dataSets,r=t.labelRange,i=ZU(e,n,r),a=XU(e,n),o={labelValues:i,dataSetsValues:a},s=a.length?a[0]?.data.length+(a[0]?.label===void 0?0:1):0;return Of(i.length,s,t.dataSetsHaveTitle||!1)&&i.shift(),o}function XU(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${Ry.Series} ${parseInt(r)+1}`,a=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){let{sheetId:n,zone:r}=i.labelCell,a=e.getEvaluatedCell({sheetId:n,col:r.left,row:r.top});a&&(t=a.formattedValue)}let o=i.dataRange?$U(e,i):[];o.every(e=>!e.value||qu(e))&&o.filter(qu).length>1?o=o.map(e=>e.value&&!Ju(e)?qU:KU):o.every(e=>!U(e))&&(a=!0),n.push({data:o,label:t,hidden:a,dataSetId:i.dataSetId})}return n}function ZU(e,t,n){if(n){let{left:t}=n.zone;if(!n.invalidXc&&!n.invalidSheetName&&!e.isColHidden(n.sheetId,t))return e.getVisibleRangeValues(n)}if(t[0]){let n=$U(e,t[0]).length;return Array.from({length:n},()=>({value:``}))}return[]}function QU(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));let n=t.map(e=>({data:[],label:``,dataSetId:e.dataSetId})),r=e.getLocale(),i=t.map(t=>$U(e,t)).map(e=>e.map(({value:e,format:t})=>e===null?KU:{value:H(e,{format:t,locale:r})}));if(!i.length)return n;let a=Math.min(...i.map(e=>e.length)),o=[],s=t.length-1;for(let e=0;e<a;e++)for(let t=0;t<i.length;t++){let r=i[t][e];(r===void 0||r.value===null)&&t!==s&&(r=o[t]),r?.value!==o[t]?.value&&(o=o.slice(0,t),o[t]=r),n[t].data.push(r??KU)}return n.filter(e=>e.data.some(e=>e.value!==null))}function $U(e,t){if(t.dataRange){let n=t.labelCell?[t.labelCell.zone]:[],r=cn([t.dataRange.zone],n)[0];if(r===void 0)return[];let i=e.getRangeFromZone(t.dataRange.sheetId,r);return e.getVisibleRangeValues(i).map(e=>e.value===``?KU:e)}return[]}uS.add(`range`,JU),uS.add(`none`,{supportedChartTypes:[],fromExternalDefinition:()=>({type:`none`}),fromContextCreation:()=>({type:`none`}),fromHierarchicalContextCreation:()=>({type:`none`}),validate:()=>`Success`,transform:()=>({type:`none`}),extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]}),adaptRanges:e=>e,getDefinition:e=>e,duplicateInDuplicatedSheet:e=>e,getContextCreation:()=>({}),getHierarchicalContextCreation:()=>({}),toExcelDataSets:()=>({dataSets:[],labelRange:void 0})});function eW(e){return!CO.includes(e.horizontalGroupBy)||!CO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let tW={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,eW)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=a_(t,n(),e),{labels:i,datasets:a}=gp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...sh,indexAxis:`x`,layout:L_(t,r),scales:Qf(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:sv(t,r),chartShowValuesPlugin:Z_(t,r),chartColorScalePlugin:$f(t,r),background:{color:t.background}}}}}}},nW={sequence:15,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:xp(t,a)},options:{...sh,layout:I_(t,a),scales:Zf(t,a),plugins:{title:nv(t,e),legend:U_(t,a),tooltip:ov(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:wp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:cp(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:mv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}}}}},iW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=u_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Cp(t,a)},options:{...sh,layout:I_(t,a),scales:sp(t,a),plugins:{title:nv(t,e),tooltip:pv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},aW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=o_(t,YU(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:ap(t,a),plugins:{title:nv(t,e),legend:z_(t,a),tooltip:dv(t,a),chartShowValuesPlugin:$_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},oW={sequence:80,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=l_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...sh,layout:I_(t,a),scales:op(t,a),plugins:{title:nv(t,e),legend:G_(t,a),tooltip:fv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sW={sequence:60,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:yp(t,a)},options:{...sh,layout:I_(t,a),scales:rp(t,a),plugins:{title:nv(t,e),legend:H_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cW={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:Ep(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:K_(t,a),tooltip:hv(t,a),sunburstLabelsPlugin:Q_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},lW={sequence:100,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:jp(t,a)},options:{...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:gv(t,a),background:{color:t.background}},...i}}}}};dS.add(`bar`,xv),dS.add(`combo`,nW),dS.add(`line`,Mv),dS.add(`pie`,Nv),dS.add(`scorecard`,im),dS.add(`gauge`,Dv),dS.add(`scatter`,sW),dS.add(`waterfall`,Pv),dS.add(`pyramid`,aW),dS.add(`radar`,oW),dS.add(`geo`,iW),dS.add(`funnel`,rW),dS.add(`sunburst`,cW),dS.add(`treemap`,lW),dS.add(`calendar`,tW),Kv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var uW=class extends BL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},dW=class extends zL{copy(e){}},fW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Bd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=tk.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=tk.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=tk.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Bd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mW=class extends BL{uuidGenerator=new Bd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},hW=class extends BL{uuidGenerator=new Bd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},gW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Bd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},_W=class extends BL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},vW=class extends BL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},yW=class extends BL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(ZT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},bW=class extends BL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};FF.figureHandlers.add(`chart`,pW).add(`image`,gW).add(`carousel`,fW),FF.cellHandlers.add(`dataValidation`,hW).add(`cell`,VL).add(`sheet`,yW).add(`merge`,_W).add(`border`,uW).add(`table`,bW).add(`conditionalFormat`,mW).add(`references`,vW);var xW=l({ARRAYTOTEXT:()=>XW,ARRAY_CONSTRAIN:()=>wW,ARRAY_LITERAL:()=>TW,ARRAY_ROW:()=>EW,CHOOSECOLS:()=>DW,CHOOSEROWS:()=>OW,EXPAND:()=>kW,FLATTEN:()=>AW,FREQUENCY:()=>jW,HSTACK:()=>MW,MDETERM:()=>NW,MINVERSE:()=>PW,MMULT:()=>FW,SUMPRODUCT:()=>IW,SUMX2MY2:()=>RW,SUMX2PY2:()=>zW,SUMXMY2:()=>BW,TOCOL:()=>UW,TOROW:()=>WW,TRANSPOSE:()=>GW,VSTACK:()=>KW,WRAPCOLS:()=>qW,WRAPROWS:()=>JW});function SW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function CW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=co(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let wW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return co(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},TW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},EW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},DW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},OW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?co(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},kW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):co(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},AW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[To(e,e=>e===void 0?{value:``}:e)]},isExported:!1},jW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=To([e],e=>e.value).filter(e=>typeof e==`number`),r=To([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},MW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e)},isExported:!0},NW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return vh(t)?xh(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},PW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!vh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=xh(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},FW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Ch(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},IW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!_h(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function LW(e,t,n){if(!_h(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let RW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2-t**2)},isExported:!0},zW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2+t**2)},isExported:!0},BW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>(e-t)**2)},isExported:!0},VW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function HW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let UW={description:j(`Transforms a range of cells into a single column.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},WW={description:j(`Transforms a range of cells into a single row.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},GW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return co(n,r,(e,n)=>t[n][e])},isExported:!0},KW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e)},isExported:!0},qW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},JW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},YW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],XW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),YW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return sT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return fo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:Xa(e,this.locale))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var ZW=l({ABS:()=>$W,ACOS:()=>eG,ACOSH:()=>tG,ACOT:()=>nG,ACOTH:()=>rG,ASIN:()=>iG,ASINH:()=>aG,ATAN:()=>oG,ATAN2:()=>sG,ATANH:()=>cG,CEILING:()=>lG,CEILING_MATH:()=>dG,CEILING_PRECISE:()=>fG,COS:()=>pG,COSH:()=>mG,COT:()=>hG,COTH:()=>gG,COUNTBLANK:()=>_G,COUNTIF:()=>vG,COUNTIFS:()=>yG,COUNTUNIQUE:()=>bG,COUNTUNIQUEIFS:()=>xG,CSC:()=>SG,CSCH:()=>CG,DECIMAL:()=>wG,DEGREES:()=>TG,EXP:()=>EG,FLOOR:()=>DG,FLOOR_MATH:()=>kG,FLOOR_PRECISE:()=>AG,INT:()=>fK,ISEVEN:()=>jG,ISODD:()=>NG,ISO_CEILING:()=>MG,LN:()=>PG,LOG:()=>FG,MOD:()=>LG,MUNIT:()=>RG,ODD:()=>zG,PI:()=>BG,POWER:()=>VG,PRODUCT:()=>HG,RAND:()=>UG,RANDARRAY:()=>WG,RANDBETWEEN:()=>GG,ROUND:()=>KG,ROUNDDOWN:()=>qG,ROUNDUP:()=>JG,SEC:()=>YG,SECH:()=>XG,SEQUENCE:()=>ZG,SIN:()=>QG,SINH:()=>$G,SQRT:()=>eK,SUBTOTAL:()=>iK,SUM:()=>aK,SUMIF:()=>oK,SUMIFS:()=>sK,TAN:()=>cK,TANH:()=>lK,TRUNC:()=>dK});let QW=/^-?[a-z0-9]+$/i,$W={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},eG={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},tG={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},nG={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},rG={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},iG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},aG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},oG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},sG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},cG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},lG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function uG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let dG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:uG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},fG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:uG(I(e,this.locale),n),format:e?.format}},isExported:!0},pG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},mG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},hG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},gG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},_G={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ao(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},vG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},yG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},bG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return tg(e)}},xG={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return yo(t,(t,r)=>{let i=e[t]?.[r];Eo(i)&&n.add(i.value)},this.locale),n.size}},SG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},CG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},wG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!QW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},TG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},EG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},DG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function OG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let kG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:OG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},AG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:OG(I(e,this.locale),n),format:e?.format}},isExported:!0},jG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},MG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:uG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},NG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},PG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},FG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function IG(e,t){hh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let LG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:IG(I(e,this.locale),n),format:e?.format}},isExported:!0},RG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):bh(t)},isExported:!0},zG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},BG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},VG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},HG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},UG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},WG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},GG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},KG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},qG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},JG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},YG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},XG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},ZG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):co(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},QG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},$G={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},eK={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},tK={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},nK=Object.entries(tK).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),rK=Object.entries(tK).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),iK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...nK,...rK]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[tK[n]].apply(this,[[i]])},isExported:!0},aK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:eg(e,this.locale),format:za(t)}},isExported:!0},oK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return yo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},sK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},cK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},lK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function uK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let dK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:uK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},fK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var pK=l({AVEDEV:()=>CK,AVERAGE:()=>wK,AVERAGEA:()=>OK,AVERAGEIF:()=>kK,AVERAGEIFS:()=>AK,AVERAGE_WEIGHTED:()=>DK,CORREL:()=>QK,COUNT:()=>jK,COUNTA:()=>MK,COVAR:()=>NK,COVARIANCE_P:()=>PK,COVARIANCE_S:()=>FK,FORECAST:()=>IK,GROWTH:()=>LK,INTERCEPT:()=>RK,LARGE:()=>zK,LINEST:()=>BK,LOGEST:()=>VK,MATTHEWS:()=>HK,MAX:()=>UK,MAXA:()=>WK,MAXIFS:()=>GK,MEDIAN:()=>KK,MIN:()=>qK,MINA:()=>JK,MINIFS:()=>YK,PEARSON:()=>ZK,PERCENTILE:()=>$K,PERCENTILE_EXC:()=>eq,PERCENTILE_INC:()=>tq,POLYFIT_COEFFS:()=>nq,POLYFIT_FORECAST:()=>rq,QUARTILE:()=>iq,QUARTILE_EXC:()=>aq,QUARTILE_INC:()=>oq,RANK:()=>sq,RSQ:()=>cq,SLOPE:()=>lq,SMALL:()=>uq,SPEARMAN:()=>dq,STDEV:()=>fq,STDEVA:()=>hq,STDEVP:()=>gq,STDEVPA:()=>_q,STDEV_P:()=>pq,STDEV_S:()=>mq,STEYX:()=>vq,TREND:()=>yq,VAR:()=>bq,VARA:()=>Cq,VARP:()=>wq,VARPA:()=>Tq,VAR_P:()=>xq,VAR_S:()=>Sq});let mK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],hK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],gK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],_K=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],vK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function yK(e,t){let n=[],r=[],i=0,a=0;no([e],e=>{n.push(e),i+=1}),no([t],e=>{r.push(e),a+=1}),mh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function bK(e,t,n){let{flatDataX:r,flatDataY:i}=yK(e,t),a=i.length;hh(a),n&&hh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function xK(e,t,n,r){let i=0,a=n?so:oo,o=a(e,(e,t)=>(i+=1,e+t),0,r);hh(i),t&&hh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function SK(e,t,n,r){let i=I(t,r);mh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return no(e,e=>{let t=e?.value;typeof t==`number`&&(o=bo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),mh(s!==0,Do),n||mh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let CK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return oo(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},wK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Oh(e,this.locale),format:za(e[0])}},isExported:!0},TK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),EK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),DK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!_h(i,a))return new N(TK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(EK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(EK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},OK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=so(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},kK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return yo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},AK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return yo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},jK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Ah(e,this.locale)},isExported:!0},MK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return jh(e)},isExported:!0},NK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},PK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},FK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!0)},isExported:!0},IK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=yK(t,n);return r.length===0||i.length===0?new Ri(Do):Vh([i],[r],lo(B(e),e=>I(e,this.locale)),!0)},isExported:!0},LK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):zh(Vh(Bh(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},RK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[],[i]]=Fh([n],[r]);return i},isExported:!0},zK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},BK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Oo(`data_y`)):Fh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},VK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Oo(`data_y`));let i=Fh(Ka(t,`data_x`),Bh(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},HK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Dh(n,r),n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},UK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Mh(e,this.locale)},isExported:!0},WK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},KK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return ro(e,e=>{t.push(e)},this.locale),{value:SK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},qK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return Nh(e,this.locale)},isExported:!0},JK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},YK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function XK(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let ZK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return XK(e,t)},isExported:!0},QK=ZK,$K={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return tq.compute.bind(this)(e,t)},isExported:!0},eq={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!1,this.locale),format:za(e)}},isExported:!0},tq={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!0,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=yK(e,t);return i.length===0||a.length===0?new Ri(Do):Ih(a,i,I(n,this.locale),R(r))},isExported:!1},rq={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=yK(t,n);if(o.length===0||s.length===0)return new Ri(Do);let c=Ih(s,o,a,R(i)).flat();return lo(B(e),e=>Rh(c,I(e,this.locale),a))},isExported:!1},iq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){return oq.compute.bind(this)(e,t)},isExported:!0},aq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!1,this.locale),format:za(e)}},isExported:!0},oq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!0,this.locale),format:za(e)}},isExported:!0},sq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},cq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=XK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},lq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[i]]=Fh([n],[r]);return i},isExported:!0},uq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},dq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(t,e);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},fq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Sq.compute.bind(this)(...e))},isExported:!0},hq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Cq.compute.bind(this)(...e))},isExported:!0},gq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(wq.compute.bind(this)(...e))},isExported:!0},_q={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Tq.compute.bind(this)(...e))},isExported:!0},vq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);return n.length===0||r.length===0?new Ri(Do):Fh([n],[r],!0,!0)[1][2]},isExported:!0},yq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):Vh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},bq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Sq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},Cq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!0,this.locale)},isExported:!0},wq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Tq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!0,this.locale)},isExported:!0};var Eq=l({DAVERAGE:()=>kq,DCOUNT:()=>Aq,DCOUNTA:()=>jq,DGET:()=>Mq,DMAX:()=>Nq,DMIN:()=>Pq,DPRODUCT:()=>Fq,DSTDEV:()=>Iq,DSTDEVP:()=>Lq,DSUM:()=>Rq,DVAR:()=>zq,DVARP:()=>Bq});function Dq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)yo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Oq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],kq={description:j(`Average of a set of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Counts values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return jK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Counts values and text from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return MK.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Single value from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},Nq={description:j(`Maximum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Minimum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return qK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Product of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return HG.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Standard deviation of population sample from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Lq={description:j(`Standard deviation of entire population from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Rq={description:j(`Sum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return aK.compute.bind(this)([r])},isExported:!0},zq={description:j(`Variance of population sample from table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Bq={description:j(`Variance of a population from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wq.compute.bind(this)([r])},isExported:!0},Vq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hq=j(`There must be both positive and negative values in cashflow_amounts.`),Uq=e=>j(`The cost (%s) must be positive or null.`,e),Wq=e=>j(`The cost (%s) must be strictly positive.`,e),Gq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Jq=e=>j(`The discount (%s) must be different from -1.`,e),Yq=e=>j(`The discount (%s) must be strictly positive.`,e),Xq=e=>j(`The discount (%s) must be smaller than 1.`,e),Zq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Qq=e=>j(`The end_period (%s) must be positive or null.`,e),$q=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),eJ=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),tJ=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),nJ=e=>j(`The first_period (%s) must be strictly positive.`,e),rJ=e=>j(`The future_value (%s) must be strictly positive.`,e),iJ=e=>j(`The investment (%s) must be strictly positive.`,e),aJ=e=>j(`The issue (%s) must be positive or null.`,e),oJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),sJ=e=>j(`The last_period (%s) must be strictly positive.`,e),cJ=e=>j(`The life (%s) must be strictly positive.`,e),lJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),uJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),dJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),fJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),pJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),mJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),hJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),gJ=e=>j(`The period (%s) must be positive or null.`,e),_J=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),yJ=e=>j(`The period (%s) must be strictly positive.`,e),bJ=e=>j(`The present_value (%s) must be strictly positive.`,e),xJ=e=>j(`The price (%s) must be strictly positive.`,e),SJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),CJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),wJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),TJ=e=>j(`The rate (%s) must be positive or null.`,e),EJ=e=>j(`The rate (%s) must be strictly positive.`,e),DJ=e=>j(`The redemption (%s) must be strictly positive.`,e),OJ=e=>j(`The salvage (%s) must be positive or null.`,e),kJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),AJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),jJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),MJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),NJ=e=>j(`The start_period (%s) must be positive or null.`,e),PJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),FJ=e=>j(`The unit (%s) must be strictly positive.`,e),IJ=e=>j(`The yield (%s) must be positive or null.`,e);function LJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function RJ(e){return![0,1,2,3,4].includes(e)}function zJ(e){return![1,2,4].includes(e)}function BJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let VJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var HJ=l({DATE:()=>WJ,DATEDIF:()=>GJ,DATEVALUE:()=>KJ,DAY:()=>qJ,DAYS:()=>JJ,DAYS360:()=>YJ,EDATE:()=>XJ,EOMONTH:()=>ZJ,HOUR:()=>QJ,ISOWEEKNUM:()=>$J,MINUTE:()=>eY,MONTH:()=>tY,MONTH_END:()=>vY,MONTH_START:()=>_Y,NETWORKDAYS:()=>nY,NETWORKDAYS_INTL:()=>aY,NOW:()=>oY,QUARTER:()=>yY,QUARTER_END:()=>xY,QUARTER_START:()=>bY,SECOND:()=>sY,TIME:()=>cY,TIMEVALUE:()=>lY,TODAY:()=>uY,WEEKDAY:()=>dY,WEEKNUM:()=>fY,WORKDAY:()=>pY,WORKDAY_INTL:()=>mY,YEAR:()=>hY,YEARFRAC:()=>gY,YEAR_END:()=>CY,YEAR_START:()=>SY}),UJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(UJ||{});let WJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},GJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(UJ).includes(r))return new N(Wa(Object.values(UJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},KJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},qJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},JJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},YJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},XJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ZJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},QJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},$J={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},eY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},tY={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},nY={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return aY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function rY(e){let t=e?.value;if(typeof t==`string`){mh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return mh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let iY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],aY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},oY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:db(this.locale)}},isExported:!0},sY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},cY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},lY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},uY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},fY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return $J.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},pY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return mY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},mY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},hY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},gY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},_Y={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},vY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return ZJ.compute.bind(this)(e,{value:0})}},yY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},bY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},xY={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},SY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},CY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var wY=l({DELTA:()=>TY});let TY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var EY=l({FILTER:()=>OY,SORT:()=>kY,SORTN:()=>AY,UNIQUE:()=>jY});function DY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;mh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(wh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))mh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(wh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:gz(`desc`),asc:gz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let OY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>lo(B(e),e=>e.value));for(let e of r)if(!gh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!_h(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?fo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?fo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},kY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return fo(DY(fo(e),this.locale,...t))},isExported:!0},AY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=DY(fo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return fo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return fo(o.slice(0,e));return fo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return fo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return fo(e)}}},isExported:!1},jY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=fo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:fo(o):new N(j(`No unique values found`))},isExported:!0};var MY=l({ACCRINTM:()=>LY,AMORLINC:()=>RY,COUPDAYBS:()=>BY,COUPDAYS:()=>zY,COUPDAYSNC:()=>VY,COUPNCD:()=>HY,COUPNUM:()=>UY,COUPPCD:()=>WY,CUMIPMT:()=>GY,CUMPRINC:()=>KY,DB:()=>qY,DDB:()=>YY,DISC:()=>XY,DOLLARDE:()=>ZY,DOLLARFR:()=>QY,DURATION:()=>$Y,EFFECT:()=>eX,FV:()=>nX,FVSCHEDULE:()=>rX,INTRATE:()=>iX,IPMT:()=>oX,IRR:()=>cX,ISPMT:()=>lX,MDURATION:()=>uX,MIRR:()=>dX,NOMINAL:()=>fX,NPER:()=>pX,NPV:()=>hX,PDURATION:()=>gX,PMT:()=>vX,PPMT:()=>bX,PRICE:()=>SX,PRICEDISC:()=>CX,PRICEMAT:()=>wX,PV:()=>xX,RATE:()=>EX,RECEIVED:()=>DX,RRI:()=>OX,SLN:()=>kX,SYD:()=>AX,TBILLEQ:()=>NX,TBILLPRICE:()=>MX,TBILLYIELD:()=>PX,VDB:()=>FX,XIRR:()=>IX,XNPV:()=>LX,YIELD:()=>RX,YIELDDISC:()=>zX,YIELDMAT:()=>BX});let NY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],PY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],FY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)];function IY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){mh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,mh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let LY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(aJ(a));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(DJ(s));if(c<=0)return new N(EJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},RY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Wq(s));if(c<0)return new N(CJ(c));if(u<0)return new N(OJ(u));if(u>s)return new N(kJ(u,s));if(d<0)return new N(gJ(d));if(f<=0)return new N(EJ(f));if(RJ(p))return new N(Kq(p));if(c>l)return new N(SJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},zY={description:j(`Days in coupon period containing settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));if(s===1){let i=WY.compute.bind(this)(e,t,n,r).value,a=HY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},BY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=WY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},VY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=HY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=BY.compute.bind(this)(e,t,n,r);return I(zY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},HY={description:j(`Next coupon date after the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},UY={description:j(`Number of coupons between settlement and maturity.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},WY={description:j(`Last coupon date prior to or on the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},GY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=aX(c,e,u,l,0,d);return f},isExported:!0},KY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=yX(c,e,u,l,0,d);return f},isExported:!0},qY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(1>l||l>12)return new N(uJ(l));if(c>u)return new N(hJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},JY=`#,##0.00`,YY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(c>s)return new N(vJ(c,s));if(l<=0)return new N(qq(l));if(a===0||o>=a)return{value:0,format:JY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:JY};if(c<=1)return{value:a*u,format:JY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:JY}},isExported:!0},XY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},ZY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},QY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},$Y={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(zJ(u))return new N(Gq(u));if(RJ(d))return new N(Kq(d));if(c<0)return new N(TJ(c));if(l<0)return new N(IJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},eX={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(dJ(n)):r<=0?new N(_J(r)):(1+n/r)**+r-1},isExported:!0};function tX(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let nX={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},rX={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return ao([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},iX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(c<=0)return new N(iJ(c));if(s<=0)return new N(DJ(s));if(RJ(l))return new N(Kq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function aX(e,t,n,r,i,a){return _X(e,n,r,i,a)-yX(e,t,n,r,i,a)}let oX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:aX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},sX=.1,cX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${sX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:sX}){let n=I(t,this.locale);if(n<=-1)return new N(wJ(n));let r=!1,i=!1,a=[];if(ro([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Hq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:IY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},lX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(fJ(o)):-1*(s-a/o*s)*i},isExported:!0},uX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=$Y.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},dX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=fo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Hq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},fX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(Zq(n)):r<=0?new N(_J(r)):((n+1)**(1/r)-1)*r},isExported:!0},pX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function mX(e,t,n,r){let i=0;return oo(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let hX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Jq(n)):{value:mX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},gX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(EJ(r)):i<=0?new N(bJ(i)):a<=0?new N(rJ(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function _X(e,t,n,r,i){if(t<=0)throw new N(pJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let vX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:_X(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function yX(e,t,n,r,i,a){if(n<=0)throw new N(pJ(n));if(t<=0||t>n)throw new N(mJ(n));let o=_X(e,n,r,i,a);return a===1&&t===1?o:o+-tX(e,a===0?t-1:t-2,o,r+o*a,0)*e}let bX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:yX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},xX={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},SX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},CX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(Yq(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},wX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(MJ(o,c));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},TX=.1,EX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:TX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||TX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(pJ(o)):LJ([s,d,u])?l<=-1?new N(wJ(l)):(u-=s*c,d+=s*c,{value:IY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},DX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(lJ(a,o)):RJ(l)?new N(Kq(l)):s<=0?new N(iJ(s)):c<=0?new N(Yq(c)):s/(1-c*xa(a,o,l))},isExported:!0},OX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(pJ(r)):(a/i)**(1/r)-1},isExported:!0},kX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},AX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(yJ(s));if(o<=0)return new N(cJ(o));if(s>o)return new N(vJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function jX(e,t,n){return 100*(1-n*xa(e,t,2))}let MX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(lJ(r,i)):BJ(r,i,this.locale)?a<=0?new N(Yq(a)):a>=1?new N(Xq(a)):jX(r,i,a):new N(jJ(r,i))},isExported:!0},NX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(Yq(a));if(a>=1)return new N(Xq(a));let o=JJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=jX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},PX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(xJ(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},FX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(Uq(s));if(c<0)return new N(OJ(c));if(l<=0)return new N(cJ(l));if(u<0)return new N(NJ(u));if(d<0)return new N(Qq(d));if(u>d)return new N(PJ(u,d));if(d>l)return new N($q(d,l));if(f<=0)return new N(qq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},IX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:TX}){let r=I(n,this.locale);if(!_h(e,t))return new N(Vq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!LJ(i))return new N(Hq);if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=-1)return new N(wJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return IY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},LX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!_h(t,n))return new N(Vq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=0)return new N(EJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},RX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(IY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},zX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},BX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(o<c)return new N(AJ(o,c));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var VX=l({CELL:()=>UX,ISBLANK:()=>ZX,ISERR:()=>WX,ISERROR:()=>GX,ISFORMULA:()=>$X,ISLOGICAL:()=>KX,ISNA:()=>qX,ISNONTEXT:()=>JX,ISNUMBER:()=>YX,ISTEXT:()=>XX,NA:()=>QX});let HX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],UX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),HX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!HX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,HX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:ou(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},WX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},GX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},KX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},qX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},JX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!XX.compute.bind(this)(e)},isExported:!0},YX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},XX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},ZX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},QX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},$X={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var eZ=l({AND:()=>tZ,FALSE:()=>nZ,IF:()=>rZ,IFERROR:()=>iZ,IFNA:()=>aZ,IFS:()=>oZ,NOT:()=>sZ,OR:()=>cZ,SWITCH:()=>lZ,TRUE:()=>uZ,XOR:()=>dZ});let tZ={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Qh(e);return n?t:new N(Do)},isExported:!0},nZ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rZ={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Eh(e)?po(rZ.compute,[e,t,n]):(R(wh(e))?t:n)??{value:0}},isExported:!0},iZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Eh(e)?po(iZ.compute,[e,t]):(F(wh(e)?.value)?t:e)??{value:0}},isExported:!0},aZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Eh(e)?po(aZ.compute,[e,t]):(wh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},oZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Eh(e[0]))return po(oZ.compute,e);let t=R(wh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},sZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},cZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=$h(e);return n?t:new N(Do)},isExported:!0},lZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},uZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},dZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return ho(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Do)},isExported:!0};function fZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function pZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function mZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function hZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var gZ=l({ADDRESS:()=>yZ,CHOOSE:()=>IZ,COLUMN:()=>bZ,COLUMNS:()=>xZ,DROP:()=>LZ,FORMULATEXT:()=>zZ,HLOOKUP:()=>SZ,INDEX:()=>CZ,INDIRECT:()=>wZ,LOOKUP:()=>TZ,MATCH:()=>EZ,OFFSET:()=>FZ,PIVOT:()=>PZ,PIVOT_HEADER:()=>NZ,PIVOT_VALUE:()=>MZ,ROW:()=>DZ,ROWS:()=>OZ,TAKE:()=>RZ,VLOOKUP:()=>kZ,XLOOKUP:()=>jZ});let _Z=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],vZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],yZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),_Z),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(yh(a));if(o<1)return new N(yh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Qo(L(i),l)},isExported:!0},bZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:co(t.length,1,e=>({value:r+e+1}))},isExported:!0},xZ={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},SZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?bo(a,e,`nextSmaller`,`asc`,a.length,o):xo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},CZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},wZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),_Z)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},TZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=bo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},EZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=bo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=xo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=bo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},DZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:co(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},OZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},kZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?bo(a,e,`nextSmaller`,`asc`,a[0].length,o):xo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},AZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},jZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=AZ[o],m=s===-1,h=s===2||s===-2?bo(c,e,p,s===2?`asc`:`desc`,f,d):xo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},MZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=fZ(r,this.getters);pZ(a,i,this.getters),mZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);hZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},NZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=fZ(n,this.getters);mZ(t);let i=this.getters.getPivot(r);hZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},PZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=fZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=qg(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));hZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(qy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Rg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},FZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),co(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},IZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},LZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},RZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},zZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var BZ=l({ADD:()=>VZ,CONCAT:()=>HZ,DIVIDE:()=>UZ,EQ:()=>qZ,GT:()=>YZ,GTE:()=>XZ,LT:()=>ZZ,LTE:()=>QZ,MINUS:()=>$Z,MULTIPLY:()=>eQ,NE:()=>tQ,POW:()=>nQ,SPILLED_RANGE:()=>rQ,UMINUS:()=>iQ,UNARY_PERCENT:()=>aQ,UPLUS:()=>oQ});let VZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},HZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return Xa(e,this.locale)+Xa(t,this.locale)},isExported:!0},UZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function WZ(e){return e===void 0||e.value===null}let GZ={number:0,string:``,boolean:!1};function KZ(e,t,n=2e-16){return Math.abs(e-t)<n}let qZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=WZ(e)?GZ[typeof t?.value]:e?.value,r=WZ(t)?GZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:KZ(n,r)}:{value:n===r}}};function JZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=WZ(e)?GZ[typeof t?.value]:e?.value,i=WZ(t)?GZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let YZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!KZ(e,t)&&e>t:e>t)}},XZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?KZ(e,t)||e>t:e>=t)}},ZZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=XZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=YZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},$Z={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},eQ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},tQ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=qZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},nQ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return VG.compute.bind(this)(e,t)}},rQ={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),co(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},iQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},aQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},oQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),sQ={transform:e=>e,inverseTransform:e=>e},cQ=1e-10,lQ=.0254,uQ=lQ/72,dQ=.3048,fQ=.9144,pQ=1609.34,mQ=1852,hQ=946073047258e4,gQ={g:{...sQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...sQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(cQ),category:`distance`},Picapt:{...$(uQ),category:`distance`},pica:{...$(lQ/6),category:`distance`},in:{...$(lQ),category:`distance`},ft:{...$(dQ),category:`distance`},yd:{...$(fQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(pQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(mQ),category:`distance`},ly:{...$(hQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...sQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...sQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...sQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...sQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...sQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...sQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...sQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...sQ,category:`volume`,order:3},"ang^3":{...$(cQ**3),category:`volume`,order:3},"Picapt^3":{...$(uQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(lQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(dQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(fQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(pQ**3),category:`volume`,order:3},"Nmi^3":{...$(mQ**3),category:`volume`,order:3},"ly^3":{...$(hQ**3),category:`volume`,order:3},"m^2":{...sQ,category:`area`,order:2},"ang^2":{...$(cQ**2),category:`area`,order:2},"Picapt^2":{...$(uQ**2),category:`area`,order:2},"in^2":{...$(lQ**2),category:`area`,order:2},"ft^2":{...$(dQ**2),category:`area`,order:2},"yd^2":{...$(fQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(pQ**2),category:`area`,order:2},"Nmi^2":{...$(mQ**2),category:`area`,order:2},"ly^2":{...$(hQ**2),category:`area`,order:2},bit:{...sQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...sQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},_Q={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},vQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},yQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},bQ=Object.entries(gQ).map(([e,t])=>({value:e,label:xQ(t.category)}));function xQ(e){return yQ[e]??``}function SQ(e){for(let[t,n]of Object.entries(vQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=gQ[r];if(!i&&_Q[r]&&(i=gQ[_Q[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var CQ=l({CONVERT:()=>wQ});let wQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),bQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),bQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=SQ(i),s=SQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,xQ(o.category),xQ(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var TQ=l({CHAR:()=>kQ,CLEAN:()=>AQ,CONCATENATE:()=>jQ,EXACT:()=>MQ,FIND:()=>NQ,FORMAT_LARGE_NUMBER:()=>PQ,JOIN:()=>FQ,LEFT:()=>IQ,LEN:()=>LQ,LOWER:()=>RQ,MID:()=>zQ,PROPER:()=>BQ,REGEXEXTRACT:()=>HQ,REGEXREPLACE:()=>UQ,REGEXTEST:()=>VQ,REPLACE:()=>WQ,RIGHT:()=>GQ,SEARCH:()=>KQ,SPLIT:()=>qQ,SUBSTITUTE:()=>JQ,TEXT:()=>$Q,TEXTAFTER:()=>t$,TEXTBEFORE:()=>n$,TEXTJOIN:()=>YQ,TEXTSPLIT:()=>XQ,TRIM:()=>ZQ,UPPER:()=>QQ,VALUE:()=>e$});let EQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,DQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],OQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],kQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},AQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=Xa(e,this.locale),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},jQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ao(e,(e,t)=>e+Xa(t,this.locale),``)},isExported:!0},MQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return Xa(e,this.locale)===Xa(t,this.locale)},isExported:!0},NQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale),i=Xa(t,this.locale),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},PQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Ql(e,t,this.locale)}}},FQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=Xa(e,this.locale);return ao(t,(e,t)=>(e?e+n:``)+Xa(t,this.locale),``)}},IQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):Xa(e,this.locale).substring(0,n)},isExported:!0},LQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return Xa(e,this.locale).length},isExported:!0},RQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return Xa(e,this.locale).toLowerCase()},isExported:!0},zQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=Xa(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},BQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return Xa(e,this.locale).replace(EQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},VQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},HQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},UQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},WQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=Xa(e,this.locale),o=I(n,this.locale),s=Xa(r,this.locale);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},GQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=Xa(e,this.locale),i=r.length;return r.substring(i-n,i)},isExported:!0},KQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale).toLowerCase(),i=Xa(t,this.locale).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},qQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=Xa(e,this.locale),a=Ze(Xa(t,this.locale)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),fo([l])},isExported:!1},JQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=Xa(e,this.locale),o=Xa(t,this.locale);if(o===``)return a;let s=Xa(n,this.locale),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},YQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=Xa(e,this.locale),i=R(t),a=0;return ao(n,(e,t)=>i&&Xa(t,this.locale)===``?e:(a++?e+r:``)+Xa(t,this.locale),``)},isExported:!0},XQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return fo(d)},isExported:!0},ZQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(Xa(e,this.locale))},isExported:!0},QQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return Xa(e,this.locale).toUpperCase()},isExported:!0},$Q={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},e$={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},t$={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},n$={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var r$=l({HYPERLINK:()=>i$});let i$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=Xa(t,this.locale)||n;return n===``?r:ut(r,n)},isExported:!0},a$=[{name:j(`Array`),functions:xW},{name:j(`Database`),functions:Eq},{name:j(`Date`),functions:HJ},{name:j(`Filter`),functions:EY},{name:j(`Financial`),functions:MY},{name:j(`Info`),functions:VX},{name:j(`Lookup`),functions:gZ},{name:j(`Logical`),functions:eZ},{name:j(`Math`),functions:ZW},{name:j(`Operator`),functions:BZ},{name:j(`Statistical`),functions:pK},{name:j(`Text`),functions:TQ},{name:j(`Engineering`),functions:wY},{name:j(`Web`),functions:r$},{name:j(`Parser`),functions:CQ}];for(let e of a$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Io.add(n,{isExported:!1,...r})}}let o$={},s$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},c$={autoCompleteProviders:uT,autofillModifiersRegistry:WL,autofillRulesRegistry:GL,cellMenuRegistry:TP,colMenuRegistry:RP,errorTypes:Pi,functionRegistry:Io,featurePluginRegistry:Iz,iconsOnCellRegistry:yL,statefulUIPluginRegistry:Lz,coreViewsPluginRegistry:Rz,corePluginRegistry:Fz,rowMenuRegistry:GP,sidePanelRegistry:qM,figureRegistry:Py,chartSidePanelComponentRegistry:QO,chartDataSourceSidePanelComponentRegistry:QD,chartComponentRegistry:dy,chartTypeRegistry:dS,chartSubtypeRegistry:Kv,chartDataSourceRegistry:uS,topbarMenuRegistry:EB,topbarComponentRegistry:KB,clickableCellRegistry:Gz,otRegistry:mR,inverseCommandRegistry:Jz,urlRegistry:Mu,cellPopoverRegistry:xw,numberFormatMenuRegistry:fB,repeatLocalCommandTransformRegistry:oz,repeatCommandTransformRegistry:az,clipboardHandlersRegistries:FF,pivotRegistry:zj,pivotTimeAdapterRegistry:rg,pivotSidePanelRegistry:eM,pivotNormalizationValueRegistry:Fg,supportedPivotPositionalFormulaRegistry:pI,pivotToFunctionValueRegistry:Ig,migrationStepRegistry:qC,chartJsExtensionRegistry:Vd,NonSquishableFunctionRegistry:Lo},l$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:jg,toFunctionPivotValue:Ng,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Bd,formatValue:H,createCurrencyFormat:Gl,ColorGenerator:ui,computeTextWidth:Sd,createEmptyWorkbookData:pw,createEmptySheet:fw,createEmptyExcelSheet:mw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:GB,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:Cg,getFirstPivotFunction:Wj,getNumberOfPivotFunctions:Kj,parseDimension:Eg,isDateOrDatetimeField:Dg,makeFieldProposal:qj,periodYearToComparable:ng,insertTokenAfterArgSeparator:Yj,insertTokenAfterLeftParenthesis:Xj,mergeContiguousZones:ar,getPivotHighlights:KA,pivotTimeAdapter:ig,UNDO_REDO_PIVOT_COMMANDS:IL,createPivotFormula:Ag,areDomainArgsFieldsValid:kg,splitReference:Zo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Hg,schemeToColorScale:Wh,isDateTimeFormat:Rl,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:cl,isFormula:qt,domainToColRowDomain:uj,collapseHierarchicalDisplayName:Jg,PositionMap:ZM},u$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Lu,urlRepresentation:Iu},d$={Checkbox:BT,Section:Z,Select:ky,RoundColorPicker:ET,ChartDataSeries:eO,ChartErrorSection:iO,ChartLabelRange:tO,ChartRangeDataSourceComponent:SO,ChartTitle:uO,ChartPanel:rk,ChartFigure:My,ChartJsComponent:qp,ClickableCellSortIcon:mI,ZoomableChartJsComponent:ry,Grid:fI,GridOverlay:VF,ScorecardChart:Hm,GaugeChartComponent:ly,LineConfigPanel:LO,BarConfigPanel:oO,PieChartDesignPanel:BO,GenericChartConfigPanel:aO,ChartWithAxisDesignPanel:yO,GenericZoomableChartDesignPanel:bO,LineChartDesignPanel:RO,GaugeChartConfigPanel:jO,GaugeChartDesignPanel:MO,ScorecardChartConfigPanel:UO,ScorecardChartDesignPanel:WO,GeoChartDesignPanel:FO,RadarChartDesignPanel:VO,WaterfallChartDesignPanel:ZO,ComboChartDesignPanel:OO,FunnelChartDesignPanel:AO,SunburstChartDesignPanel:GO,TreeMapChartDesignPanel:XO,ChartTypePicker:ek,FigureComponent:Fy,MenuPopover:Oy,Popover:wy,SelectionInput:FT,ValidationMessages:rO,AddDimensionButton:ZA,PivotDimensionGranularity:$A,PivotDimensionOrder:ej,PivotDimension:QA,PivotLayoutConfigurator:ij,PivotHTMLRenderer:gI,PivotDeferUpdate:JA,PivotTitleSection:aj,CogWheelMenu:XD,TextInput:WD,SidePanelCollapsible:Ow,RadioSelection:fO,GeoChartRegionSelectSection:NO,ChartDashboardMenu:Ay,FullScreenFigure:hI,NumberInput:sO,TopBar:RV,Composer:Qw},f$={useDragAndDropListItems:OT,useHighlights:sk,useHighlightsOnHover:ok},p$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:Sw,ComposerFocusStore:Er,CellComposerStore:xF,FindAndReplaceStore:Dk,HighlightStore:fT,DelayedHoveredCellStore:Iy,HoveredTableStore:RF,ModelStore:yr,NotificationStore:pT,RendererStore:Cr,SelectionInputStore:PT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:YM,PivotSidePanelStore:Qj,PivotMeasureDisplayPanelStore:WA,ClientFocusStore:qP,GridRenderer:YF};function m$(e,t){return Io.add(e,t),{addFunction:(e,t)=>m$(e,t)}}let h$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Ry,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:Uh},g$={...Fv,...bv};e.AbstractCellClipboardHandler=BL,e.AbstractChart=Jp,e.AbstractFigureClipboardHandler=dW,e.CellErrorType=M,e.ClientDisconnectedError=XR,e.CommandResult=Au,e.CompiledFormula=Bc,e.CorePlugin=vI,e.CoreViewPlugin=KI,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ro,e.DispatchResult=Ou,e.EvaluationError=N,e.LocalTransportService=qB,e.Model=WU,e.PivotRuntimeDefinition=oj,e.Registry=A,e.Revision=YR,e.SPREADSHEET_DIMENSIONS=s$,e.Spreadsheet=VV,e.SpreadsheetPivotTable=Dj,e.UIPlugin=HL,e.__info__=o$,e.addFunction=m$,e.addRenderingLayer=Sr,e.astToFormula=_F,e.canExecuteInReadonly=Du,e.categories=a$,e.chartHelpers=g$,e.components=d$,e.constants=h$,e.convertAstNodes=Ks,e.coreTypes=Tu,e.createAutocompleteArgumentsProvider=zz,e.findCellInNewZone=Kn,e.functionCache=Rc,e.getCaretDownSvg=Tb,e.getCaretUpSvg=Eb,e.helpers=l$,e.hooks=f$,e.invalidateCFEvaluationCommands=bu,e.invalidateChartEvaluationCommands=vu,e.invalidateDependenciesCommands=yu,e.invalidateEvaluationCommands=_u,e.isCoreCommand=Eu,e.isSheetDependent=du,e.iterateAstNodes=qs,e.links=u$,e.load=QC,e.lockedSheetAllowedCommands=wu,e.parse=Ws,e.parseTokens=Gs,e.readonlyAllowedCommands=Cu,e.registries=c$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=p$,e.tokenColors=Ke,e.tokenize=ls,o$.version=`19.3.21`,o$.date=`2026-09-18T05:27:19.223Z`,o$.hash=`6577e59`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|