@odoo/o-spreadsheet 19.4.0-alpha.12 → 19.4.0-alpha.13

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.
@@ -14,7 +14,7 @@ stores.inject(MyMetaStore, storeInstance);
14
14
  `,e.endsWith(`{`)&&n++;return t.trim()}let Su=bc.content,Cu={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},wu={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`,"#":`SPILLED.RANGE`},Tu={},Eu=new Intl.Collator(`en`,{sensitivity:`accent`});var Du=class e{sheetId;tokens;literalValues;symbols;isBadExpression;normalizedFormula;execute;rangeDependencies;hasDependencies;constructor(e,t,n,r,i,a,o,s){this.sheetId=e,this.tokens=t,this.literalValues=n,this.symbols=r,this.isBadExpression=a,this.normalizedFormula=o,this.execute=s,this.hasDependencies=i?.length>0,this.tokens.forEach(e=>{[`REFERENCE`,`NUMBER`,`STRING`,`INVALID_REFERENCE`].includes(e.type)&&(e.value=`__NO_REAL_VALUE__`)}),this.rangeDependencies=i}getTokens(e,t){let n=0,r=0,i=0;return this.isBadExpression||this.tokens.forEach(a=>{switch(a.type){case`REFERENCE`:case`INVALID_REFERENCE`:a.value=e.getRangeString(this.rangeDependencies[n++],this.sheetId,t);break;case`NUMBER`:a.value=this.literalValues.numbers[r++].value.toString();break;case`STRING`:a.value=`"${this.literalValues.strings[i++].value}"`;break}}),this.tokens}getAst(e){return Dl(this.getTokens(e))}toFormulaString(e,t){return this.isBadExpression?this.normalizedFormula:Gt(this.getTokens(e,t).filter(e=>e.type!==`SPACE`).map(e=>e.value))}getNamedRangesInFormula(e){let t=[];for(let n=0;n<this.tokens.length;n++)if(su(this.tokens,n)){let r=e.getNamedRange(this.tokens[n].value);r&&t.push(r)}return t}usesSymbol(e){return this.symbols.some(t=>Eu.compare(t,e)===0)}areAllFunctionsExportableToExcel(){return this.isBadExpression?!1:!kl(Dl(this.tokens)).some(e=>e.type===`FUNCALL`&&!Su[e.value.toUpperCase()]?.isExported)}getFunctionsFromTokens(e,t){return this.isBadExpression||!e.some(e=>this.usesSymbol(e))?[]:kl(this.getAst(t)).filter(t=>t.type===`FUNCALL`&&e.includes(t.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}isFirstNonWhitespaceSymbol(e){let t=this.tokens.find((e,t)=>t>0&&e.type!==`SPACE`);return t?.type===`SYMBOL`&&t.value.toUpperCase()===e}adaptCompiledFormula(t,n){let r=[],i=!1;for(let e of this.rangeDependencies){let n=t(e);r.push(n.range),n.changeType!==`NONE`&&(i=!0)}let a=this.renameNamedRangeTokens(n);return i||a?new e(this.sheetId,a?.newTokens||this.tokens,this.literalValues,a?.newSymbols||this.symbols,r,this.isBadExpression,Au(a?.newTokens||this.tokens),this.execute):this}renameNamedRangeTokens(e){let t=!1,n=[],r=[];for(let i=0;i<this.tokens.length;i++){let a=this.tokens[i];if(su(this.tokens,i)){let n=e(this.tokens[i].value);n!==this.tokens[i].value&&(t=!0,a={...this.tokens[i],value:n})}n.push(a),a.type===`SYMBOL`&&r.push(a.value)}return t?{newSymbols:r,newTokens:n}:void 0}static IsBadExpression(e){return Ou(ml(e)).isBadExpression}static CopyWithDependencies(t,n,r){return new e(n,t.tokens,t.literalValues,t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CopyWithDependenciesAndLiteral(t,n,r,i,a){return new e(n,t.tokens,{numbers:i,strings:a},t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CompileForSerializedFormula(t,n){let r=Ou(n.tokens);return new e(t,n.tokens,n.literalValues,n.symbols,n.rangeDependencies,n.isBadExpression,n.normalizedFormula,r.execute)}static Compile(t,n,r){let i=Ou(ml(t));return new e(n,i.tokens,i.literalValues,i.symbols,i.dependencies.map(e=>r.getRangeFromSheetXC(n,e)),i.isBadExpression,i.normalizedFormula,i.execute)}};function Ou(e){try{return ku(e)}catch(t){if(!(t instanceof N))throw t;return{tokens:e,literalValues:{numbers:[],strings:[]},symbols:[],dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function ku(e){let{dependencies:t,literalValues:n,symbols:r}=ju(e),i=Au(e);if(!Tu[i]){let t=Dl([...e]),n=new yu,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new Ra(j(`Invalid formula`));let u=o(t),d=new _u;d.append(u),d.append(hu`return ${u.returnExpression};`),Tu[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=Su[e.value.toUpperCase()];if(!n)throw new Ha(j(`Unknown function: "%s"`,e.value));Mu(e);let r=[],i=oc(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i[e].index],s=t[e],c=(a.type||[]).some(e=>Nu(e));r.push(o(s,c))}return r}function o(e,t=!1){let i=new _u(n);switch(e.debug&&(i.append(hu`debugger;`),i.append(hu`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return i.return(hu`{ value: ${e.value} }`);case`NUMBER`:return i.return(hu`this.literalValues.numbers[${c++}]`);case`STRING`:return i.return(hu`this.literalValues.strings[${s++}]`);case`REFERENCE`:return i.return(hu`${e.value.includes(`:`)||t?hu`range`:hu`ref`}(deps[${l++}])`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());i.append(...n);let u=e.value.toUpperCase();if(!Object.hasOwn(Su,u))throw Error(`Unknown function: "${u}"`);let d=mu(u);return i.return(hu`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`ARRAY`:return o({type:`FUNCALL`,value:`ARRAY.LITERAL`,args:e.value.map(e=>({type:`FUNCALL`,value:`ARRAY.ROW`,args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case`UNARY_OPERATION`:{if(!Object.hasOwn(wu,e.value))throw Error(`Unknown operator: "${e.value}"`);let t=mu(wu[e.value]),n=o(e.operand,e.value===`#`).assignResultToVariable();return i.append(n),i.return(hu`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{if(!Object.hasOwn(Cu,e.value))throw Error(`Unknown operator: "${e.value}"`);let t=mu(Cu[e.value]),n=o(e.left,!1).assignResultToVariable(),r=o(e.right,!1).assignResultToVariable();return i.append(n),i.append(r),i.return(hu`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let f=r.indexOf(e.value);return i.return(hu`getSymbolValue(this.symbols[${f}], ${t})`);case`EMPTY`:return i.return(hu`undefined`)}}}return{execute:Tu[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function Au(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function ju(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=Tt(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=Da(i.value,R);t.numbers.push({value:e});break}case`SYMBOL`:r.push(Tt(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function Mu(e){let t=e.args.length,n=e.value.toUpperCase(),r=Su[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new Ra(j(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new Ra(j(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrOptionalNonRepeatingArgs;if(o>0)throw new Ra(j(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrOptionalNonRepeatingArgs,nbrValueRemaining:o}))}}function Nu(e){return e.startsWith(`RANGE`)}let Pu=function(e){return e.boolean=`boolean`,e.number=`number`,e.text=`text`,e.empty=`empty`,e.error=`error`,e}({});function Fu(e){return`sheetId`in e}function Iu(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function Lu(e){return`target`in e&&`sheetId`in e}function Ru(e){return`ranges`in e}function zu(e){return`col`in e&&`row`in e&&`sheetId`in e}function Bu(e){return`sheetId`in e&&`zone`in e}let Vu=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`,`CREATE_NAMED_RANGE`,`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`]),Hu=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),Uu=new Set([`MOVE_RANGES`]),Wu=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Gu=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),Ku=new Set([`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`]),qu=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`SET_ZOOM`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`,`UPDATE_CHART_REGION`,`UPDATE_CAROUSEL_ACTIVE_ITEM`,`UPDATE_PIVOT`]),Ju=new Set(`LOCK_SHEET.UNLOCK_SHEET.MOVE_SHEET.DUPLICATE_SHEET.CREATE_SHEET.HIDE_SHEET.SHOW_SHEET.COPY.START.SCROLL_TO_CELL.ACTIVATE_SHEET.RESIZE_SHEETVIEW.SET_VIEWPORT_OFFSET.SET_FORMULA_VISIBILITY.SELECT_FIGURE.EVALUATE_CHARTS.EVALUATE_CELLS.REQUEST_UNDO.REQUEST_REDO.REPLACE_SEARCH.SET_ZOOM.UPDATE_CAROUSEL_ACTIVE_ITEM.DUPLICATE_PIVOT_IN_NEW_SHEET.UPDATE_FILTER.ACTIVATE_NEXT_SHEET.ACTIVATE_PREVIOUS_SHEET.SCROLL_TO_CELL.SHIFT_VIEWPORT_DOWN.SHIFT_VIEWPORT_UP`.split(`.`)),Yu=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.LOCK_SHEET.UNLOCK_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.CREATE_CAROUSEL.UPDATE_CAROUSEL.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.DELETE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.CREATE_NAMED_RANGE.UPDATE_NAMED_RANGE.DELETE_NAMED_RANGE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Xu(e){return Yu.has(e.type)}function Zu(e){return qu.has(e.type)}var Qu=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return $u}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let $u=new Qu,ed=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.EmptyTarget=`EmptyTarget`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidYRange=`InvalidYRange`,e.InvalidXRange=`InvalidXRange`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidBubbleSizeRange=`InvalidBubbleSizeRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptySelectedRange=`EmptySelectedRange`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotIdTaken=`PivotIdTaken`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e.InvalidPivotCustomField=`InvalidPivotCustomField`,e.MissingFigureArguments=`MissingFigureArguments`,e.InvalidCarouselItem=`InvalidCarouselItem`,e.SheetLocked=`SheetLocked`,e.InvalidZoomLevel=`InvalidZoomLevel`,e.NamedRangeNameAlreadyExists=`NamedRangeNameAlreadyExists`,e.NamedRangeInvalidName=`NamedRangeInvalidName`,e.NamedRangeNameLooksLikeCellReference=`NamedRangeNameLooksLikeCellReference`,e.NamedRangeNotFound=`NamedRangeNotFound`,e.SubCommandOnly=`SubCommandOnly`,e}({});function td(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let nd=new O;function rd(e,t){return e=td(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}nd.add(`sheet_URL`,{match:e=>Rt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=Bt(e);return t.tryGetSheetName(n)||j(`Invalid sheet`)},open(e,t){let n=Bt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:j(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0,title:j(`Sheets`),getLinkProposals(e){return e.model.getters.getSheetIds().map(t=>{let n=e.model.getters.getSheet(t);return{...this.createLink(zt(t),n.name),icon:`o-spreadsheet-Icon.INSERT_SHEET`}})}});let id={createLink:rd,match:e=>Pt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0,title:j(`Web`)};function ad(e){return nd.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||id}function od(e,t){return ad(e.url).urlRepresentation(e.url,t)}function sd(e,t,n){ad(e.url).open(e.url,t,n)}function cd(e){if(typeof e==`string`){if(Nt(e)){let{label:t,url:n}=It(e);return ad(n).createLink(n,t)}else if(Pt(e))return rd(e)}}function ld(e,t,n){return hd({value:Xs(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format,origin:n},t.locale,n)}function ud(e,t,n,r,i,a,o){return n.startsWith(`=`)?fd(e,t,n,r,i,a):dd(e,t,n,r,i,o)}function dd(e,t,n,r,i,a){let o=e.getLocale(),s=md(n,o);if(!r&&typeof s==`number`){let e=Ns(n,o);if(a?.avoidAutomaticDateFormat&&e)return{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:n};r=e||Ps(n)}else r||=void 0;return!Xs(r)&&!n.startsWith(`'`)&&!Ja(n)&&(n=F(s)),{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:s}}function fd(e,t,n,r,i,a){return pd(t,Du.Compile(n,a,e),r,i)}function pd(e,t,n,r){return{id:e,format:n,style:r,isFormula:!0,compiledFormula:t}}function md(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith(`'`))return e.slice(1);if(e===``)return null;if(e.includes(`
15
15
  `))return e;if(Ta(e,R))return Da(e,R);let n=Yi(e,t);return n?n.value:At(e)?e.toUpperCase()===`TRUE`:e}function hd(e,t=R,n,r){let i=cd(e.value);if(!i)return Ed(gd(e,t,n,r),e.origin??n);let a=md(i.label,t);return Ed({...gd({value:a,format:e.format||(typeof a==`number`?Ns(i.label,t)||Ps(i.label):void 0)},t,n,r),link:i},e.origin??n)}function gd(e,t,n,r){let{value:i,format:a,message:o,errorOriginPosition:s}=e;a=r?.format||a;let c=z(i,{format:a,locale:t});return Ja(i)?Td(i,o,n,s):i===null?Sd(a):Xs(a)?bd(F(i),a,c,n):typeof i==`number`?Os(a||``)?Cd(i,a,c,n):xd(i,a,c,n):typeof i==`boolean`?wd(i,a,c,n):bd(i,a,c,n)}function V(e){return!!e&&yd(e)===`number`}function _d(e){return!!e&&yd(e)===`text`}function vd(e){return!!e&&yd(e)===`error`}function yd({value:e,format:t}){if(e===null)return`empty`;if(Ja(e))return`error`;if(Xs(t))return`text`;switch(typeof e){case`number`:return`number`;case`boolean`:return`boolean`;case`string`:return`text`}}function bd(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function xd(e,t,n,r){return{value:e||0,format:t,formattedValue:n,position:r,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let Sd=on(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function Cd(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function wd(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function Td(e,t,n,r){return{value:e,formattedValue:e,message:t,position:n,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:r}}function Ed(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function Dd(e,t=1){return t*(e+4)-4}function Od(e=100,t=100){return new OffscreenCanvas(e,t).getContext(`2d`)}function kd(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=z(md(t.content,n),e)}}catch{i=M.GenericError}return Ad(e,i,t.style,r)}function Ad(e,t,n,r){return Md(e,Hd(e,t,n,n?.wrapping===`wrap`?r-8:void 0),n).height+6}function jd(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${Ye}`}function Md(e,t,n={},r=`pt`){if(!t.length)return{width:0,height:0};let i=zd(n,r),a=t.map(t=>Ld(e,t,i)),o=Dd(a[0].height,t.length),s=Math.max(...a.map(e=>e.width));if(!n.rotation)return{height:o,width:s};let c=Math.abs(Math.cos(n.rotation)),l=Math.abs(Math.sin(n.rotation));return{width:s*c+o*l,height:l*s+c*o}}function Nd(e,t,n={},r=`pt`){return Pd(e,t,zd(n,r),n.rotation)}function Pd(e,t,n,r){let i=Ld(e,t,n);if(!r)return i.width;let a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r));return i.width*a+i.height*o}let Fd={};function Id(e,t,n,r=`pt`){let i=Ld(e,t,zd(n,r));if(!n.rotation)return i;let a=Math.abs(Math.cos(n.rotation)),o=Math.abs(Math.sin(n.rotation));return{width:i.width*a+i.height*o,height:i.height*a+i.width*o}}function Ld(e,t,n){if(Fd[n]||(Fd[n]={}),Fd[n][t]===void 0){e.save(),e.font=n;let r=e.measureText(t);e.restore();let i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;Fd[n][t]={width:i,height:a}}return Fd[n][t]}function Rd(e){return Math.round(e*96/72)}function zd(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?Bd(e):e.fontSize)??Je}px ${Ye}`}function Bd(e){return Rd(e?.fontSize||Je)}function Vd(e,t,n,r){if(Nd(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)Nd(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function Hd(e,t,n,r){n||={},Nt(t)&&(t=It(t).label);let i=[],a=t.includes(`
16
16
  `)?t.split(`
17
- `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Vd(e,t,r,n),c=a.pop(),l=Nd(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=Nd(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Ud(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Wd(e){return e?e.toLowerCase().trim():``}let Gd=/([0-9\.]*)px/;function Kd(e){return Number(e.match(Gd)?.[1])}function qd(e,t,n){let r=Pd(e,t,e.font);if(r<=n)return t;let i=Pd(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=Pd(e,t,e.font);return t+`…`}function Jd(e,t,n,r=!1,i=!1,a=Kd(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Yd(e,t,n,r,i=`pt`){if(Nd(e,n,r,i)<=t)return n;let a=Nd(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Nd(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function Xd(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}let Zd={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=jd(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=Vs({value:u,format:void 0},n.locale),f=Vs({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function Qd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function $d(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=ef(this),c=(s-(i?ef(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=ef(this),c=a?ef(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function ef(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let tf=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},nf={id:`o-spreadsheet-minor-gridlines`,beforeDatasetsDraw(e){let t=e.ctx,n=e.chartArea;if(n)for(let r in e.scales){let i=e.scales[r],a=i.options,o=a?.grid?.minor;if(!o?.display)continue;let s=a?.grid?.display,c=i.ticks;if(!(!c||c.length<2)){t.save(),t.lineWidth=1,t.strokeStyle=o.color??a?.grid?.color??`#e6e6e6`;for(let e=0;e<c.length-1;e++){let r=i.getPixelForTick(e),a=i.getPixelForTick(e+1);if(!(!isFinite(r)||!isFinite(a)))for(let e=+!!s;e<4;e++){let o=e/4,s=Math.round(r+(a-r)*o)+.5;t.beginPath(),i.isHorizontal()?(t.moveTo(s,n.top),t.lineTo(s,n.bottom)):(t.moveTo(n.left,s),t.lineTo(n.right,s)),t.stroke()}}t.restore()}}}},rf=/rgba?\(|\s+|\)/gi,af=/^#([A-F\d]{2}){3,4}$/,of=/^light-dark\(\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*,\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*\)$/i,sf=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#62A300`,`#ff4136`,`#949494`,`#ff5c9d`];function cf(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return uf(e.toString(16).padStart(6,`0`))+n}function lf(e){return typeof e==`number`?e:Number.parseInt(uf(e).slice(1,7),16)}function uf(e){let t=e;if(e.startsWith(`light-dark`)){let t=e.match(of);if(!t)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${uf(t[1])}, ${uf(t[2])})`}if(e.startsWith(`rgb`)?t=gf(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!af.test(t))throw Error(`invalid color input: ${e}`);return t}function df(e){try{return uf(e),!0}catch{return!1}}function ff(e){try{return xf(e),!0}catch{return!1}}let pf=e=>e>=0&&e<=255;function mf(e,t,n,r=1){if(!pf(e)||!pf(t)||!pf(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function hf(e){let{r:t,g:n,b:r}=vf(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function gf(e){let t=e.replace(rf,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Gt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function _f(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function vf(e){e=uf(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function yf(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function bf(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function xf(e){return _f(yf(e))}function Sf(e){return bf(vf(e))}function Cf(e,t){let n=vf(t),r=vf(e),i=n.a+r.a*(1-n.a);return _f({r:Math.round((n.r*n.a+r.r*r.a*(1-n.a))/i),g:Math.round((n.g*n.a+r.g*r.a*(1-n.a))/i),b:Math.round((n.b*n.a+r.b*r.a*(1-n.a))/i),a:i})}function wf(e){return vf(typeof e==`number`?cf(e):e)}function Tf(e,t,n=0){if(!(df(e)&&df(t)))return!1;let r=vf(e),i=vf(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function Ef(e,t){if(e.startsWith(`light-dark`)){let n=e.match(of);if(!n)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${Ef(n[1],t)}, ${Ef(n[2],t)})`}return t===1?uf(e).slice(0,7):_f({...vf(e),a:t})}function Df(e,t){let n=Sf(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,xf(n))}let Of={invert:1,hueRotate:170,contrast:.85,brightness:1.2},kf=`invert(${Of.invert}) hue-rotate(${Of.hueRotate}deg) contrast(${Of.contrast}) brightness(${Of.brightness})`;function Af(e){let t=e*Math.PI/180,n=Math.cos(t),r=Math.sin(t);return[[.213+n*.787-r*.213,.715-n*.715-r*.715,.072-n*.072+r*.928],[.213-n*.213+r*.143,.715+n*.285+r*.14,.072-n*.072-r*.283],[.213-n*.213-r*.787,.715-n*.715+r*.715,.072+n*.928+r*.072]]}function jf(e){let{r:t,g:n,b:r,a:i}=vf(e),a=t/255,o=n/255,s=r/255;a/=Of.brightness,o/=Of.brightness,s/=Of.brightness,a=(a-.5)/Of.contrast+.5,o=(o-.5)/Of.contrast+.5,s=(s-.5)/Of.contrast+.5,a=Math.max(0,Math.min(1,a)),o=Math.max(0,Math.min(1,o)),s=Math.max(0,Math.min(1,s));let c=Af(-Of.hueRotate),l=Math.max(0,Math.min(1,c[0][0]*a+c[0][1]*o+c[0][2]*s)),u=Math.max(0,Math.min(1,c[1][0]*a+c[1][1]*o+c[1][2]*s)),d=Math.max(0,Math.min(1,c[2][0]*a+c[2][1]*o+c[2][2]*s));return _f({r:Math.round((1-l)*255),g:Math.round((1-u)*255),b:Math.round((1-d)*255),a:i})}function Mf(e,t){let n=Sf(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,xf(n))}function Nf(e){return hf(e)<.6?Df(e,.9):Mf(e,.75)}let Pf=`#4EA7F2`,Ff=[Pf,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],If=[Pf,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],Lf=[Pf,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],Rf=[Pf,`#3188E6`,`#056BD9`,`#155193`,`#A76DBC`,`#7F4295`,`#6D2387`,`#4F1565`,`#EA6175`,`#CE4257`,`#982738`,`#791B29`,`#43C5B1`,`#00A78D`,`#0E8270`,`#105F53`,`#F4A261`,`#F48935`,`#BE5D10`,`#7D380D`,`#8481DD`,`#5752D1`,`#3A3580`,`#26235F`,`#A4A8B6`,`#7E8290`,`#545B70`,`#3F4250`,`#FFD86D`,`#FFBC2C`,`#C08A16`,`#936A12`],zf=[Pf,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],Bf=[Pf,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],Vf=[Pf,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`,`#155193`,`#4F1565`,`#791B29`,`#105F53`,`#7D380D`,`#26235F`,`#3F4250`,`#936A12`];function Hf(e,t){return t[e%t.length]}function Uf(e){return e<=6?Ff:e<=12?If:e<=24?Lf:Rf}function Wf(e){return e<=6?Ff:e<=12?zf:e<=24?Bf:Vf}var Gf=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Uf(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Hf(this.currentColorIndex++,this.palette)}},Kf=class extends Gf{constructor(e,t=[]){super(e,t),this.palette=Wf(e).filter(e=>!t.includes(e))}},qf=class{availableColors;colors={};constructor(e=12){this.availableColors=new Kf(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};let Jf={greys:[`#ffffff`,`#808080`,`#000000`],blues:[`#f7fbff`,`#6aaed6`,`#08306b`],reds:[`#fff5f0`,`#fb694a`,`#67000d`],greens:[`#f7fcf5`,`#73c476`,`#00441b`],oranges:[`#fff5eb`,`#fd8c3b`,`#7f2704`],purples:[`#fcfbfd`,`#9e9ac8`,`#3f007d`],viridis:[`#440154`,`#21918c`,`#fde725`],cividis:[`#00224e`,`#7d7c78`,`#fee838`],rainbow:[`#B41DB4`,`#FFFF00`,`#00FFFF`]},Yf=Object.keys(Jf);function Xf(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=wf(t[e-1].color).a,i=wf(t[e].color).a,a=lf(t[e-1].color),o=lf(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:Zf(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return cf(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return cf(Qf(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return cf(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function Zf(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function Qf(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}let $f=`000000`,ep={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},tp={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},np=`http://schemas.openxmlformats.org/drawingml/2006/main`,rp=`http://schemas.openxmlformats.org/drawingml/2006/chart`,ip={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},ap={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},op=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,sp=.75,cp=.143,lp=8.43,up=12.75,dp={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}],IFERROR:[{type:`NUMBER`,value:0}]},fp=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),pp=`xMovingAverage`,mp={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function hp(e,t,n){return n?zl(e,t,n):void 0}function gp(e,{applyChange:t}){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function _p(e,t,n){let r=[];for(let i of n.dataSets){let{unboundedZone:a,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(t,i.dataRange);if(!(s||c))if(a.left!==a.right&&a.top!==a.bottom){if(a.right===void 0)continue;let t=i.dataSetId;for(let i=a.left;i<=a.right;i++){let s={...a,left:i,right:i};r.push({...vp(e,o,s,n.dataSetsHaveTitle?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),dataSetId:t}),t=`${t}_${i}`}}else r.push({...vp(e,o,a,n.dataSetsHaveTitle?{top:a.top,bottom:a.top,left:a.left,right:a.left}:void 0),dataSetId:i.dataSetId})}return r}function vp(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${Yn(n)}`);if(r){let i=Yn(n),a=Yn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Yn(n))}}function yp(e,t,n){let r=n.labelCell?.zone,i=n.dataRange.zone;if(r){let{numberOfRows:e,numberOfCols:t}=cr(i);e===1?i={...i,left:i.left+1}:t===1&&(i={...i,top:i.top+1})}let a=t[n.dataSetId]??{},o=Nl({...n.dataRange,zone:i},e.getSheetSize),s={};a.label?s={text:a.label}:n.labelCell&&(s={reference:e.getRangeString(n.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let c;return a.trend?.type&&(c={type:a.trend.type===`polynomial`&&a.trend.order===1?`linear`:mp[a.trend.type],color:a.trend.color,order:a.trend.order?Math.min(a.trend.order,6):void 0,window:a.trend.window||2}),{label:s,range:e.getRangeString(o,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,trend:c}}function bp(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=Nl({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function xp(e){return e&&hf(e)<.3?`#FFFFFF`:`#000000`}function Sp(e){return e&&hf(e)<.3?`#C8C8C8`:`#666666`}function Cp(e){return e.dataSets.find(e=>!Dc.test(e.dataRange))!==void 0||e.dataSets.map(e=>Un(e.dataRange)).some(e=>e.top!==e.bottom&&yr(e))?`InvalidDataSet`:`Success`}function wp(e){return e.labelRange&&!Dc.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function Tp(e,t,n){return n&&!!t&&e>=t}function Ep(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function Dp(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};let r=`dataSetStyles`in e?e.dataSetStyles??{}:{};for(let e of Object.values(r))e?.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function Op(e,t,n=!1){return(r,i)=>{let a=e?.[i];return kp({format:a,locale:t},n)(r)}}function kp(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return Mp(t?Vs({value:n,format:i},r):z(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let Ap=[{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}];function jp(e,t){let n=[],r=pn(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function Mp(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function Np(e){return e===`x1`||e===`xMovingAverage`}function Pp({background:e},t){let n=t.getSpreadsheetTheme().backgroundColor;return e||n}function Fp(e,t){return e.type===`bar`&&t.type===`line`}let Ip={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:Hp(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:Rp(e,n,r);break;case`bar`:n.horizontal?Vp(e,n,r):Rp(e,n,r);break;case`pyramid`:Vp(e,n,r);break;case`calendar`:zp(e,n,r);break;case`bubble`:Bp(e,n,r);break;case`funnel`:Vp(e,n,r);break}r.restore()}};function Lp(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function Rp(e,t,n){let r={};for(let i of e._metasets){if(Np(i.xAxisID)||i.hidden||Fp(t,i))continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else if(e.config.type===`bubble`)d=l.y;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=e+13*(c<0?1:-1));r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,Lp(t.callback(Number(c),i,o),u,d,n)}}}function zp(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(Np(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||Lp(g,d,f,n)}}}function Bp(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top,a={};for(let o of e._metasets)for(let e=0;e<o._parsed.length;e++){let s=o._parsed[e].y;if(isNaN(s))continue;let c=o.data[e],l=c.x,u=Math.max(Math.min(c.y,r),i);a[l]||(a[l]=[]);for(let e of a[l]||[])Math.abs(e-u)<13&&(u=e+13*(s<0?1:-1));a[l].push(u);let d=c.options.backgroundColor??`#ffffff`;Sf(uf(d)).a===1?n.fillStyle=xp(d):n.fillStyle=`#000000`;let f=t.callback(Number(s),o,e);n.fillText(f,l,u)}}function Vp(e,t,n){let r={};for(let i of e._metasets){if(Np(i.xAxisID)||Fp(t,i))continue;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Nd(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,Lp(s,f,l,n)}}}function Hp(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Nd(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,ee=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=ee||ee<h))continue;let y=t.background(Number(i),r,e);n.fillStyle=xp(y),n.strokeStyle=y||`#ffffff`,Lp(m,f,p,n)}}let Up={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Wp={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Gp={inSeconds:function(e){return Math.floor(e/Wp.second)},inMinutes:function(e){return Math.floor(e/Wp.minute)},inHours:function(e){return Math.floor(e/Wp.hour)},inDays:function(e){return Math.floor(e/Wp.day)},inMonths:function(e){return Math.floor(e/Wp.month)},inYears:function(e){return Math.floor(e/Wp.year)}},Kp=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function qp(e,t,n){let r=Jp(t),i=Xp(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function Jp(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function Yp(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Xp(e,t,n){let r=e.map(e=>Yi(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=pn(i)-mn(i),o=Yp(t);return Wp.second>=Wp[o]&&Gp.inSeconds(a)<180?`second`:Wp.minute>=Wp[o]&&Gp.inMinutes(a)<180?`minute`:Wp.hour>=Wp[o]&&Gp.inHours(a)<96?`hour`:Wp.day>=Wp[o]&&Gp.inDays(a)<90?`day`:Wp.month>=Wp[o]&&Gp.inMonths(a)<36?`month`:`year`}function Zp(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a,axisType:o}=t,s={stacked:e.stacked,locale:i};if(e.horizontal)n.x=fm(e,`bottom`,`values`,o,{...s,format:a?.x}),n.y={...fm(e,`left`,`labels`,`linear`,s),grid:{display:!1}};else{n.x={...fm(e,`bottom`,`labels`,o,s),grid:{display:!1}};let t={...s,format:a?.y};n.y=fm(e,`left`,`values`,`linear`,t);let r={...s,format:a?.y1};n.y1=fm(e,`right`,`values`,`linear`,r)}if(n=Qt(n),r&&r.length&&r.some(w)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[pp]={...n.x,offset:!0,display:!1}}return n}function Qp(e,t){let n=t.map(e=>e.label||``),r=xp(e.background);return{y:{title:dm(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:dm(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function $p(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(V).map(e=>e.value),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(w):[...Jf[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:xp(e.background),minValue:i,maxValue:a,locale:t.locale}}function em(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:fm(e,`bottom`,`labels`,r,{locale:n}),y:fm(e,`left`,`values`,`linear`,{locale:n,stacked:c,format:o?.y}),y1:fm(e,`right`,`values`,`linear`,{locale:n,stacked:c,format:o?.y1})};if(l=Qt(l),r===`time`&&a&&s){let t={type:`time`,time:qp(a,s,n),min:z(e.axesDesign?.x?.min??``,{format:s,locale:n}),max:z(e.axesDesign?.x?.max??``,{format:s,locale:n})};Object.assign(l.x,t),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>Vs({value:e,format:s},n):e=>z(e,{format:s,locale:n}));if(i&&i.length&&i.some(w)&&(l.x1={...l.x,display:!1},l[pp]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=C(0,e).map(e=>e.toString()),l.x1.offset=!1,l[pp].type=`category`,l[pp].offset=!1}return l}function tm(e){return hf(e||`#ffffff`)>.5?`#cccccc`:`#999999`}function nm(e){return hf(e||`#ffffff`)>.5?`#e6e6e6`:`#333333`}function rm(e,t){let n=em(e,t),r=n?.x??{},i=e.axesDesign?.x,a=i?.gridLines!==`none`&&i?.gridLines!==`minor`;return{...n,x:{...r,grid:{...r.grid,color:tm(e.background),display:a}}}}function im(e,t){let n=rm(e,t),r=e.verticalAxisPosition||`left`;return{...n,y:{...n.y,position:r}}}function am(e,t){let{locale:n,axisFormats:r,axisType:i}=t,a=r?.y||r?.y1,o=e.axesDesign?.y,s={x:{...fm(e,`bottom`,`labels`,i,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:xp(e.background),callback:kp({locale:n,format:a},e.humanize)},title:dm(e.axesDesign?.y),min:o?.min,max:o?.max,grid:{lineWidth:e=>e.tick.value===0?2:1,display:o?.gridLines!==`none`&&o?.gridLines!==`minor`,color:tm(e.background)}}};return(o?.gridLines===`minor`||o?.gridLines===`both`)&&(s.y.grid.minor={display:!0,color:nm(e.background)}),s}function om(e,t){let{dataSetsValues:n}=t,r=Zp(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.filter(V).map(e=>Math.abs(e.value)))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function sm(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(V).map(e=>e.value))));return{r:{beginAtZero:!0,ticks:{callback:kp({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:xp(e.background),callback:e=>Mp(e)},suggestedMin:a<0?a-1:0}}}function cm(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=hm(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:um(o?.defaultProjection||`mercator`),axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:Ie},grid:{color:Ie},ticks:{color:xp(e.background),callback:kp({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:mm(e)},interpolate:pm(e.colorScale??ze),missing:e.missingValueColor||`#ffffff`}}}function lm(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Mp(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o?.value||a?.value===null||!V(a)||!V(o)?``:z(a.value/o.value,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function um(e){return e===`conicConformal`?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function dm(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:Rd(e.title.fontSize??12)},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function fm(e,t,n,r,i){let{useLeftAxis:a,useRightAxis:o}=Dp(e);if(t===`left`&&!a||t===`right`&&!o)return;let s=xp(e.background),c;if(c=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&a),o=c?.gridLines?c?.gridLines===`major`||c?.gridLines===`both`:n,l=!(r===`category`||r===void 0)&&(c?.gridLines===`minor`||c?.gridLines===`both`),u=kp(i,e.humanize),d={position:t,title:dm(c),beginAtZero:!c?.min,stacked:i?.stacked,ticks:{color:s,callback:u},min:c?.min,max:c?.max,grid:{display:o,color:tm(e.background)}};return l&&(d.grid.minor={display:!0,color:nm(e.background)}),d}else{let t={ticks:{padding:5,color:s,callback:function(e,t,n){return Mp(this.getLabelForValue(e))}},min:c?.min,max:c?.max,grid:{display:c?.gridLines===`major`||c?.gridLines===`both`,color:tm(e.background)},stacked:i?.stacked,title:dm(c)};return(c?.gridLines===`minor`||c?.gridLines===`both`)&&(t.grid.minor={display:!0,color:nm(e.background)}),t}}function pm(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),Xf(r)}function mm(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function hm(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let gm=`nullValue`;function _m(e,t){let{dataSetsValues:n,background:r}=t,i=[],a=Bm(e.dataSetStyles,n),o=[];for(let s in n){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label??c;let f=a.next(),p={label:c,data:l.map(e=>V(e)?e.value:NaN),hidden:u,borderColor:e.background||r,borderWidth:+!!e.stacked,backgroundColor:f,yAxisID:e.horizontal?`y`:e.dataSetStyles?.[d]?.yAxisId??`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};i.push(p);let m=e.dataSetStyles?.[d]?.trend,h=t.trendDataSetsValues?.[s];!m?.display||e.horizontal||!h||o.push(Rm(p,m,h))}i.push(...o);let s=vm(e,n);return s&&i.push(s),i}function vm(e,t){let n=t.filter(e=>!e.hidden);if(!e.stacked||!e.showTotalLine||n.length<2)return;let r=C(0,Math.max(...n.map(e=>e.data.length))).map(e=>{let t;for(let r of n){let n=r.data[e];V(n)&&(t=(t??0)+n.value)}return t??NaN}),i=hf(e.background||`#FFFFFF`)<.3?`#e9ecef`:`#343a40`;return{type:`line`,label:j(`Sum`),data:r,order:-1,tension:0,fill:!1,pointRadius:3,borderWidth:2,backgroundColor:i,borderColor:i,pointBackgroundColor:i,xAxisID:`x`,yAxisID:`y`}}function ym(e,t){let{labels:n,dataSetsValues:r,background:i}=t,a=r.map(e=>e.data).flat().filter(V).map(e=>e.value),o=Math.max(...a),s=Math.min(...a),c=pm(e.colorScale??ze,s,o),l=[];for(let t of r)l.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>V(t)?c(t.value):e.missingValueColor||`#00000000`),borderColor:e.background||i,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data.map(e=>V(e)?e.value:NaN)});return{labels:n,datasets:l}}function bm(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),!V(f)){c.push([d,d]),s.push(``);continue}c.push([d,f.value+d]);let p=f.value>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f.value}e.showSubTotals&&(u.push(j(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function xm(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=Bm(e.dataSetStyles,n);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p,dataSetId:m}=n[u];d=e.dataSetStyles?.[m]?.label??d;let h=[],g=l.next();h=r&&[`linear`,`time`].includes(r)?f.map((e,t)=>({x:i[t]===``?NaN:i[t]??NaN,y:V(e)?e.value:NaN})):f.map(e=>V(e)?e.value:NaN);let _=e.dataSetStyles?.[m],v={label:d,data:h,hidden:p,tension:0,borderColor:g,backgroundColor:o?Ef(g,tt):g,pointBackgroundColor:g,fill:o?zm(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:_?.yAxisId||`y`};a.push(v);let ee=_?.trend,y=t.trendDataSetsValues?.[u];!ee?.display||!y||c.push(Rm(v,ee,y))}return a.push(...c),a}function Sm(e,t){let n=xm(e,t);for(let e of n)Np(e.xAxisID)||(e.showLine=!1);return n}function Cm(e,t){let n,r;if(e.bubbleColor.color===`multiple`){let i=new Gf(t.bubbleSizes.length);r=[];for(let e=0;e<t.bubbleSizes.length;e++)r.push(i.next());n=r.map(t=>Ef(t,e.bubbleColor.transparent?.5:1))}else r=e.bubbleColor.color,n=Ef(r,e.bubbleColor.transparent?.5:1);let i=wm(t.bubbleSizes),a=[];for(let e=0;e<t.bubbleSizes.length;e++){let n=t.dataSetsValues[0].data[e];a.push({x:t.labels[e],y:V(n)?n.value:NaN})}return[{label:t.dataSetsValues[0]?.label,data:a,backgroundColor:n,borderColor:r,hoverBackgroundColor:n,hoverBorderColor:r,yAxisID:`y`,pointRadius:i,pointHoverRadius:i,showLine:!1}]}function wm(e){if(!e.length)return[];let t=e.filter(e=>Number.isFinite(e)&&e>0),n=t.length?Math.min(...t):0,r=(t.length?Math.max(...t):0)-n;return t.length?e.map(e=>e===void 0||!Number.isFinite(e)||e<0?0:e===0?2:r===0?10:10+S((e-n)/r,0,1)*20):e.map(()=>2)}function Tm(e,t){let{dataSetsValues:n}=t,r=[],i=jp(new Gf(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a.map(e=>V(e)?e.value:NaN),borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function Em(e,t){let{dataSetsValues:n}=t,r=[],i=Bm(e.dataSetStyles,n),a=[],o=n.filter(({dataSetId:t})=>(e.dataSetStyles?.[t]?.type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label||c;let f=e.dataSetStyles?.[d],p=i.next(),m=s===0?`bar`:`line`,h=f?.type??m,g={label:c,data:l.map(e=>V(e)?e.value:null),hidden:u,borderColor:p,backgroundColor:p,yAxisID:e.dataSetStyles?.[d]?.yAxisId||`y`,xAxisID:`x`,type:h,order:h===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};g.type===`bar`&&(g.barPercentage=.9,g.categoryPercentage=o.length>1?.8:1,g.borderRadius=2),r.push(g);let _=e.dataSetStyles?.[d]?.trend,v=t.trendDataSetsValues?.[s];!_?.display||!v||a.push(Rm(g,_,v))}return r.push(...a),r}function Dm(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=Bm(e.dataSetStyles,n);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSetStyles?.[t]?.label&&(o=e.dataSetStyles[t].label);let l=a.next(),u={label:o,data:s.map(e=>V(e)?e.value:null),hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Ef(l,tt),u.fill=`start`),r.push(u)}return r}function Om(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){let o=r[0].data[n];if(!i[n]||o===void 0)continue;let s=t.geoFeatureNameToId(a,i[n]);s&&(e[s]={value:V(o)?o.value:0,label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function km(e,t){let n=t.dataSetsValues[0],{labels:r,background:i}=t;if(!n)return[];let{label:a,data:o}=n;return a=e.dataSetStyles?.[0]?.label||a,[{label:a,data:o.map(e=>{if(!V(e))return 0;let t=e.value;return t<=0?[0,0]:[-t,t]}),backgroundColor:Am(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||i,borderWidth:3}]}function Am(e,t){let n=new Gf(e.length,t);return e.map(()=>n.next())}function jm(e,t){let{dataSetsValues:n,labels:r,background:i}=t,a=Fm(Nm(n,r)),o=a[0]||[],s=new Gf(o.length,e.groupColors||[]),c=o.map(e=>({label:e.label,color:s.next()})),l=[];for(let t=a.length-1;t>=0;t--){let n={groupColors:c,parsing:{key:`value`},data:a[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?Ne:e.background||i},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return Ne;let n=t.groups[0];return c.find(e=>e.label===n)?.color},hoverOffset:10};l.push(n)}return l}function Mm(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]?.value,a=r===null?gm:String(r);n[i][t]=a}n[i].value=Number(t[i])}return n}function Nm(e,t){return Pm(Mm(e,t),0,e.length,[])}function Pm(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:Pm(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function Fm(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function Im(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=Nm(n,r).sort((e,t)=>t.value-e.value),c=Vm(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e].value?String(n[t].data[e].value):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Up.showLabels,f=e.showValues??Up.showValues,p=e.coloringOptions||Up.coloringOptions,m;return p?.type===`colorScale`&&(m=Hm(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...Lm(e.valuesDesign,Up.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?z(e.raw.v,o):void 0].filter(w)},captions:{display:e.showHeaders??Up.showHeaders,padding:6,...Lm(e.headerDesign,Up.headerDesign)},key:`value`,groups:C(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Up.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return Um(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function Lm(e,t){let n=e=>{let t=e.element.options.backgroundColor;return hf(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:Rd(e?.fontSize??t.fontSize)}}}function Rm(e,t,n){let r=vf(e.backgroundColor);r.a=1;let i=t.color||Df(_f(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?pp:`x1`,yAxisID:e.yAxisID,label:e.label?j(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function zm(e,t){return t?e===0?`origin`:`-1`:`origin`}function Bm(e,t){let n=t.map(t=>e?.[t.dataSetId]?.backgroundColor),r=t.length;return new Gf(r,n)}function Vm(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new Gf(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function Hm(e,t){if(e.length===0)return;let n=Fm(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),Xf(e)}}function Um(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=Fm(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Df(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let Wm={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Gm(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==gm}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Df(s,.5):e.options.backgroundColor=s}}};function Gm(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Km={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;qm(e,n,r)}};function qm(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(w),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,ee=(p+m)/2,y=(m-p)*.9,b=f-d;if((b>=Math.PI?m:Math.sin(b/2)*p*2)<l.length*a)continue;n.save();let te={x:Math.cos(v)*g,y:Math.sin(v)*g},ne=e.chartArea.left+e.chartArea.width/2+te.x,re=e.chartArea.top+e.chartArea.height/2+te.y;n.translate(ne,re);let ie;v>Math.PI/2?(n.rotate(v-Math.PI),ie=-ee):(ie=ee,n.rotate(v));let ae=u.options.backgroundColor,oe=hf(ae)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||oe,n.textAlign=`center`,n.textBaseline=`middle`,n.font=jd(i,r.bold,r.italic);let se=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Yd(n,y,l[e],r,`px`);n.fillText(t,ie,se+e*a)}n.restore()}}let Jm={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Xm(r,e);if(!n)break;let a=Ym(t),o=Ym(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Ym(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Xm(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Zm={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};Wr.add(`chartShowValuesPlugin`,{register:e=>e.register(Ip),unregister:e=>e.unregister(Ip)}),Wr.add(`chartMinorGridPlugin`,{register:e=>e.register(nf),unregister:e=>e.unregister(nf)}),Wr.add(`waterfallLinesPlugin`,{register:e=>e.register(Jm),unregister:e=>e.unregister(Jm)}),Wr.add(`funnelController`,{register:e=>e.register(Qd()),unregister:e=>e.unregister(Qd())}),Wr.add(`funnelElement`,{register:e=>e.register($d()),unregister:e=>e.unregister($d())}),Wr.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=tf,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Wr.add(`sunburstLabelsPlugin`,{register:e=>e.register(Km),unregister:e=>e.unregister(Km)}),Wr.add(`sunburstHoverPlugin`,{register:e=>e.register(Wm),unregister:e=>e.unregister(Wm)}),Wr.add(`chartColorScalePlugin`,{register:e=>e.register(Zd),unregister:e=>e.unregister(Zd)}),Wr.add(`calendarController`,{register:e=>e.register(Mi()),unregister:e=>e.unregister(Mi())}),Wr.add(`zoomWindowPlugin`,{register:e=>e.register(Zm),unregister:e=>e.unregister(Zm)}),Wr.add(`chartBackgroundPlugin`,{register:e=>e.register(ji),unregister:e=>e.unregister(ji)});var Qm=class extends k{static template=`o-spreadsheet-ChartJsComponent`;props=(0,t.props)({chartId:t.types.string(),"isFullScreen?":t.types.boolean()});canvas=(0,t.signal)(null);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=A(Ai)),(0,t.onMounted)(()=>{Kr();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(x(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),hi(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(x(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(x(e)):(this.chart?.destroy(),this.createChart(x(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas();if(!n)return;let r=n.getContext(`2d`);this.chart=new globalThis.Chart(r,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!T(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},$m=class{static commonKeys=[`type`,`title`,`background`,`humanize`]};function eh(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Vs(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Vs({value:a,format:o},i):z(a,{format:o,locale:i})}function th(e,t,n){return e?t?Vs(e,n):e.formattedValue??String(e.value??``):``}function nh(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function rh(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function ih(e){return e.keyValue&&!Dc.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function ah(e){return e.baseline&&!Dc.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let oh=globalThis.Path2D,sh=oh&&new oh(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),ch=oh&&new oh(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`),lh={sequence:40,allowedDefinitionKeys:[...$m.commonKeys,`keyValue`,`keyDescr`,`baseline`,`baselineMode`,`baselineDescr`,`baselineColorUp`,`baselineColorDown`],fromStrDefinition(e,t,n){let r=Bl(n,t,e.baseline),i=Bl(n,t,e.keyValue);return{...e,baseline:r,keyValue:i}},validateDefinition(e,t){return e.checkValidations(t,ih,ah)},copyInSheetId:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,type:`scorecard`,keyValue:e.dataSource?.type===`range`?e.dataSource?.dataSets?.[0]?.dataRange:void 0,title:e.title||{text:``},baselineMode:Qe,baselineColorUp:$e,baselineColorDown:et,baseline:e.auxiliaryRange||``,humanize:e.humanize}},transformDefinition(e,t,{adaptRangeString:n}){let r,i;if(e.baseline){let{changeType:i,range:a}=n(t,e.baseline);i!==`REMOVE`&&(r=a)}if(e.keyValue){let{changeType:r,range:a}=n(t,e.keyValue);r!==`REMOVE`&&(i=a)}return{...e,baseline:r,keyValue:i}},duplicateInDuplicatedSheet(e,t,n){let r=hp(t,n,e.baseline),i=hp(t,n,e.keyValue);return{...e,baseline:r,keyValue:i}},toStrDefinition(e,t,n){return{...e,keyValue:e.keyValue?n.getRangeString(e.keyValue,t):void 0,baseline:e.baseline?n.getRangeString(e.baseline,t):void 0}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.keyValue?[{dataRange:e.keyValue,dataSetId:`0`}]:[]},auxiliaryRange:e.baseline}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=gp(e.baseline,t),r=gp(e.keyValue,t);return e.baseline===n&&e.keyValue===r?e:{...e,baseline:n,keyValue:r}},getRuntime(e,t){let n=``,r,i=e.getLocale();if(t.keyValue){let a={sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top};r=e.getEvaluatedCell(a),n=th(r,t.humanize??!0,i)}let a,o=t.baseline;if(o){let t={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=e.getEvaluatedCell(t)}let{background:s,fontColor:c}=e.getStyleOfSingleCellChart(t.background,t.keyValue),l=eh(a,r,t.baselineMode,t.humanize??!0,i),u=t.baselineMode===`progress`&&Ta(l,i)?P(l,i):0,d=t.title;return{title:{...d,text:d.text?e.dynamicTranslate(d.text):``},keyValue:n,keyDescr:t.keyDescr?.text?e.dynamicTranslate(t.keyDescr.text):``,baselineDisplay:l,baselineArrow:rh(a,r,t.baselineMode),baselineColor:nh(a,t.baselineMode,r,t.baselineColorUp,t.baselineColorDown),baselineDescr:t.baselineMode!==`progress`&&t.baselineDescr?.text?e.dynamicTranslate(t.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...t.baselineMode!==`percentage`&&t.baselineMode!==`progress`&&o?e.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:t.baselineDescr?.fontSize,align:t.baselineDescr?.align},baselineDescrStyle:{textColor:t.baselineDescr?.color,...t.baselineDescr},keyValueStyle:{...t.keyValue?e.getCellComputedStyle({sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top}):void 0,fontSize:t.keyDescr?.fontSize,align:t.keyDescr?.align},keyValueDescrStyle:{textColor:t.keyDescr?.color,...t.keyDescr},progressBar:t.baselineMode===`progress`?{value:u,color:u>0?t.baselineColorUp:t.baselineColorDown}:void 0}}};function uh(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(qd(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Jd(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&oh){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(sh);break;case`up`:r.fill(ch);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(qd(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Jd(r,qd(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(qd(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}let dh=.05;function fh(e,t){let n=e||``;return t&&n?` `+n:n}function ph({width:e,height:t},n){return new mh({width:e,height:t},n).computeDesign()}var mh=class{runtime;context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-dh*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*dh)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-dh*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return fh(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return fh(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Sp(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:jd(Rd(this.runtime.title.fontSize??14),this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:jd(Rd(e),this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:jd(Rd(t),this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:jd(Rd(n),this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:jd(Rd(r),this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*Rd(n):0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};function hh(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=vh(t,r)),!n)return gh(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function gh(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function _h(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function vh(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:ee(n,t)}var yh=class extends k{static template=`o-spreadsheet-ScorecardChart`;props=(0,t.props)({chartId:t.types.string(),"isFullScreen?":t.types.boolean()});canvas=(0,t.signal)(null);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){hi(this.createChart.bind(this),()=>{let e=this.canvas();if(!e)return[];let t=e.getBoundingClientRect();return[t.width,t.height,this.runtime,e,window.devicePixelRatio]});let e=new ResizeObserver(()=>this.createChart());(0,t.onMounted)(()=>{let t=this.canvas();t&&e.observe(t)}),(0,t.onWillUnmount)(()=>e.disconnect())}createChart(){let e=this.canvas();if(!e)return;let t=this.env.model.getters.getViewportZoomLevel();uh(ph(_h(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};let bh=`#F3F2F1`;function xh(e,t,n=1,r){let i=r??Sh(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Oh({width:i.width/n,height:i.height/n,x:0,y:0},t,o);wh(o,s),Ch(o,s),Eh(o,s),Th(o,s),Dh(o,s)}function Sh(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function Ch(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=bh,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function wh(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function Th(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${Ye}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Eh(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=Sp(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${Ye}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function Dh(e,t){e.save();let n=t.title;e.font=jd(Rd(n.fontSize),n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Oh(e,t,n){let r=t.maxValue,i=t.minValue,a=Ih(t,`animated`),o=kh(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Nd(n,f,{fontSize:u},`px`)>d&&(u=Ud(d,u,e=>Nd(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=Sp(t.background),g=Ah(t,o,h,n),_=0,v=0,ee=0;switch(t.title.text&&({width:v,height:ee}=Id(n,t.title.text,{...t.title,fontSize:Rd(t.title.fontSize??16)},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+ee/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:S(c,0,1),color:jh(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function kh(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function Ah(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Nd(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=Fh(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>Ph(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function jh(e){let t=Ih(e,`final`);if(t===void 0)return bh;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function Mh(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function Nh(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function Ph(e,t){let n=Mh(e),r=Mh(t);for(let e of n)for(let t of r)if(Nh(e,t))return!0;return!1}function Fh(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function Ih(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let Lh={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function Rh(e,t,n){try{let r=Bh(t.width,t.height),i=Uh(r,e,t,n),a=await Hh(r);return i(),a}catch(e){console.log(`Error exporting chart to image URL: `+e.message)}}async function zh(e,t,n){try{let r=Bh(t.width,t.height),i=Uh(r,e,t,n),a=await Vh(r);return i(),a}catch(e){console.log(`Error exporting chart to image file: `+e.message)}return null}function Bh(e,t){if(!globalThis.OffscreenCanvas)throw Error(`converting a chart to an image using OffscreenCanvas is not supported in this environment`);return new OffscreenCanvas(e,t)}async function Vh(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function Hh(e){let t=await Vh(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}function Uh(e,t,n,r){if(`chartJsConfig`in t){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let n=Gr();n||Kr();let r=x(t.chartJsConfig);if(!globalThis.Chart.registry.controllers.get(r.type))throw console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),n||qr(),Error(`Chart of type "${r.type}" is not registered in Chart.js library.`);let i=new globalThis.Chart(e,r);return()=>{i.destroy(),n||qr()}}else r===`scorecard`?uh(ph(n,t),e):r===`gauge`&&xh(e,t,1,n);return()=>{}}function Wh(e,t){let{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),a=n+Math.max(0,(i.width-t.width)/2),o=r+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:a,y:o})}function Gh(e,t){let n=x(t),r=e.getSheetViewDimension(),i=r.width,a=r.height;if(n.width>i){let e=i/n.width;n.width=i,n.height*=e}if(n.height>a){let e=a/n.height;n.height=a,n.width*=e}return n}function Kh(e,t,n,r){let i=e.getMaxAnchorOffset(t,r.height,r.width),{col:a,row:o}=n,s={...r.offset};for(let n=e.getColSize(t,a);s.x>n;n=e.getColSize(t,a))a+=1,s.x-=n;a>i.col&&(a=i.col,s.x=i.offset.x);for(let n=e.getRowSize(t,o);s.y>n;n=e.getRowSize(t,o))o+=1,s.y-=n;return o>i.row&&(o=i.row,s.y=i.offset.y),{col:a,row:o,offset:s}}function qh(e,t){return t.model.getters.getChartIdFromFigureId(e)?ve([tg(e,t),{id:`edit`,name:j(`Edit`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`)},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},Xh(e,t),Zh(e,t),Qh(e,t),$h(e,t),eg(e,t)]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0):[]}function Jh(e,t){return ve([Xh(e,t,j(`Image copied to clipboard`)),Zh(e,t),{id:`reset_size`,name:j(`Reset size`),execute:async()=>{let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getFigure(n,e);if(!r)return;let i=t.model.getters.getImagePath(e),a=t.model.getters.getImageSize(e)??await t.imageProvider?.getImageOriginalSize(i);if(!t.model.getters.getImageSize(e)){let n=t.model.getters.getImage(e);n.size=a}let{col:o,row:s}=r,{height:c,width:l}=Gh(t.model.getters,a);t.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,figureId:e,height:c,width:l,col:o,row:s})},icon:`o-spreadsheet-Icon.REFRESH`},{id:`download`,name:j(`Download`),execute:async()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),de(t.model.getters.getImagePath(e),`image`)},icon:`o-spreadsheet-Icon.DOWNLOAD`},eg(e,t)])}function Yh(e,t){let n=t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`;return ve([{id:`edit_carousel`,name:j(`Edit carousel`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`CarouselPanel`,{figureId:e})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},{...Xh(e,t,j(`Carousel copied to clipboard`)),name:j(`Copy carousel`)},{...Zh(e,t),name:j(`Cut carousel`)},{...eg(e,t),name:j(`Delete carousel`),separator:!0},{id:`edit_chart`,name:j(`Edit chart`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`,{})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall,isVisible:n},{...Qh(e,t),isVisible:n,name:j(`Copy chart as image`)},{...$h(e,t),isVisible:n,name:j(`Download chart`)},{id:`popout_chart`,name:j(`Pop out chart`),icon:`o-spreadsheet-Icon.EXTERNAL`,execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);!n||n.type!==`chart`||t.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{carouselId:e,chartId:n.chartId,sheetId:t.model.getters.getActiveSheetId()})},isVisible:n},{id:`delete_carousel_item`,name:t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`?j(`Delete chart`):j(`Delete data view`),execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);if(!n)return;let r=t.model.getters.getCarousel(e),i=r.items.filter(e=>!T(e,n));t.model.dispatch(`UPDATE_CAROUSEL`,{figureId:e,sheetId:t.model.getters.getActiveSheetId(),definition:{...r,items:i}})},icon:`o-spreadsheet-Icon.TRASH`,isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0)}function Xh(e,t,n){return{id:`copy`,name:j(`Copy`),shortcut:`Ctrl+C`,execute:async()=>{t.model.getters.getSelectedFigureIds().includes(e)||t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`COPY`);let r=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(r),n&&t.notifyUser({sticky:!1,type:`success`,text:n})},icon:`o-spreadsheet-Icon.CLIPBOARD`,isEnabledOnLockedSheet:!0}}function Zh(e,t){return{id:`cut`,name:j(`Cut`),shortcut:`Ctrl+X`,execute:async()=>{t.model.getters.getSelectedFigureIds().includes(e)||t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`CUT`),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`}}function Qh(e,t){return{id:`copy_as_image`,name:j(`Copy as image`),icon:`o-spreadsheet-Icon.COPY_AS_IMAGE`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await zh(t.model.getters.getChartRuntime(i),r,a);if(!o)return;let s=await new Promise(e=>{let t=new FileReader;t.addEventListener(`loadend`,n=>{let r=t.result;e(r)}),t.readAsArrayBuffer(o)}),c=`<img src="data:image/png;base64,${new Uint8Array(s).toBase64()}" />`;await t.clipboard.write({"text/html":c,"image/png":o}),t.notifyUser({sticky:!1,type:`success`,text:j(`Chart copied to clipboard`)})},isVisible:e=>e.model.getters.getSelectedFigureIds().length<=1,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function $h(e,t){return{id:`download`,name:j(`Download`),icon:`o-spreadsheet-Icon.DOWNLOAD`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await Rh(t.model.getters.getChartRuntime(i),r,a);o&&de(o,`chart`)},isVisible:e=>e.model.getters.getSelectedFigureIds().length<=1,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function eg(e,t){return{id:`delete`,name:j(`Delete`),execute:()=>{let n=t.model.getters.getSelectedFigureIds();n.includes(e)?t.model.dispatch(`DELETE_FIGURES`,{sheetId:t.model.getters.getActiveSheetId(),figureIds:n}):t.model.dispatch(`DELETE_FIGURE`,{sheetId:t.model.getters.getActiveSheetId(),figureId:e})},icon:`o-spreadsheet-Icon.TRASH`}}function tg(e,t){return{id:`mergeCarousel`,name:j(`Create carousel`),isVisible:t=>{let n=t.model.getters.getSelectedFigureIds();if(n.length<2||!n.includes(e))return!1;let r=t.model.getters.getActiveSheetId();return!n.map(e=>t.model.getters.getFigure(r,e)).some(e=>e===void 0||e.tag!==`chart`)},execute:()=>{let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getSelectedFigureIds();t.model.dispatch(`MERGE_CHART_FIGURES_INTO_CAROUSEL`,{sheetId:n,baseFigureId:e,chartFigureIds:r})},icon:`o-spreadsheet-Icon.CAROUSEL`}}let ng=new O,rg={type:`bar`,title:{},stacked:!1,dataSetStyles:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},legendPosition:`top`,humanize:!0};function ig(e,t){if(t.type===`carouselDataView`)return`o-spreadsheet-Icon.DATA`;let n=e.getChartDefinition(t.chartId);return(ng.getAll().find(e=>e.matcher?.(n))||ng.get(n.type)).preview}function ag(e,t){if(t.title)return t.title;if(t.type===`carouselDataView`)return j(`Data`);let n=e.getChartDefinition(t.chartId);return(ng.getAll().find(e=>e.matcher?.(n))||ng.get(n.type)).displayName}let og=[`x1`,pp],sg=[`x`,...og];var cg=class extends Vr{mutators=[`resetAxisLimits`,`updateAxisLimits`,`updateTrendLineConfiguration`,`clearAxisLimits`];originalAxisLimits={};currentAxesLimits={};idConversion={};axisDesignBoundaries={};handle(e){switch(e.type){case`DELETE_FIGURE`:if(e.figureId&&this.idConversion[e.figureId]){for(let t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];delete this.axisDesignBoundaries[e.figureId]}break;case`UPDATE_CHART`:let t=`${e.definition.type}-${e.chartId}`;if(this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),!(`zoomable`in e.definition&&e.definition.zoomable))this.clearAxisLimits(t),delete this.axisDesignBoundaries[e.figureId];else{let n=`axesDesign`in e.definition?e.definition.axesDesign:void 0,r=n?.x?.min,i=n?.x?.max,a=this.axisDesignBoundaries[e.figureId];(a?.min!==r||a?.max!==i)&&(this.clearAxisLimits(t),this.axisDesignBoundaries[e.figureId]={min:r,max:i})}break}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],`noStateChange`}resetAxisLimits(e,t){for(let n of sg)t[n]?this.originalAxisLimits[e]={...this.originalAxisLimits[e],[n]:{...t[n]}}:this.originalAxisLimits[e]?.[n]&&delete this.originalAxisLimits[e][n];return`noStateChange`}updateAxisLimits(e,t){let{min:n,max:r}=t;return n>r&&([n,r]=[r,n]),this.currentAxesLimits[e]={x:{min:n,max:r}},`noStateChange`}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e]?.x||!this.currentAxesLimits[e]?.x)return`noStateChange`;let t=this.originalAxisLimits[e].x;for(let n of og){if(!this.originalAxisLimits[e][n])continue;let r=t.max-t.min,i=this.originalAxisLimits[e][n],a=(i.max-i.min)/r,o=i.min-t.min*a,s=this.currentAxesLimits[e].x.min,c=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][n]={min:s*a+o,max:c*a+o}}return`noStateChange`}},lg=class extends Qm{static template=`o-spreadsheet-ZoomableChartJsComponent`;store;masterChartCanvas=(0,t.signal)(null);masterChart;mode;hasLinearScale;isBarChart;chartId=``;datasetBoundaries={min:0,max:0};removeEventListeners=()=>{};isMasterChartAllowed=!1;setup(){this.store=A(cg),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`
17
+ `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Vd(e,t,r,n),c=a.pop(),l=Nd(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=Nd(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Ud(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Wd(e){return e?e.toLowerCase().trim():``}let Gd=/([0-9\.]*)px/;function Kd(e){return Number(e.match(Gd)?.[1])}function qd(e,t,n){let r=Pd(e,t,e.font);if(r<=n)return t;let i=Pd(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=Pd(e,t,e.font);return t+`…`}function Jd(e,t,n,r=!1,i=!1,a=Kd(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Yd(e,t,n,r,i=`pt`){if(Nd(e,n,r,i)<=t)return n;let a=Nd(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Nd(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function Xd(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}let Zd={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=jd(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=Vs({value:u,format:void 0},n.locale),f=Vs({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function Qd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function $d(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=ef(this),c=(s-(i?ef(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=ef(this),c=a?ef(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function ef(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let tf=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},nf={id:`o-spreadsheet-minor-gridlines`,beforeDatasetsDraw(e){let t=e.ctx,n=e.chartArea;if(n)for(let r in e.scales){let i=e.scales[r],a=i.options,o=a?.grid?.minor;if(!o?.display)continue;let s=a?.grid?.display,c=i.ticks;if(!(!c||c.length<2)){t.save(),t.lineWidth=1,t.strokeStyle=o.color??a?.grid?.color??`#e6e6e6`;for(let e=0;e<c.length-1;e++){let r=i.getPixelForTick(e),a=i.getPixelForTick(e+1);if(!(!isFinite(r)||!isFinite(a)))for(let e=+!!s;e<4;e++){let o=e/4,s=Math.round(r+(a-r)*o)+.5;t.beginPath(),i.isHorizontal()?(t.moveTo(s,n.top),t.lineTo(s,n.bottom)):(t.moveTo(n.left,s),t.lineTo(n.right,s)),t.stroke()}}t.restore()}}}},rf=/rgba?\(|\s+|\)/gi,af=/^#([A-F\d]{2}){3,4}$/,of=/^light-dark\(\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*,\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*\)$/i,sf=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#62A300`,`#ff4136`,`#949494`,`#ff5c9d`];function cf(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return uf(e.toString(16).padStart(6,`0`))+n}function lf(e){return typeof e==`number`?e:Number.parseInt(uf(e).slice(1,7),16)}function uf(e){let t=e;if(e.startsWith(`light-dark`)){let t=e.match(of);if(!t)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${uf(t[1])}, ${uf(t[2])})`}if(e.startsWith(`rgb`)?t=gf(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!af.test(t))throw Error(`invalid color input: ${e}`);return t}function df(e){try{return uf(e),!0}catch{return!1}}function ff(e){try{return xf(e),!0}catch{return!1}}let pf=e=>e>=0&&e<=255;function mf(e,t,n,r=1){if(!pf(e)||!pf(t)||!pf(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function hf(e){let{r:t,g:n,b:r}=vf(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function gf(e){let t=e.replace(rf,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Gt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function _f(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function vf(e){e=uf(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function yf(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function bf(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function xf(e){return _f(yf(e))}function Sf(e){return bf(vf(e))}function Cf(e,t){let n=vf(t),r=vf(e),i=n.a+r.a*(1-n.a);return _f({r:Math.round((n.r*n.a+r.r*r.a*(1-n.a))/i),g:Math.round((n.g*n.a+r.g*r.a*(1-n.a))/i),b:Math.round((n.b*n.a+r.b*r.a*(1-n.a))/i),a:i})}function wf(e){return vf(typeof e==`number`?cf(e):e)}function Tf(e,t,n=0){if(!(df(e)&&df(t)))return!1;let r=vf(e),i=vf(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function Ef(e,t){if(e.startsWith(`light-dark`)){let n=e.match(of);if(!n)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${Ef(n[1],t)}, ${Ef(n[2],t)})`}return t===1?uf(e).slice(0,7):_f({...vf(e),a:t})}function Df(e,t){let n=Sf(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,xf(n))}let Of={invert:1,hueRotate:170,contrast:.85,brightness:1.2},kf=`invert(${Of.invert}) hue-rotate(${Of.hueRotate}deg) contrast(${Of.contrast}) brightness(${Of.brightness})`;function Af(e){let t=e*Math.PI/180,n=Math.cos(t),r=Math.sin(t);return[[.213+n*.787-r*.213,.715-n*.715-r*.715,.072-n*.072+r*.928],[.213-n*.213+r*.143,.715+n*.285+r*.14,.072-n*.072-r*.283],[.213-n*.213-r*.787,.715-n*.715+r*.715,.072+n*.928+r*.072]]}function jf(e){let{r:t,g:n,b:r,a:i}=vf(e),a=t/255,o=n/255,s=r/255;a/=Of.brightness,o/=Of.brightness,s/=Of.brightness,a=(a-.5)/Of.contrast+.5,o=(o-.5)/Of.contrast+.5,s=(s-.5)/Of.contrast+.5,a=Math.max(0,Math.min(1,a)),o=Math.max(0,Math.min(1,o)),s=Math.max(0,Math.min(1,s));let c=Af(-Of.hueRotate),l=Math.max(0,Math.min(1,c[0][0]*a+c[0][1]*o+c[0][2]*s)),u=Math.max(0,Math.min(1,c[1][0]*a+c[1][1]*o+c[1][2]*s)),d=Math.max(0,Math.min(1,c[2][0]*a+c[2][1]*o+c[2][2]*s));return _f({r:Math.round((1-l)*255),g:Math.round((1-u)*255),b:Math.round((1-d)*255),a:i})}function Mf(e,t){let n=Sf(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,xf(n))}function Nf(e){return hf(e)<.6?Df(e,.9):Mf(e,.75)}let Pf=`#4EA7F2`,Ff=[Pf,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],If=[Pf,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],Lf=[Pf,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],Rf=[Pf,`#3188E6`,`#056BD9`,`#155193`,`#A76DBC`,`#7F4295`,`#6D2387`,`#4F1565`,`#EA6175`,`#CE4257`,`#982738`,`#791B29`,`#43C5B1`,`#00A78D`,`#0E8270`,`#105F53`,`#F4A261`,`#F48935`,`#BE5D10`,`#7D380D`,`#8481DD`,`#5752D1`,`#3A3580`,`#26235F`,`#A4A8B6`,`#7E8290`,`#545B70`,`#3F4250`,`#FFD86D`,`#FFBC2C`,`#C08A16`,`#936A12`],zf=[Pf,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],Bf=[Pf,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],Vf=[Pf,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`,`#155193`,`#4F1565`,`#791B29`,`#105F53`,`#7D380D`,`#26235F`,`#3F4250`,`#936A12`];function Hf(e,t){return t[e%t.length]}function Uf(e){return e<=6?Ff:e<=12?If:e<=24?Lf:Rf}function Wf(e){return e<=6?Ff:e<=12?zf:e<=24?Bf:Vf}var Gf=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Uf(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Hf(this.currentColorIndex++,this.palette)}},Kf=class extends Gf{constructor(e,t=[]){super(e,t),this.palette=Wf(e).filter(e=>!t.includes(e))}},qf=class{availableColors;colors={};constructor(e=12){this.availableColors=new Kf(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};let Jf={greys:[`#ffffff`,`#808080`,`#000000`],blues:[`#f7fbff`,`#6aaed6`,`#08306b`],reds:[`#fff5f0`,`#fb694a`,`#67000d`],greens:[`#f7fcf5`,`#73c476`,`#00441b`],oranges:[`#fff5eb`,`#fd8c3b`,`#7f2704`],purples:[`#fcfbfd`,`#9e9ac8`,`#3f007d`],viridis:[`#440154`,`#21918c`,`#fde725`],cividis:[`#00224e`,`#7d7c78`,`#fee838`],rainbow:[`#B41DB4`,`#FFFF00`,`#00FFFF`]},Yf=Object.keys(Jf);function Xf(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=wf(t[e-1].color).a,i=wf(t[e].color).a,a=lf(t[e-1].color),o=lf(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:Zf(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return cf(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return cf(Qf(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return cf(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function Zf(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function Qf(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}let $f=`000000`,ep={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},tp={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},np=`http://schemas.openxmlformats.org/drawingml/2006/main`,rp=`http://schemas.openxmlformats.org/drawingml/2006/chart`,ip={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},ap={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},op=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,sp=.75,cp=.143,lp=8.43,up=12.75,dp={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}],IFERROR:[{type:`NUMBER`,value:0}]},fp=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),pp=`xMovingAverage`,mp={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function hp(e,t,n){return n?zl(e,t,n):void 0}function gp(e,{applyChange:t}){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function _p(e,t,n){let r=[];for(let i of n.dataSets){let{unboundedZone:a,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(t,i.dataRange);if(!(s||c))if(a.left!==a.right&&a.top!==a.bottom){if(a.right===void 0)continue;let t=i.dataSetId;for(let i=a.left;i<=a.right;i++){let s={...a,left:i,right:i};r.push({...vp(e,o,s,n.dataSetsHaveTitle?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),dataSetId:t}),t=`${t}_${i}`}}else r.push({...vp(e,o,a,n.dataSetsHaveTitle?{top:a.top,bottom:a.top,left:a.left,right:a.left}:void 0),dataSetId:i.dataSetId})}return r}function vp(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${Yn(n)}`);if(r){let i=Yn(n),a=Yn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Yn(n))}}function yp(e,t,n){let r=n.labelCell?.zone,i=n.dataRange.zone;if(r){let{numberOfRows:e,numberOfCols:t}=cr(i);e===1?i={...i,left:i.left+1}:t===1&&(i={...i,top:i.top+1})}let a=t[n.dataSetId]??{},o=Nl({...n.dataRange,zone:i},e.getSheetSize),s={};a.label?s={text:a.label}:n.labelCell&&(s={reference:e.getRangeString(n.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let c;return a.trend?.type&&(c={type:a.trend.type===`polynomial`&&a.trend.order===1?`linear`:mp[a.trend.type],color:a.trend.color,order:a.trend.order?Math.min(a.trend.order,6):void 0,window:a.trend.window||2}),{label:s,range:e.getRangeString(o,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,trend:c}}function bp(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=Nl({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function xp(e){return e&&hf(e)<.3?`#FFFFFF`:`#000000`}function Sp(e){return e&&hf(e)<.3?`#C8C8C8`:`#666666`}function Cp(e){return e.dataSets.find(e=>!Dc.test(e.dataRange))!==void 0||e.dataSets.map(e=>Un(e.dataRange)).some(e=>e.top!==e.bottom&&yr(e))?`InvalidDataSet`:`Success`}function wp(e){return e.labelRange&&!Dc.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function Tp(e,t,n){return n&&!!t&&e>=t}function Ep(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function Dp(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};let r=`dataSetStyles`in e?e.dataSetStyles??{}:{};for(let e of Object.values(r))e?.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function Op(e,t,n=!1){return(r,i)=>{let a=e?.[i];return kp({format:a,locale:t},n)(r)}}function kp(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return Mp(t?Vs({value:n,format:i},r):z(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let Ap=[{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}];function jp(e,t){let n=[],r=pn(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function Mp(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function Np(e){return e===`x1`||e===`xMovingAverage`}function Pp({background:e},t){let n=t.getSpreadsheetTheme().backgroundColor;return e||n}function Fp(e,t){return e.type===`bar`&&t.type===`line`}let Ip={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:Hp(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:Rp(e,n,r);break;case`bar`:n.horizontal?Vp(e,n,r):Rp(e,n,r);break;case`pyramid`:Vp(e,n,r);break;case`calendar`:zp(e,n,r);break;case`bubble`:Bp(e,n,r);break;case`funnel`:Vp(e,n,r);break}r.restore()}};function Lp(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function Rp(e,t,n){let r={};for(let i of e._metasets){if(Np(i.xAxisID)||i.hidden||Fp(t,i))continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else if(e.config.type===`bubble`)d=l.y;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=e+13*(c<0?1:-1));r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,Lp(t.callback(Number(c),i,o),u,d,n)}}}function zp(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(Np(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||Lp(g,d,f,n)}}}function Bp(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top,a={};for(let o of e._metasets)for(let e=0;e<o._parsed.length;e++){let s=o._parsed[e].y;if(isNaN(s))continue;let c=o.data[e],l=c.x,u=Math.max(Math.min(c.y,r),i);a[l]||(a[l]=[]);for(let e of a[l]||[])Math.abs(e-u)<13&&(u=e+13*(s<0?1:-1));a[l].push(u);let d=c.options.backgroundColor??`#ffffff`;Sf(uf(d)).a===1?n.fillStyle=xp(d):n.fillStyle=`#000000`;let f=t.callback(Number(s),o,e);n.fillText(f,l,u)}}function Vp(e,t,n){let r={};for(let i of e._metasets){if(Np(i.xAxisID)||Fp(t,i))continue;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Nd(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,Lp(s,f,l,n)}}}function Hp(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Nd(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,ee=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=ee||ee<h))continue;let y=t.background(Number(i),r,e);n.fillStyle=xp(y),n.strokeStyle=y||`#ffffff`,Lp(m,f,p,n)}}let Up={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Wp={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Gp={inSeconds:function(e){return Math.floor(e/Wp.second)},inMinutes:function(e){return Math.floor(e/Wp.minute)},inHours:function(e){return Math.floor(e/Wp.hour)},inDays:function(e){return Math.floor(e/Wp.day)},inMonths:function(e){return Math.floor(e/Wp.month)},inYears:function(e){return Math.floor(e/Wp.year)}},Kp=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function qp(e,t,n){let r=Jp(t),i=Xp(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function Jp(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function Yp(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Xp(e,t,n){let r=e.map(e=>Yi(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=pn(i)-mn(i),o=Yp(t);return Wp.second>=Wp[o]&&Gp.inSeconds(a)<180?`second`:Wp.minute>=Wp[o]&&Gp.inMinutes(a)<180?`minute`:Wp.hour>=Wp[o]&&Gp.inHours(a)<96?`hour`:Wp.day>=Wp[o]&&Gp.inDays(a)<90?`day`:Wp.month>=Wp[o]&&Gp.inMonths(a)<36?`month`:`year`}function Zp(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a,axisType:o}=t,s={stacked:e.stacked,locale:i};if(e.horizontal)n.x=fm(e,`bottom`,`values`,o,{...s,format:a?.x}),n.y={...fm(e,`left`,`labels`,`linear`,s),grid:{display:!1}};else{n.x={...fm(e,`bottom`,`labels`,o,s),grid:{display:!1}};let t={...s,format:a?.y};n.y=fm(e,`left`,`values`,`linear`,t);let r={...s,format:a?.y1};n.y1=fm(e,`right`,`values`,`linear`,r)}if(n=Qt(n),r&&r.length&&r.some(w)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[pp]={...n.x,offset:!0,display:!1}}return n}function Qp(e,t){let n=t.map(e=>e.label||``),r=xp(e.background);return{y:{title:dm(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:dm(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function $p(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(V).map(e=>e.value),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(w):[...Jf[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:xp(e.background),minValue:i,maxValue:a,locale:t.locale}}function em(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:fm(e,`bottom`,`labels`,r,{locale:n}),y:fm(e,`left`,`values`,`linear`,{locale:n,stacked:c,format:o?.y}),y1:fm(e,`right`,`values`,`linear`,{locale:n,stacked:c,format:o?.y1})};if(l=Qt(l),r===`time`&&a&&s){let t={type:`time`,time:qp(a,s,n),min:z(e.axesDesign?.x?.min??``,{format:s,locale:n}),max:z(e.axesDesign?.x?.max??``,{format:s,locale:n})};Object.assign(l.x,t),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>Vs({value:e,format:s},n):e=>z(e,{format:s,locale:n}));if(i&&i.length&&i.some(w)&&(l.x1={...l.x,display:!1},l[pp]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=C(0,e).map(e=>e.toString()),l.x1.offset=!1,l[pp].type=`category`,l[pp].offset=!1}return l}function tm(e){return hf(e||`#ffffff`)>.5?`#cccccc`:`#999999`}function nm(e){return hf(e||`#ffffff`)>.5?`#e6e6e6`:`#333333`}function rm(e,t){let n=em(e,t),r=n?.x??{},i=e.axesDesign?.x,a=i?.gridLines!==`none`&&i?.gridLines!==`minor`;return{...n,x:{...r,grid:{...r.grid,color:tm(e.background),display:a}}}}function im(e,t){let n=rm(e,t),r=e.verticalAxisPosition||`left`;return{...n,y:{...n.y,position:r}}}function am(e,t){let{locale:n,axisFormats:r,axisType:i}=t,a=r?.y||r?.y1,o=e.axesDesign?.y,s={x:{...fm(e,`bottom`,`labels`,i,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:xp(e.background),callback:kp({locale:n,format:a},e.humanize)},title:dm(e.axesDesign?.y),min:o?.min,max:o?.max,grid:{lineWidth:e=>e.tick.value===0?2:1,display:o?.gridLines!==`none`&&o?.gridLines!==`minor`,color:tm(e.background)}}};return(o?.gridLines===`minor`||o?.gridLines===`both`)&&(s.y.grid.minor={display:!0,color:nm(e.background)}),s}function om(e,t){let{dataSetsValues:n}=t,r=Zp(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.filter(V).map(e=>Math.abs(e.value)))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function sm(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(V).map(e=>e.value))));return{r:{beginAtZero:!0,ticks:{callback:kp({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:xp(e.background),callback:e=>Mp(e)},suggestedMin:a<0?a-1:0}}}function cm(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=hm(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:um(o?.defaultProjection||`mercator`),axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:Ie},grid:{color:Ie},ticks:{color:xp(e.background),callback:kp({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:mm(e)},interpolate:pm(e.colorScale??ze),missing:e.missingValueColor||`#ffffff`}}}function lm(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Mp(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o?.value||a?.value===null||!V(a)||!V(o)?``:z(a.value/o.value,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function um(e){return globalThis.ChartGeo&&e===`conicConformal`?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function dm(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:Rd(e.title.fontSize??12)},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function fm(e,t,n,r,i){let{useLeftAxis:a,useRightAxis:o}=Dp(e);if(t===`left`&&!a||t===`right`&&!o)return;let s=xp(e.background),c;if(c=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&a),o=c?.gridLines?c?.gridLines===`major`||c?.gridLines===`both`:n,l=!(r===`category`||r===void 0)&&(c?.gridLines===`minor`||c?.gridLines===`both`),u=kp(i,e.humanize),d={position:t,title:dm(c),beginAtZero:!c?.min,stacked:i?.stacked,ticks:{color:s,callback:u},min:c?.min,max:c?.max,grid:{display:o,color:tm(e.background)}};return l&&(d.grid.minor={display:!0,color:nm(e.background)}),d}else{let t={ticks:{padding:5,color:s,callback:function(e,t,n){return Mp(this.getLabelForValue(e))}},min:c?.min,max:c?.max,grid:{display:c?.gridLines===`major`||c?.gridLines===`both`,color:tm(e.background)},stacked:i?.stacked,title:dm(c)};return(c?.gridLines===`minor`||c?.gridLines===`both`)&&(t.grid.minor={display:!0,color:nm(e.background)}),t}}function pm(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),Xf(r)}function mm(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function hm(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let gm=`nullValue`;function _m(e,t){let{dataSetsValues:n,background:r}=t,i=[],a=Bm(e.dataSetStyles,n),o=[];for(let s in n){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label??c;let f=a.next(),p={label:c,data:l.map(e=>V(e)?e.value:NaN),hidden:u,borderColor:e.background||r,borderWidth:+!!e.stacked,backgroundColor:f,yAxisID:e.horizontal?`y`:e.dataSetStyles?.[d]?.yAxisId??`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};i.push(p);let m=e.dataSetStyles?.[d]?.trend,h=t.trendDataSetsValues?.[s];!m?.display||e.horizontal||!h||o.push(Rm(p,m,h))}i.push(...o);let s=vm(e,n);return s&&i.push(s),i}function vm(e,t){let n=t.filter(e=>!e.hidden);if(!e.stacked||!e.showTotalLine||n.length<2)return;let r=C(0,Math.max(...n.map(e=>e.data.length))).map(e=>{let t;for(let r of n){let n=r.data[e];V(n)&&(t=(t??0)+n.value)}return t??NaN}),i=hf(e.background||`#FFFFFF`)<.3?`#e9ecef`:`#343a40`;return{type:`line`,label:j(`Sum`),data:r,order:-1,tension:0,fill:!1,pointRadius:3,borderWidth:2,backgroundColor:i,borderColor:i,pointBackgroundColor:i,xAxisID:`x`,yAxisID:`y`}}function ym(e,t){let{labels:n,dataSetsValues:r,background:i}=t,a=r.map(e=>e.data).flat().filter(V).map(e=>e.value),o=Math.max(...a),s=Math.min(...a),c=pm(e.colorScale??ze,s,o),l=[];for(let t of r)l.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>V(t)?c(t.value):e.missingValueColor||`#00000000`),borderColor:e.background||i,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data.map(e=>V(e)?e.value:NaN)});return{labels:n,datasets:l}}function bm(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),!V(f)){c.push([d,d]),s.push(``);continue}c.push([d,f.value+d]);let p=f.value>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f.value}e.showSubTotals&&(u.push(j(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function xm(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=Bm(e.dataSetStyles,n);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p,dataSetId:m}=n[u];d=e.dataSetStyles?.[m]?.label??d;let h=[],g=l.next();h=r&&[`linear`,`time`].includes(r)?f.map((e,t)=>({x:i[t]===``?NaN:i[t]??NaN,y:V(e)?e.value:NaN})):f.map(e=>V(e)?e.value:NaN);let _=e.dataSetStyles?.[m],v={label:d,data:h,hidden:p,tension:0,borderColor:g,backgroundColor:o?Ef(g,tt):g,pointBackgroundColor:g,fill:o?zm(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:_?.yAxisId||`y`};a.push(v);let ee=_?.trend,y=t.trendDataSetsValues?.[u];!ee?.display||!y||c.push(Rm(v,ee,y))}return a.push(...c),a}function Sm(e,t){let n=xm(e,t);for(let e of n)Np(e.xAxisID)||(e.showLine=!1);return n}function Cm(e,t){let n,r;if(e.bubbleColor.color===`multiple`){let i=new Gf(t.bubbleSizes.length);r=[];for(let e=0;e<t.bubbleSizes.length;e++)r.push(i.next());n=r.map(t=>Ef(t,e.bubbleColor.transparent?.5:1))}else r=e.bubbleColor.color,n=Ef(r,e.bubbleColor.transparent?.5:1);let i=wm(t.bubbleSizes),a=[];for(let e=0;e<t.bubbleSizes.length;e++){let n=t.dataSetsValues[0].data[e];a.push({x:t.labels[e],y:V(n)?n.value:NaN})}return[{label:t.dataSetsValues[0]?.label,data:a,backgroundColor:n,borderColor:r,hoverBackgroundColor:n,hoverBorderColor:r,yAxisID:`y`,pointRadius:i,pointHoverRadius:i,showLine:!1}]}function wm(e){if(!e.length)return[];let t=e.filter(e=>Number.isFinite(e)&&e>0),n=t.length?Math.min(...t):0,r=(t.length?Math.max(...t):0)-n;return t.length?e.map(e=>e===void 0||!Number.isFinite(e)||e<0?0:e===0?2:r===0?10:10+S((e-n)/r,0,1)*20):e.map(()=>2)}function Tm(e,t){let{dataSetsValues:n}=t,r=[],i=jp(new Gf(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a.map(e=>V(e)?e.value:NaN),borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function Em(e,t){let{dataSetsValues:n}=t,r=[],i=Bm(e.dataSetStyles,n),a=[],o=n.filter(({dataSetId:t})=>(e.dataSetStyles?.[t]?.type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label||c;let f=e.dataSetStyles?.[d],p=i.next(),m=s===0?`bar`:`line`,h=f?.type??m,g={label:c,data:l.map(e=>V(e)?e.value:null),hidden:u,borderColor:p,backgroundColor:p,yAxisID:e.dataSetStyles?.[d]?.yAxisId||`y`,xAxisID:`x`,type:h,order:h===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};g.type===`bar`&&(g.barPercentage=.9,g.categoryPercentage=o.length>1?.8:1,g.borderRadius=2),r.push(g);let _=e.dataSetStyles?.[d]?.trend,v=t.trendDataSetsValues?.[s];!_?.display||!v||a.push(Rm(g,_,v))}return r.push(...a),r}function Dm(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=Bm(e.dataSetStyles,n);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSetStyles?.[t]?.label&&(o=e.dataSetStyles[t].label);let l=a.next(),u={label:o,data:s.map(e=>V(e)?e.value:null),hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Ef(l,tt),u.fill=`start`),r.push(u)}return r}function Om(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){let o=r[0].data[n];if(!i[n]||o===void 0)continue;let s=t.geoFeatureNameToId(a,i[n]);s&&(e[s]={value:V(o)?o.value:0,label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function km(e,t){let n=t.dataSetsValues[0],{labels:r,background:i}=t;if(!n)return[];let{label:a,data:o}=n;return a=e.dataSetStyles?.[0]?.label||a,[{label:a,data:o.map(e=>{if(!V(e))return 0;let t=e.value;return t<=0?[0,0]:[-t,t]}),backgroundColor:Am(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||i,borderWidth:3}]}function Am(e,t){let n=new Gf(e.length,t);return e.map(()=>n.next())}function jm(e,t){let{dataSetsValues:n,labels:r,background:i}=t,a=Fm(Nm(n,r)),o=a[0]||[],s=new Gf(o.length,e.groupColors||[]),c=o.map(e=>({label:e.label,color:s.next()})),l=[];for(let t=a.length-1;t>=0;t--){let n={groupColors:c,parsing:{key:`value`},data:a[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?Ne:e.background||i},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return Ne;let n=t.groups[0];return c.find(e=>e.label===n)?.color},hoverOffset:10};l.push(n)}return l}function Mm(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]?.value,a=r===null?gm:String(r);n[i][t]=a}n[i].value=Number(t[i])}return n}function Nm(e,t){return Pm(Mm(e,t),0,e.length,[])}function Pm(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:Pm(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function Fm(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function Im(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=Nm(n,r).sort((e,t)=>t.value-e.value),c=Vm(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e].value?String(n[t].data[e].value):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Up.showLabels,f=e.showValues??Up.showValues,p=e.coloringOptions||Up.coloringOptions,m;return p?.type===`colorScale`&&(m=Hm(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...Lm(e.valuesDesign,Up.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?z(e.raw.v,o):void 0].filter(w)},captions:{display:e.showHeaders??Up.showHeaders,padding:6,...Lm(e.headerDesign,Up.headerDesign)},key:`value`,groups:C(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Up.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return Um(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function Lm(e,t){let n=e=>{let t=e.element.options.backgroundColor;return hf(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:Rd(e?.fontSize??t.fontSize)}}}function Rm(e,t,n){let r=vf(e.backgroundColor);r.a=1;let i=t.color||Df(_f(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?pp:`x1`,yAxisID:e.yAxisID,label:e.label?j(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function zm(e,t){return t?e===0?`origin`:`-1`:`origin`}function Bm(e,t){let n=t.map(t=>e?.[t.dataSetId]?.backgroundColor),r=t.length;return new Gf(r,n)}function Vm(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new Gf(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function Hm(e,t){if(e.length===0)return;let n=Fm(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),Xf(e)}}function Um(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=Fm(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Df(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let Wm={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Gm(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==gm}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Df(s,.5):e.options.backgroundColor=s}}};function Gm(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Km={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;qm(e,n,r)}};function qm(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(w),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,ee=(p+m)/2,y=(m-p)*.9,b=f-d;if((b>=Math.PI?m:Math.sin(b/2)*p*2)<l.length*a)continue;n.save();let te={x:Math.cos(v)*g,y:Math.sin(v)*g},ne=e.chartArea.left+e.chartArea.width/2+te.x,re=e.chartArea.top+e.chartArea.height/2+te.y;n.translate(ne,re);let ie;v>Math.PI/2?(n.rotate(v-Math.PI),ie=-ee):(ie=ee,n.rotate(v));let ae=u.options.backgroundColor,oe=hf(ae)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||oe,n.textAlign=`center`,n.textBaseline=`middle`,n.font=jd(i,r.bold,r.italic);let se=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Yd(n,y,l[e],r,`px`);n.fillText(t,ie,se+e*a)}n.restore()}}let Jm={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Xm(r,e);if(!n)break;let a=Ym(t),o=Ym(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Ym(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Xm(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Zm={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};Wr.add(`chartShowValuesPlugin`,{register:e=>e.register(Ip),unregister:e=>e.unregister(Ip)}),Wr.add(`chartMinorGridPlugin`,{register:e=>e.register(nf),unregister:e=>e.unregister(nf)}),Wr.add(`waterfallLinesPlugin`,{register:e=>e.register(Jm),unregister:e=>e.unregister(Jm)}),Wr.add(`funnelController`,{register:e=>e.register(Qd()),unregister:e=>e.unregister(Qd())}),Wr.add(`funnelElement`,{register:e=>e.register($d()),unregister:e=>e.unregister($d())}),Wr.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=tf,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Wr.add(`sunburstLabelsPlugin`,{register:e=>e.register(Km),unregister:e=>e.unregister(Km)}),Wr.add(`sunburstHoverPlugin`,{register:e=>e.register(Wm),unregister:e=>e.unregister(Wm)}),Wr.add(`chartColorScalePlugin`,{register:e=>e.register(Zd),unregister:e=>e.unregister(Zd)}),Wr.add(`calendarController`,{register:e=>e.register(Mi()),unregister:e=>e.unregister(Mi())}),Wr.add(`zoomWindowPlugin`,{register:e=>e.register(Zm),unregister:e=>e.unregister(Zm)}),Wr.add(`chartBackgroundPlugin`,{register:e=>e.register(ji),unregister:e=>e.unregister(ji)});var Qm=class extends k{static template=`o-spreadsheet-ChartJsComponent`;props=(0,t.props)({chartId:t.types.string(),"isFullScreen?":t.types.boolean()});canvas=(0,t.signal)(null);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=A(Ai)),(0,t.onMounted)(()=>{Kr();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(x(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),hi(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(x(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(x(e)):(this.chart?.destroy(),this.createChart(x(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas();if(!n)return;let r=n.getContext(`2d`);this.chart=new globalThis.Chart(r,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!T(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},$m=class{static commonKeys=[`type`,`title`,`background`,`humanize`]};function eh(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Vs(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Vs({value:a,format:o},i):z(a,{format:o,locale:i})}function th(e,t,n){return e?t?Vs(e,n):e.formattedValue??String(e.value??``):``}function nh(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function rh(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function ih(e){return e.keyValue&&!Dc.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function ah(e){return e.baseline&&!Dc.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let oh=globalThis.Path2D,sh=oh&&new oh(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),ch=oh&&new oh(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`),lh={sequence:40,allowedDefinitionKeys:[...$m.commonKeys,`keyValue`,`keyDescr`,`baseline`,`baselineMode`,`baselineDescr`,`baselineColorUp`,`baselineColorDown`],fromStrDefinition(e,t,n){let r=Bl(n,t,e.baseline),i=Bl(n,t,e.keyValue);return{...e,baseline:r,keyValue:i}},validateDefinition(e,t){return e.checkValidations(t,ih,ah)},copyInSheetId:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,type:`scorecard`,keyValue:e.dataSource?.type===`range`?e.dataSource?.dataSets?.[0]?.dataRange:void 0,title:e.title||{text:``},baselineMode:Qe,baselineColorUp:$e,baselineColorDown:et,baseline:e.auxiliaryRange||``,humanize:e.humanize}},transformDefinition(e,t,{adaptRangeString:n}){let r,i;if(e.baseline){let{changeType:i,range:a}=n(t,e.baseline);i!==`REMOVE`&&(r=a)}if(e.keyValue){let{changeType:r,range:a}=n(t,e.keyValue);r!==`REMOVE`&&(i=a)}return{...e,baseline:r,keyValue:i}},duplicateInDuplicatedSheet(e,t,n){let r=hp(t,n,e.baseline),i=hp(t,n,e.keyValue);return{...e,baseline:r,keyValue:i}},toStrDefinition(e,t,n){return{...e,keyValue:e.keyValue?n.getRangeString(e.keyValue,t):void 0,baseline:e.baseline?n.getRangeString(e.baseline,t):void 0}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.keyValue?[{dataRange:e.keyValue,dataSetId:`0`}]:[]},auxiliaryRange:e.baseline}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=gp(e.baseline,t),r=gp(e.keyValue,t);return e.baseline===n&&e.keyValue===r?e:{...e,baseline:n,keyValue:r}},getRuntime(e,t){let n=``,r,i=e.getLocale();if(t.keyValue){let a={sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top};r=e.getEvaluatedCell(a),n=th(r,t.humanize??!0,i)}let a,o=t.baseline;if(o){let t={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=e.getEvaluatedCell(t)}let{background:s,fontColor:c}=e.getStyleOfSingleCellChart(t.background,t.keyValue),l=eh(a,r,t.baselineMode,t.humanize??!0,i),u=t.baselineMode===`progress`&&Ta(l,i)?P(l,i):0,d=t.title;return{title:{...d,text:d.text?e.dynamicTranslate(d.text):``},keyValue:n,keyDescr:t.keyDescr?.text?e.dynamicTranslate(t.keyDescr.text):``,baselineDisplay:l,baselineArrow:rh(a,r,t.baselineMode),baselineColor:nh(a,t.baselineMode,r,t.baselineColorUp,t.baselineColorDown),baselineDescr:t.baselineMode!==`progress`&&t.baselineDescr?.text?e.dynamicTranslate(t.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...t.baselineMode!==`percentage`&&t.baselineMode!==`progress`&&o?e.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:t.baselineDescr?.fontSize,align:t.baselineDescr?.align},baselineDescrStyle:{textColor:t.baselineDescr?.color,...t.baselineDescr},keyValueStyle:{...t.keyValue?e.getCellComputedStyle({sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top}):void 0,fontSize:t.keyDescr?.fontSize,align:t.keyDescr?.align},keyValueDescrStyle:{textColor:t.keyDescr?.color,...t.keyDescr},progressBar:t.baselineMode===`progress`?{value:u,color:u>0?t.baselineColorUp:t.baselineColorDown}:void 0}}};function uh(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(qd(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Jd(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&oh){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(sh);break;case`up`:r.fill(ch);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(qd(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Jd(r,qd(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(qd(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}let dh=.05;function fh(e,t){let n=e||``;return t&&n?` `+n:n}function ph({width:e,height:t},n){return new mh({width:e,height:t},n).computeDesign()}var mh=class{runtime;context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-dh*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*dh)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-dh*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return fh(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return fh(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Sp(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:jd(Rd(this.runtime.title.fontSize??14),this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:jd(Rd(e),this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:jd(Rd(t),this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:jd(Rd(n),this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:jd(Rd(r),this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*Rd(n):0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};function hh(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=vh(t,r)),!n)return gh(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function gh(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function _h(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function vh(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:ee(n,t)}var yh=class extends k{static template=`o-spreadsheet-ScorecardChart`;props=(0,t.props)({chartId:t.types.string(),"isFullScreen?":t.types.boolean()});canvas=(0,t.signal)(null);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){hi(this.createChart.bind(this),()=>{let e=this.canvas();if(!e)return[];let t=e.getBoundingClientRect();return[t.width,t.height,this.runtime,e,window.devicePixelRatio]});let e=new ResizeObserver(()=>this.createChart());(0,t.onMounted)(()=>{let t=this.canvas();t&&e.observe(t)}),(0,t.onWillUnmount)(()=>e.disconnect())}createChart(){let e=this.canvas();if(!e)return;let t=this.env.model.getters.getViewportZoomLevel();uh(ph(_h(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};let bh=`#F3F2F1`;function xh(e,t,n=1,r){let i=r??Sh(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Oh({width:i.width/n,height:i.height/n,x:0,y:0},t,o);wh(o,s),Ch(o,s),Eh(o,s),Th(o,s),Dh(o,s)}function Sh(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function Ch(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=bh,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function wh(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function Th(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${Ye}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Eh(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=Sp(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${Ye}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function Dh(e,t){e.save();let n=t.title;e.font=jd(Rd(n.fontSize),n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Oh(e,t,n){let r=t.maxValue,i=t.minValue,a=Ih(t,`animated`),o=kh(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Nd(n,f,{fontSize:u},`px`)>d&&(u=Ud(d,u,e=>Nd(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=Sp(t.background),g=Ah(t,o,h,n),_=0,v=0,ee=0;switch(t.title.text&&({width:v,height:ee}=Id(n,t.title.text,{...t.title,fontSize:Rd(t.title.fontSize??16)},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+ee/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:S(c,0,1),color:jh(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function kh(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function Ah(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Nd(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=Fh(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>Ph(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function jh(e){let t=Ih(e,`final`);if(t===void 0)return bh;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function Mh(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function Nh(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function Ph(e,t){let n=Mh(e),r=Mh(t);for(let e of n)for(let t of r)if(Nh(e,t))return!0;return!1}function Fh(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function Ih(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let Lh={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function Rh(e,t,n){try{let r=Bh(t.width,t.height),i=Uh(r,e,t,n),a=await Hh(r);return i(),a}catch(e){console.log(`Error exporting chart to image URL: `+e.message)}}async function zh(e,t,n){try{let r=Bh(t.width,t.height),i=Uh(r,e,t,n),a=await Vh(r);return i(),a}catch(e){console.log(`Error exporting chart to image file: `+e.message)}return null}function Bh(e,t){if(!globalThis.OffscreenCanvas)throw Error(`converting a chart to an image using OffscreenCanvas is not supported in this environment`);return new OffscreenCanvas(e,t)}async function Vh(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function Hh(e){let t=await Vh(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}function Uh(e,t,n,r){if(`chartJsConfig`in t){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let n=Gr();n||Kr();let r=x(t.chartJsConfig);if(!globalThis.Chart.registry.controllers.get(r.type))throw console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),n||qr(),Error(`Chart of type "${r.type}" is not registered in Chart.js library.`);let i=new globalThis.Chart(e,r);return()=>{i.destroy(),n||qr()}}else r===`scorecard`?uh(ph(n,t),e):r===`gauge`&&xh(e,t,1,n);return()=>{}}function Wh(e,t){let{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),a=n+Math.max(0,(i.width-t.width)/2),o=r+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:a,y:o})}function Gh(e,t){let n=x(t),r=e.getSheetViewDimension(),i=r.width,a=r.height;if(n.width>i){let e=i/n.width;n.width=i,n.height*=e}if(n.height>a){let e=a/n.height;n.height=a,n.width*=e}return n}function Kh(e,t,n,r){let i=e.getMaxAnchorOffset(t,r.height,r.width),{col:a,row:o}=n,s={...r.offset};for(let n=e.getColSize(t,a);s.x>n;n=e.getColSize(t,a))a+=1,s.x-=n;a>i.col&&(a=i.col,s.x=i.offset.x);for(let n=e.getRowSize(t,o);s.y>n;n=e.getRowSize(t,o))o+=1,s.y-=n;return o>i.row&&(o=i.row,s.y=i.offset.y),{col:a,row:o,offset:s}}function qh(e,t){return t.model.getters.getChartIdFromFigureId(e)?ve([tg(e,t),{id:`edit`,name:j(`Edit`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`)},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},Xh(e,t),Zh(e,t),Qh(e,t),$h(e,t),eg(e,t)]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0):[]}function Jh(e,t){return ve([Xh(e,t,j(`Image copied to clipboard`)),Zh(e,t),{id:`reset_size`,name:j(`Reset size`),execute:async()=>{let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getFigure(n,e);if(!r)return;let i=t.model.getters.getImagePath(e),a=t.model.getters.getImageSize(e)??await t.imageProvider?.getImageOriginalSize(i);if(!t.model.getters.getImageSize(e)){let n=t.model.getters.getImage(e);n.size=a}let{col:o,row:s}=r,{height:c,width:l}=Gh(t.model.getters,a);t.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,figureId:e,height:c,width:l,col:o,row:s})},icon:`o-spreadsheet-Icon.REFRESH`},{id:`download`,name:j(`Download`),execute:async()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),de(t.model.getters.getImagePath(e),`image`)},icon:`o-spreadsheet-Icon.DOWNLOAD`},eg(e,t)])}function Yh(e,t){let n=t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`;return ve([{id:`edit_carousel`,name:j(`Edit carousel`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`CarouselPanel`,{figureId:e})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall},{...Xh(e,t,j(`Carousel copied to clipboard`)),name:j(`Copy carousel`)},{...Zh(e,t),name:j(`Cut carousel`)},{...eg(e,t),name:j(`Delete carousel`),separator:!0},{id:`edit_chart`,name:j(`Edit chart`),execute:()=>{t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.openSidePanel(`ChartPanel`,{})},icon:`o-spreadsheet-Icon.EDIT`,isEnabled:e=>!e.isSmall,isVisible:n},{...Qh(e,t),isVisible:n,name:j(`Copy chart as image`)},{...$h(e,t),isVisible:n,name:j(`Download chart`)},{id:`popout_chart`,name:j(`Pop out chart`),icon:`o-spreadsheet-Icon.EXTERNAL`,execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);!n||n.type!==`chart`||t.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{carouselId:e,chartId:n.chartId,sheetId:t.model.getters.getActiveSheetId()})},isVisible:n},{id:`delete_carousel_item`,name:t=>t.model.getters.getSelectedCarouselItem(e)?.type===`chart`?j(`Delete chart`):j(`Delete data view`),execute:()=>{let n=t.model.getters.getSelectedCarouselItem(e);if(!n)return;let r=t.model.getters.getCarousel(e),i=r.items.filter(e=>!T(e,n));t.model.dispatch(`UPDATE_CAROUSEL`,{figureId:e,sheetId:t.model.getters.getActiveSheetId(),definition:{...r,items:i}})},icon:`o-spreadsheet-Icon.TRASH`,isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>t.model.getters.isReadonly()?e.isReadonlyAllowed:!0)}function Xh(e,t,n){return{id:`copy`,name:j(`Copy`),shortcut:`Ctrl+C`,execute:async()=>{t.model.getters.getSelectedFigureIds().includes(e)||t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`COPY`);let r=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(r),n&&t.notifyUser({sticky:!1,type:`success`,text:n})},icon:`o-spreadsheet-Icon.CLIPBOARD`,isEnabledOnLockedSheet:!0}}function Zh(e,t){return{id:`cut`,name:j(`Cut`),shortcut:`Ctrl+X`,execute:async()=>{t.model.getters.getSelectedFigureIds().includes(e)||t.model.dispatch(`SELECT_FIGURE`,{figureId:e}),t.model.dispatch(`CUT`),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`}}function Qh(e,t){return{id:`copy_as_image`,name:j(`Copy as image`),icon:`o-spreadsheet-Icon.COPY_AS_IMAGE`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await zh(t.model.getters.getChartRuntime(i),r,a);if(!o)return;let s=await new Promise(e=>{let t=new FileReader;t.addEventListener(`loadend`,n=>{let r=t.result;e(r)}),t.readAsArrayBuffer(o)}),c=`<img src="data:image/png;base64,${new Uint8Array(s).toBase64()}" />`;await t.clipboard.write({"text/html":c,"image/png":o}),t.notifyUser({sticky:!1,type:`success`,text:j(`Chart copied to clipboard`)})},isVisible:e=>e.model.getters.getSelectedFigureIds().length<=1,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function $h(e,t){return{id:`download`,name:j(`Download`),icon:`o-spreadsheet-Icon.DOWNLOAD`,execute:async()=>{let n=t.model.getters.getFigureSheetId(e),r=t.model.getters.getFigure(n,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;let a=t.model.getters.getChartType(i),o=await Rh(t.model.getters.getChartRuntime(i),r,a);o&&de(o,`chart`)},isVisible:e=>e.model.getters.getSelectedFigureIds().length<=1,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0}}function eg(e,t){return{id:`delete`,name:j(`Delete`),execute:()=>{let n=t.model.getters.getSelectedFigureIds();n.includes(e)?t.model.dispatch(`DELETE_FIGURES`,{sheetId:t.model.getters.getActiveSheetId(),figureIds:n}):t.model.dispatch(`DELETE_FIGURE`,{sheetId:t.model.getters.getActiveSheetId(),figureId:e})},icon:`o-spreadsheet-Icon.TRASH`}}function tg(e,t){return{id:`mergeCarousel`,name:j(`Create carousel`),isVisible:t=>{let n=t.model.getters.getSelectedFigureIds();if(n.length<2||!n.includes(e))return!1;let r=t.model.getters.getActiveSheetId();return!n.map(e=>t.model.getters.getFigure(r,e)).some(e=>e===void 0||e.tag!==`chart`)},execute:()=>{let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getSelectedFigureIds();t.model.dispatch(`MERGE_CHART_FIGURES_INTO_CAROUSEL`,{sheetId:n,baseFigureId:e,chartFigureIds:r})},icon:`o-spreadsheet-Icon.CAROUSEL`}}let ng=new O,rg={type:`bar`,title:{},stacked:!1,dataSetStyles:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},legendPosition:`top`,humanize:!0};function ig(e,t){if(t.type===`carouselDataView`)return`o-spreadsheet-Icon.DATA`;let n=e.getChartDefinition(t.chartId);return(ng.getAll().find(e=>e.matcher?.(n))||ng.get(n.type)).preview}function ag(e,t){if(t.title)return t.title;if(t.type===`carouselDataView`)return j(`Data`);let n=e.getChartDefinition(t.chartId);return(ng.getAll().find(e=>e.matcher?.(n))||ng.get(n.type)).displayName}let og=[`x1`,pp],sg=[`x`,...og];var cg=class extends Vr{mutators=[`resetAxisLimits`,`updateAxisLimits`,`updateTrendLineConfiguration`,`clearAxisLimits`];originalAxisLimits={};currentAxesLimits={};idConversion={};axisDesignBoundaries={};handle(e){switch(e.type){case`DELETE_FIGURE`:if(e.figureId&&this.idConversion[e.figureId]){for(let t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];delete this.axisDesignBoundaries[e.figureId]}break;case`UPDATE_CHART`:let t=`${e.definition.type}-${e.chartId}`;if(this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),!(`zoomable`in e.definition&&e.definition.zoomable))this.clearAxisLimits(t),delete this.axisDesignBoundaries[e.figureId];else{let n=`axesDesign`in e.definition?e.definition.axesDesign:void 0,r=n?.x?.min,i=n?.x?.max,a=this.axisDesignBoundaries[e.figureId];(a?.min!==r||a?.max!==i)&&(this.clearAxisLimits(t),this.axisDesignBoundaries[e.figureId]={min:r,max:i})}break}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],`noStateChange`}resetAxisLimits(e,t){for(let n of sg)t[n]?this.originalAxisLimits[e]={...this.originalAxisLimits[e],[n]:{...t[n]}}:this.originalAxisLimits[e]?.[n]&&delete this.originalAxisLimits[e][n];return`noStateChange`}updateAxisLimits(e,t){let{min:n,max:r}=t;return n>r&&([n,r]=[r,n]),this.currentAxesLimits[e]={x:{min:n,max:r}},`noStateChange`}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e]?.x||!this.currentAxesLimits[e]?.x)return`noStateChange`;let t=this.originalAxisLimits[e].x;for(let n of og){if(!this.originalAxisLimits[e][n])continue;let r=t.max-t.min,i=this.originalAxisLimits[e][n],a=(i.max-i.min)/r,o=i.min-t.min*a,s=this.currentAxesLimits[e].x.min,c=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][n]={min:s*a+o,max:c*a+o}}return`noStateChange`}},lg=class extends Qm{static template=`o-spreadsheet-ZoomableChartJsComponent`;store;masterChartCanvas=(0,t.signal)(null);masterChart;mode;hasLinearScale;isBarChart;chartId=``;datasetBoundaries={min:0,max:0};removeEventListeners=()=>{};isMasterChartAllowed=!1;setup(){this.store=A(cg),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`
18
18
  height:${this.sliceable?`calc(100% - 60px)`:`100%`};
19
19
  `}get masterChartContainerStyle(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)?`opacity: 0.3;`:``}get sliceable(){if(this.props.isFullScreen)return!0;let e=this.env.model.getters.getChartDefinition(this.props.chartId);return(`zoomable`in e&&e.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){let t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;let t=e.options.scales.x;return this.store.currentAxesLimits[this.chartId]?.x&&(t={...t,...this.getStoredBoundaries()}),{...e,options:{...e.options,scales:{...e.options.scales,x:t},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){let t=e.data.datasets.map(e=>e.data).flat().map((e,t)=>typeof e==`object`&&e?e.x:t);return{min:Math.min(...t),max:Math.max(...t)}}setMasterChartCursor(e){let t=this.masterChartCanvas();if(t){if(e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)){t.style.cursor=`not-allowed`,this.isMasterChartAllowed=!1;return}t.style.cursor=`default`,this.isMasterChartAllowed=!0}}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.isBarChart=t.type===`bar`,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable&&(e.chartJsConfig=this.getDetailChartConfiguration(t)),super.createChart(e),this.hasLinearScale=this.chart?.scales?.x?.type===`linear`,!this.sliceable||!(`masterChartConfig`in e)){this.isMasterChartAllowed=!1;return}this.masterChart?.destroy();let n=this.masterChartCanvas();if(!n)return;let r=n.getContext(`2d`);this.setMasterChartCursor(e),this.masterChart=new globalThis.Chart(r,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig,{min:n,max:r}=this.getAxisLimitsFromDataset(t);if((this.datasetBoundaries.min!==n||this.datasetBoundaries.max!==r)&&(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries={min:n,max:r}),this.isBarChart=t?.type===`bar`,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable&&(e.chartJsConfig=this.getDetailChartConfiguration(t)),super.updateChartJs(e),this.hasLinearScale=this.chart?.scales?.x?.type===`linear`,!this.sliceable||!(`masterChartConfig`in e))this.masterChart=void 0,this.isMasterChartAllowed=!1;else{let t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{let e=this.masterChartCanvas();if(!e)return;let n=e.getContext(`2d`);this.masterChart=new globalThis.Chart(n,t)}this.setMasterChartCursor(e)}this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(this.chart){if(!this.store.originalAxisLimits[this.chartId]?.x){let e=this.masterChart?this.masterChart.scales:this.chart.scales;!this.hasLinearScale&&e.x&&(e={...e,x:this.adjustBoundaries(e.x)}),this.store.resetAxisLimits(this.chartId,e);return}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);let e=this.store.currentAxesLimits[this.chartId];for(let t of[`x1`,pp])!this.chart?.config?.options?.scales?.[t]||!e?.[t]||(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(e===void 0||!this.masterChart?.scales?.x)return;let t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;let{left:n,right:r}=this.masterChart.chartArea,{min:i,max:a}=t,o=this.axisOffset;return n+(r-n)*(o+e-i)/(2*o+a-i)}computeCoordinate(e){if(!this.masterChart)return;let t=this.masterChart.scales.x;if(this.hasLinearScale){let n=t.getValueForPixel(e);return n===void 0?void 0:Math.round(n*100)/100}let{left:n,right:r}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-n)/(r-n)}getStoredBoundaries(){let{min:e,max:t}=this.store.currentAxesLimits[this.chartId].x;return this.hasLinearScale||(e=Math.ceil(e),t=Math.floor(t)),{min:e,max:t}}adjustBoundaries({min:e,max:t}){return this.hasLinearScale||(e=Math.ceil(e)-this.axisOffset,t=Math.floor(t)+this.axisOffset),{min:e,max:t}}updateAxisLimits(e,t){if(e===t||!this.chart)return;this.store.updateAxisLimits(this.chartId,{min:e,max:t});let{min:n,max:r}=this.getStoredBoundaries();(r>n||this.isBarChart&&r===n)&&(this.chart.config.options.scales.x.min=n,this.chart.config.options.scales.x.max=r,this.updateTrendingLineAxes(),this.chart.update()),this.masterChart?.update()}onMasterChartPointerDown(e){this.removeEventListeners();let t=hh(this.env,e,this.masterChartCanvas()?.getBoundingClientRect()),n=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;let{left:r,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.upperBound??i,c=this.lowerBound??r;if(n<r-5||n>i+5||t.offsetY<a||t.offsetY>o)return;e.preventDefault(),e.stopPropagation();let l,u,d,f=n;if((c!==r||s!==i)&&n>c+5&&n<s-5){l=t.offsetX-c,this.mode=`moveInMaster`;let e=this.store.currentAxesLimits[this.chartId]?.x;u=(e?.max??this.chart.scales.x.max)-(e?.min??this.chart.scales.x.min)}else this.mode=`selectInMaster`,l=Math.abs(n-c)<5?s:Math.abs(n-s)<5?c:S(n,r,i),d=this.computeCoordinate(l);let p=this.store.originalAxisLimits[this.chartId].x.min,m=this.store.originalAxisLimits[this.chartId].x.max,h=e=>{if(this.mode===`moveInMaster`){let t=this.computeCoordinate(e-l);return t<p?t=p:t>m-u&&(t=m-u),{min:t,max:t+u}}else if(this.mode===`selectInMaster`){let t=S(e,r,i);if(Math.abs(l-t)>5){let e=this.computeCoordinate(t);return d===void 0||e===void 0?{}:{min:Math.min(d,e),max:Math.max(d,e)}}}return{}},g=e=>{let t=hh(this.env,e,this.masterChartCanvas()?.getBoundingClientRect()).offsetX;if(Math.abs(t-f)<5)return;let{min:n,max:r}=h(t);n!==void 0&&r!==void 0&&this.updateAxisLimits(n,r)},_=e=>{this.removeEventListeners();let{min:t,max:n}=this.chart.scales.x;this.hasLinearScale||(this.mode===`moveInMaster`?(t=Math.round(t)-this.axisOffset,n=t+u):{min:t,max:n}=this.adjustBoundaries({min:t,max:n})),this.updateAxisLimits(t,n),this.mode=void 0,this.updateMasterChartCursor(e)};this.removeEventListeners=()=>{window.removeEventListener(`pointermove`,g,!0),window.removeEventListener(`pointerup`,_,!0)},window.addEventListener(`pointermove`,g,!0),window.addEventListener(`pointerup`,_,!0)}updateMasterChartCursor(e){let t=e.target,{offsetX:n,offsetY:r}=hh(this.env,e,t?.getBoundingClientRect());if(!(!t||!this.isMasterChartAllowed)&&this.mode===void 0){if(!this.masterChart?.chartArea){t.style.cursor=`default`;return}let{left:e,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.lowerBound??e,c=this.upperBound??i;r<a||r>o?t.style.cursor=`default`:Math.abs(s-n)<5||Math.abs(c-n)<5?t.style.cursor=`ew-resize`:s<n&&n<c&&(s!==e||c!==i)?t.style.cursor=`grab`:t.style.cursor=`crosshair`}}onMasterChartMouseLeave(e){let t=e.target;!t||!this.isMasterChartAllowed||(t.style.cursor=`default`)}onMasterChartDoubleClick(e){this.mode=void 0;let t=hh(this.env,e,this.masterChartCanvas()?.getBoundingClientRect()),n=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;let{left:r,right:i,top:a,bottom:o}=this.masterChart.chartArea,s=this.upperBound??i,c=this.lowerBound??r;if(s<c&&([s,c]=[c,s]),n<r-5||n>i+5||t.offsetY<a||t.offsetY>o)return;e.preventDefault(),e.stopPropagation();let{min:l,max:u}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x,d=this.store.originalAxisLimits[this.chartId].x;if(d){if(Math.abs(n-c)<5)l=d.min;else if(Math.abs(n-s)<5)u=d.max;else if(c<n&&n<s)l=d.min,u=d.max;else return;this.updateAxisLimits(l,u)}}};let ug=new O;ug.add(`animatedBackgroundColorChange`,{id:`animatedBackgroundColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,n,r){let i=Xf([{value:0,color:n.style.fillColor||`#ffffff`},{value:1,color:r.style.fillColor||`#ffffff`}]);t.style.fillColor=i(dg[this.easingFn](e))}}),ug.add(`animatedTextColorChange`,{id:`animatedTextColorChange`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,n,r){let i=Xf([{value:0,color:n.style.textColor||`#000000`},{value:1,color:r.style.textColor||`#000000`}]);t.style.textColor=i(dg[this.easingFn](e))}}),ug.add(`animatedDataBar`,{id:`animatedDataBar`,easingFn:`easeOutCubic`,hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,n,r){let i=n?.dataBarFill?.percentage||0,a=r?.dataBarFill?.percentage||0,o=dg[this.easingFn](e),s=i+(a-i)*o;t.dataBarFill={color:r.dataBarFill?.color||n.dataBarFill?.color||`#ffffff`,percentage:s}}}),ug.add(`textFadeIn`,{id:`textFadeIn`,easingFn:`easeInCubic`,hasAnimation:(e,t)=>{let n=e?.content?.textLines?.join(`
20
20
  `),r=t?.content?.textLines?.join(`
@@ -35,7 +35,7 @@ stores.inject(MyMetaStore, storeInstance);
35
35
  <Default Extension="${e}" ContentType="${t}" />
36
36
  `}function Y(e){return new B_(e.join(`
37
37
  `))}function X(e,...t){let n=[e[0]];for(let r=0;r<t.length;r++){let i=t[r]instanceof B_?t[r]:ox(t[r]);n.push(i+e[r+1])}return new B_(Gt(n))}function fx(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,`$1`)}function px(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`$1NAMESPACE$2NAMESPACE$3`)}function mx(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`NAMESPACE$1NAMESPACE$2`)}var hx=class{value;constructor(e){this.value=e}asString(){return xy(String(this.value))}asBool(){return this.value===`true`?!0:this.value===`false`?!1:!!Number(this.value)}asNum(){return Number(this.value)}},gx=class{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,n){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=n,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:`Relationship`},e=>({id:this.extractAttr(e,`Id`,{required:!0}).asString(),target:this.extractAttr(e,`Target`,{required:!0}).asString(),type:this.extractAttr(e,`Type`,{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>e!==`images`).map(([e,t])=>t).flat().filter(w)}mapOnElements(e,t){let n=[],r=this.currentFile,i;if(i=e.children?this.querySelector(e.parent,e.query)?.children||[]:this.querySelectorAll(e.parent,e.query),i)for(let e of i)try{n.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=r,n}catchErrorOnElement(e,t){let n=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([n,e.message].join(`
38
- `))}extractAttr(e,t,n){let r=e.attributes[t];r||this.handleMissingValue(e,`attribute "${t}"`,n);let i=r?.value?r.value:n?.default;return i===void 0?void 0:new hx(i)}extractTextContent(e,t){if(t?.default!==void 0&&typeof t.default!=`string`)throw Error(`extractTextContent default value should be a string`);let n=e?.attributes[`xml:space`]?.value===`preserve`,r=e?.textContent;return(!e||r===null)&&this.handleMissingValue(e,`text content`,t),r&&=n?r:r.trim(),r?xy(r):t?.default}extractChildAttr(e,t,n,r){let i;i=typeof t==`number`?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,typeof t==`number`?`child at index ${t}`:`child <${t}>`,r);let a=i?this.extractAttr(i,n,r)?.asString():r?.default;return a===void 0?void 0:new hx(a)}extractChildTextContent(e,t,n){if(n?.default!==void 0&&typeof n.default!=`string`)throw Error(`extractTextContent default value should be a string`);let r=this.querySelector(e,t);return r||this.handleMissingValue(e,`child <${t}>`,n),r?this.extractTextContent(r,n):n?.default}handleMissingValue(e,t,n){if(n?.required)if(n?.default!==void 0)this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${n.default}`);else throw Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`)}extractColor(e,t,n){if(!e)return n?{rgb:n}:void 0;let r=this.extractAttr(e,`theme`)?.asString(),i;if(r!==void 0){if(!t||!t.clrScheme)throw Error(`Color referencing a theme but no theme was provided`);i=this.getThemeColor(r,t.clrScheme)}else i=this.extractAttr(e,`rgb`)?.asString(),i=i===`FF000000`?void 0:i;return{rgb:i||n,auto:this.extractAttr(e,`auto`)?.asBool(),indexed:this.extractAttr(e,`indexed`)?.asNum(),tint:this.extractAttr(e,`tint`)?.asNum()}}getTargetXmlFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!n||!n.file)throw Error(`Cannot find target file`);return n}getTargetImageFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!n)throw Error(`Cannot find target file`);return n}querySelector(e,t){let n=mx(t);return e.querySelector(n)}querySelectorAll(e,t){let n=mx(t);return e.querySelectorAll(n)}getThemeColor(e,t){switch(e){case`0`:return`FFFFFF`;case`1`:return`000000`;case`2`:return t[3].value;case`3`:return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,``)}},_x=class extends gx{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`externalBook`},e=>({rId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:`sheetName`},e=>this.extractAttr(e,`val`,{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:`sheetData`},e=>{let t=this.mapOnElements({parent:e,query:`cell`},e=>({xc:this.extractAttr(e,`r`,{required:!0}).asString(),value:this.extractChildTextContent(e,`v`,{required:!0})})),n={};for(let e of t)n[e.xc]=e.value;return{sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asNum(),data:n}})}},vx=class extends gx{getTheme(){return{clrScheme:this.mapOnElements({query:`a:clrScheme`,parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,`val`,{required:!0,default:$f}).asString(),lastClr:this.extractChildAttr(e,0,`lastClr`,{default:$f}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`si`},e=>this.mapOnElements({parent:e,query:`t`},e=>this.extractTextContent(e)||``).join(``))}getNamedRanges(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`definedNames definedName`},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),value:this.extractTextContent(e)||``}))}},yx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractConditionalFormattings(){let e=this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > conditionalFormatting`},e=>({sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),pivot:this.extractAttr(e,`pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:`extLst x14:conditionalFormatting`},e=>({sqref:this.extractChildTextContent(e,`xm:sqref`,{required:!0}).split(` `),pivot:this.extractAttr(e,`xm:pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:`cfRule, x14:cfRule`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),priority:this.extractAttr(e,`priority`,{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,`dxfId`)?.asNum(),stopIfTrue:this.extractAttr(e,`stopIfTrue`)?.asBool(),aboveAverage:this.extractAttr(e,`aboveAverage`)?.asBool(),percent:this.extractAttr(e,`percent`)?.asBool(),bottom:this.extractAttr(e,`bottom`)?.asBool(),operator:this.extractAttr(e,`operator`)?.asString(),text:this.extractAttr(e,`text`)?.asString(),timePeriod:this.extractAttr(e,`timePeriod`)?.asString(),rank:this.extractAttr(e,`rank`)?.asNum(),stdDev:this.extractAttr(e,`stdDev`)?.asNum(),equalAverage:this.extractAttr(e,`equalAverage`)?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:`formula`},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){let n=this.querySelector(e,`colorScale`);if(n)return{colors:this.mapOnElements({parent:n,query:`color`},e=>this.extractColor(e,t,`ffffff`)),cfvos:this.extractCFVos(n)}}extractCfDataBar(e,t){let n=this.querySelector(e,`dataBar`);if(n)return{color:this.extractColor(n.querySelector(`color`),t,`EFF7FF`),cfvos:this.extractCFVos(n)}}extractCfIconSet(e){let t=this.querySelector(e,`iconSet, x14:iconSet`);if(t)return{iconSet:this.extractAttr(t,`iconSet`,{default:`3TrafficLights1`}).asString(),showValue:this.extractAttr(t,`showValue`,{default:!0}).asBool(),percent:this.extractAttr(t,`percent`,{default:!0}).asBool(),reverse:this.extractAttr(t,`reverse`)?.asBool(),custom:this.extractAttr(t,`custom`)?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){let t=this.mapOnElements({parent:e,query:`cfIcon, x14:cfIcon`},e=>({iconSet:this.extractAttr(e,`iconSet`,{required:!0}).asString(),iconId:this.extractAttr(e,`iconId`,{required:!0}).asNum()}));return t.length===0?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:`cfvo, x14:cfvo`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),gte:this.extractAttr(e,`gte`,{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,`val`)?.asString():this.extractChildTextContent(e,`f, xm:f`)}))}},bx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > dataValidations > dataValidation`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),operator:this.extractAttr(e,`operator`,{default:`between`})?.asString(),sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),errorStyle:this.extractAttr(e,`errorStyle`)?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,`showErrorMessage`)?.asBool(),errorTitle:this.extractAttr(e,`errorTitle`)?.asString(),error:this.extractAttr(e,`error`)?.asString(),showInputMessage:this.extractAttr(e,`showInputMessage`)?.asBool(),promptTitle:this.extractAttr(e,`promptTitle`)?.asString(),prompt:this.extractAttr(e,`prompt`)?.asString(),allowBlank:this.extractAttr(e,`allowBlank`)?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}},xx=class extends gx{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`c:chartSpace`},e=>{let t=this.getChartType(e);if(!hv[t])throw Error(`Unsupported chart type ${t}`);if(hv[t]===`combo`)return this.extractComboChart(e);let n=this.mapOnElements({parent:e,query:`c:chart > c:title a:t`},e=>e.textContent||``).join(``),r=this.extractTitleStyle(e,`c:chart > c:title a:p a:pPr a:defRPr`),i=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),a=this.extractChildAttr(e,`c:barDir`,`val`,{default:`col`}).asString(),o=this.extractChildAttr(e,`c:holeSize`,`val`,{default:`0`}).asNum(),s=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:n,...r},type:hv[t],axesDesign:this.extractAxesDesign(e),dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:mv[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:i===`stacked`,fontColor:`000000`,horizontal:a===`bar`,isDoughnut:o>0,pieHolePercentage:o,showValues:s}})[0]}extractLabelRange(e,t){return e===`scatterChart`?this.extractChildTextContent(t,`c:ser c:strRef c:f`)||this.extractChildTextContent(t,`c:ser c:numRef c:f`):this.extractChildTextContent(t,`c:ser c:cat c:f`)}extractComboChart(e){let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``),n=this.extractTitleStyle(e,`c:chart > c:title a:p a:pPr a:defRPr`),r=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),i=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:t,...n},type:`combo`,axesDesign:this.extractAxesDesign(e),dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,`c:barChart`),`comboChart`),...this.extractChartDatasets(this.querySelectorAll(e,`c:lineChart`),`comboChart`)],labelRange:this.extractChildTextContent(e,`c:ser c:cat c:f`),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:mv[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:r===`stacked`,fontColor:`000000`,showValues:i}}extractTitleStyle(e,t){let n=this.querySelector(e,t);if(!n)return{};let r=n.getAttribute(`b`),i=r===`1`||r===`true`?!0:void 0,a=n.getAttribute(`i`),o=a===`1`||a===`true`?!0:void 0,s=n.getAttribute(`sz`);return{bold:i,italic:o,fontSize:s?Math.round(parseInt(s)/100):void 0,color:this.extractDrawingFillColor(n)}}extractDrawingFillColor(e){let t=this.querySelector(e,`a:solidFill a:srgbClr`);if(t){let e=t.getAttribute(`val`);return e&&df(e)?uf(e):void 0}let n=this.querySelector(e,`a:solidFill a:schemeClr`);if(n){let e=n.getAttribute(`val`);if(e)return this.resolveSchemeColor(e)}}resolveSchemeColor(e){let t=this.xlsxFileStructure.theme;if(!t)return;let n=this.querySelector(t.file.xml,`a:clrScheme a:${e}`);if(!n)return;let r=this.querySelector(n,`a:srgbClr`);if(r){let e=r.getAttribute(`val`);return e&&df(e)?uf(e):void 0}let i=this.querySelector(n,`a:sysClr`);if(i){let e=i.getAttribute(`lastClr`);return e&&df(e)?uf(e):void 0}}extractAxisTitleDesign(e){if(e===null)return;let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``);if(t)return{text:t,...this.extractTitleStyle(e,`c:title a:p a:pPr a:defRPr`)}}extractAxesDesign(e){let t=this.querySelector(e,`c:catAx`),n=this.querySelector(e,`c:valAx`),r=t?this.extractChildAttr(t,`c:axPos`,`val`)?.asString():void 0,i=r===`l`||r===`r`,a=i?n:t,o=i?t:n,s=this.extractAxisTitleDesign(a),c=this.extractAxisTitleDesign(o);if(!s&&!c)return;let l={};return s&&(l.x={title:s}),c&&(l.y={title:c}),l}extractChartDatasets(e,t){return Array.from(e).map(e=>t===`scatterChart`?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}let r=this.querySelectorAll(e,`c:spPr a:solidFill`),i=r.length?this.querySelector(r[0],`a:srgbClr`):void 0,a=i?i.getAttribute(`val`):void 0;return{label:t,range:this.extractChildTextContent(e,`c:val c:f`,{required:!0}),backgroundColor:a&&df(a)?`${uf(a)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){let t=this.querySelector(e,`c:trendline`);if(!t)return;let n=this.extractChildAttr(t,`c:trendlineType`,`val`),r=this.extractChildAttr(t,`a:solidFill a:srgbClr`,`val`);return{type:n?n.asString():void 0,order:this.extractChildAttr(t,`c:order`,`val`)?.asNum(),window:this.extractChildAttr(t,`c:period`,`val`)?.asNum(),color:r&&df(r.asString())?`${uf(r.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.querySelectorAll(e,`c:spPr a:solidFill a:srgbClr`),r=n.length?n[0].getAttribute(`val`):void 0,i=this.extractChildTextContent(e,`c:tx c:f`);if(i)t={reference:i};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}return{label:t,range:this.extractChildTextContent(e,`c:yVal c:f`,{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:r&&df(r)?`${uf(r)}`:void 0}})}getChartType(e){let t=this.querySelector(e,`c:plotArea`);if(!t)throw Error(`Missing plot area in the chart definition.`);let n;for(let e of t.children){let t=fx(e.tagName);V_.some(e=>e===t)&&(n?n!==t&&(n=`comboChart`):n=t)}if(n)return n;throw Error(`Unknown chart type`)}};let Sx=`oneCellAnchor`,Cx=`twoCellAnchor`;var wx=class extends gx{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`xdr:wsDr`,children:!0},e=>{let t=fx(e.tagName),n=this.extractFigureAnchorsByType(e,t),r=this.querySelector(e,`c:chart`),i=this.querySelector(e,`a:blip`);if(!r&&!i)throw Error(`Only chart and image figures are currently supported.`);return{anchors:n,data:r?this.extractChart(r):this.extractImage(e),figureSize:t===Sx?this.extractFigureSizeFromSizeTag(e,`xdr:ext`):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case Sx:return[this.extractFigureAnchor(`xdr:from`,e)];case Cx:return[this.extractFigureAnchor(`xdr:from`,e),this.extractFigureAnchor(`xdr:to`,e)];default:throw Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){let n=this.querySelector(e,t);if(!n)throw Error(`Missing size element '${t}'`);return{cx:this.extractAttr(n,`cx`,{required:!0}).asNum(),cy:this.extractAttr(n,`cy`,{required:!0}).asNum()}}extractFigureAnchor(e,t){let n=this.querySelector(t,e);if(!n)throw Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(n,`xdr:col`,{required:!0})),colOffset:Number(this.extractChildTextContent(n,`xdr:colOff`,{required:!0})),row:Number(this.extractChildTextContent(n,`xdr:row`,{required:!0})),rowOffset:Number(this.extractChildTextContent(n,`xdr:rowOff`,{required:!0}))}}extractChart(e){let t=this.extractAttr(e,`r:id`,{required:!0}).asString(),n=new xx(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw Error(`Unable to extract chart definition`);return n}extractImage(e){let t=this.querySelector(e,`a:blip`),n=this.extractAttr(t,`r:embed`,{required:!0}).asString(),r=this.getTargetImageFile(this.relationships[n]);if(!r)throw Error(`Unable to extract image`);let i=r.fileName.split(`.`).at(-1),a=fx(e.tagName),o=a===Cx?this.querySelector(e,`a:xfrm`):e,s=a===Cx?`a:ext`:`xdr:ext`,c=this.extractFigureSizeFromSizeTag(o,s);return{imageSrc:r.imageSrc,mimetype:i?Sv[i]:void 0,size:c}}},Tx=class extends gx{getPivotTable(){return this.mapOnElements({query:`:root`,parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,`rowGrandTotals`,{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:`location`,parent:e},e=>({ref:this.extractAttr(e,`ref`,{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,`firstHeaderRow`,{required:!0}).asNum(),firstDataRow:this.extractAttr(e,`firstDataRow`,{required:!0}).asNum(),firstDataCol:this.extractAttr(e,`firstDataCol`,{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:`pivotTableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),showRowHeaders:this.extractAttr(e,`showRowHeaders`,{required:!0}).asBool(),showColHeaders:this.extractAttr(e,`showColHeaders`,{required:!0}).asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`,{required:!0}).asBool(),showColStripes:this.extractAttr(e,`showColStripes`,{required:!0}).asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool()}))[0]}},Ex=class extends gx{getTable(){return this.mapOnElements({query:`table`,parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,`displayName`,{required:!0}).asString(),name:this.extractAttr(e,`name`)?.asString(),id:this.extractAttr(e,`id`,{required:!0}).asString(),ref:this.extractAttr(e,`ref`,{required:!0}).asString(),headerRowCount:this.extractAttr(e,`headerRowCount`,{default:1}).asNum(),totalsRowCount:this.extractAttr(e,`totalsRowCount`,{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:`tableColumn`,parent:e},e=>({id:this.extractAttr(e,`id`,{required:!0}).asString(),name:this.extractAttr(e,`name`,{required:!0}).asString(),colFormula:this.extractChildTextContent(e,`calculatedColumnFormula`)}))}extractTableStyleInfo(e){return this.mapOnElements({query:`tableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`)?.asString(),showFirstColumn:this.extractAttr(e,`showFirstColumn`)?.asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`)?.asBool(),showColumnStripes:this.extractAttr(e,`showColumnStripes`)?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:`autoFilter`,parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,`ref`,{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:`tableColumn`,parent:e},t=>({colId:this.extractAttr(e,`colId`,{required:!0}).asNum(),hiddenButton:this.extractAttr(e,`hiddenButton`,{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:`filter`,parent:e},e=>({val:this.extractAttr(e,`val`,{required:!0}).asString()}))}},Dx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}getSheet(){return this.mapOnElements({query:`worksheet`,parent:this.rootFile.file.xml},e=>{let t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:t.state===`visible`,isLocked:this.extractProtection(e)}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:`sheetView`},e=>{let t=this.querySelector(e,`pane`);return{tabSelected:this.extractAttr(e,`tabSelected`,{default:!1}).asBool(),showFormulas:this.extractAttr(e,`showFormulas`,{default:!1}).asBool(),showGridLines:this.extractAttr(e,`showGridLines`,{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,`showRowColHeaders`,{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,`xSplit`,{default:0}).asNum():0,ySplit:t?this.extractAttr(t,`ySplit`,{default:0}).asNum():0}}})}extractSheetName(){let e=yy(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,`sheet`))if(e.attributes[`r:id`].value===t)return e.attributes.name.value;throw Error(`Missing sheet name`)}getSheetWorkbookInfo(){let e=yy(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,n=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:`sheet`},e=>({relationshipId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asString(),sheetName:this.extractAttr(e,`name`,{required:!0}).asString(),state:this.extractAttr(e,`state`,{default:`visible`}).asString()})).find(e=>e.relationshipId===t);if(!n)throw Error(`Cannot find corresponding workbook sheet`);return n}extractConditionalFormats(){return new yx(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new bx(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:`drawing`},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new wx(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:`tablePart`,parent:e},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new Ex(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith(`pivotTable`)).map(e=>new Tx(this.getTargetXmlFile(e),this.xlsxFileStructure,this.warningManager).getPivotTable())}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:`mergeCell`},e=>this.extractAttr(e,`ref`,{required:!0}).asString())}extractSheetFormat(e){let t=this.querySelector(e,`sheetFormatPr`);if(t)return{defaultColWidth:this.extractAttr(t,`defaultColWidth`,{default:`8.43`}).asNum(),defaultRowHeight:this.extractAttr(t,`defaultRowHeight`,{default:`12.75`}).asNum()}}extractSheetProperties(e){let t=this.querySelector(e,`sheetPr`);if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,`tabColor`),this.theme)}}extractSheetOutlineProperties(e){let t=this.querySelector(e,`outlinePr`);if(t)return{summaryBelow:this.extractAttr(t,`summaryBelow`,{default:!0}).asBool(),summaryRight:this.extractAttr(t,`summaryRight`,{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:`cols col`},e=>({width:this.extractAttr(e,`width`)?.asNum(),customWidth:this.extractAttr(e,`customWidth`)?.asBool(),bestFit:this.extractAttr(e,`bestFit`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),min:this.extractAttr(e,`min`,{required:!0})?.asNum(),max:this.extractAttr(e,`max`,{required:!0})?.asNum(),styleIndex:this.extractAttr(e,`style`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractRows(e){let t=new Set;return this.mapOnElements({parent:e,query:`sheetData row`},e=>({index:this.extractAttr(e,`r`,{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,`ht`)?.asNum(),customHeight:this.extractAttr(e,`customHeight`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),styleIndex:this.extractAttr(e,`s`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:`c`},e=>{let n=this.extractAttr(e,`r`,{required:!0})?.asString(),r=this.extractCellFormula(e);if(r?.ref&&r.sharedIndex===void 0){let e=Wn(r.ref);for(let{col:r,row:i}of dr(e)){let e=E(r,i);e!==n&&t.add(e)}}let i=t.has(n);return{xc:n,styleIndex:this.extractAttr(e,`s`)?.asNum(),type:av[this.extractAttr(e,`t`,{default:`n`})?.asString()],value:i?void 0:this.extractChildTextContent(e,`v`)??void 0,formula:i?void 0:r}})}extractCellFormula(e){let t=this.querySelector(e,`f`);if(!t)return;let n=this.extractTextContent(t),r=this.extractAttr(t,`si`)?.asNum(),i=this.extractAttr(t,`ref`)?.asString();if(!((n===void 0||n.trim()===``)&&r===void 0))return{content:n,sharedIndex:r,ref:i}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:`hyperlink`},e=>{let t=this.extractAttr(e,`r:id`)?.asString();return{xc:this.extractAttr(e,`ref`,{required:!0})?.asString(),location:this.extractAttr(e,`location`)?.asString(),display:this.extractAttr(e,`display`)?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){let t=this.querySelectorAll(e,`f[si][ref]`),n={};for(let e of t){let t=this.extractAttr(e,`si`,{required:!0}).asNum();n[t]=this.extractTextContent(e,{required:!0})}let r=[];for(let e=0;e<Object.keys(n).length;e++)n[e]?r.push(n[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),r.push(``));return r}extractProtection(e){let t=this.querySelector(e,`sheetProtection`);return t?this.extractAttr(t,`sheet`,{default:!1}).asBool():!1}},Ox=class extends gx{theme;constructor(e,t,n){super(e.styles,e,t),this.theme=n}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`numFmt`},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,`numFmtId`,{required:!0}).asNum(),format:this.extractAttr(e,`formatCode`,{required:!0,default:``}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`font`},e=>this.extractFont(e))}extractFont(e){let t=this.extractChildAttr(e,`name`,`val`,{default:`Arial`}).asString(),n=this.extractChildAttr(e,`sz`,`val`,{default:Je.toString()}).asNum(),r=this.extractColor(this.querySelector(e,`color`),this.theme),i=this.querySelector(e,`i`)||void 0,a=i&&i.attributes.val?.value!==`0`,o=this.querySelector(e,`b`)||void 0,s=o&&o.attributes.val?.value!==`0`,c=this.querySelector(e,`strike`)||void 0,l=c&&c.attributes.val?.value!==`0`,u=this.querySelector(e,`u`)||void 0;return{name:t,size:n,color:r,italic:a,bold:s,underline:u&&u.attributes.val?.value!==`none`,strike:l}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`fill`},e=>this.extractFill(e))}extractFill(e){let t=e.children[0];return t.tagName===`patternFill`?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,`bgColor`),this.theme),fgColor:this.extractColor(this.querySelector(t,`fgColor`),this.theme)}:{patternType:`solid`,fgColor:this.extractColor(this.querySelectorAll(t,`color`)[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`border`},e=>this.extractBorder(e))}extractBorder(e){let t={left:this.extractSingleBorder(e,`left`,this.theme),right:this.extractSingleBorder(e,`right`,this.theme),top:this.extractSingleBorder(e,`top`,this.theme),bottom:this.extractSingleBorder(e,`bottom`,this.theme),diagonal:this.extractSingleBorder(e,`diagonal`,this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,`diagonalUp`)?.asBool(),t.diagonalDown=this.extractAttr(e,`diagonalDown`)?.asBool()),t}extractSingleBorder(e,t,n){let r=this.querySelector(e,t);if(!(!r||!r.attributes.style))return{style:this.extractAttr(r,`style`,{required:!0,default:`thin`}).asString(),color:this.extractColor(r.children[0],n,`000000`)}}extractAlignment(e){return{horizontal:this.extractAttr(e,`horizontal`,{default:`general`}).asString(),vertical:this.extractAttr(e,`vertical`,{default:`bottom`}).asString(),textRotation:this.extractAttr(e,`textRotation`)?.asNum(),wrapText:this.extractAttr(e,`wrapText`)?.asBool(),indent:this.extractAttr(e,`indent`)?.asNum(),relativeIndent:this.extractAttr(e,`relativeIndent`)?.asNum(),justifyLastLine:this.extractAttr(e,`justifyLastLine`)?.asBool(),shrinkToFit:this.extractAttr(e,`shrinkToFit`)?.asBool(),readingOrder:this.extractAttr(e,`readingOrder`)?.asNum()}}getDxfs(){return this.mapOnElements({query:`dxf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`font`),n=this.querySelector(e,`fill`),r=this.querySelector(e,`border`),i=this.querySelector(e,`numFmt`),a=this.querySelector(e,`alignment`);return{font:t?this.extractFont(t):void 0,fill:n?this.extractFill(n):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:a?this.extractAlignment(a):void 0,border:r?this.extractBorder(r):void 0}})}getStyles(){return this.mapOnElements({query:`cellXfs xf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`alignment`);return{fontId:this.extractAttr(e,`fontId`,{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,`fillId`,{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,`borderId`,{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,`numFmtId`,{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}};function kx(e,t){return Ax(jx(e,t),t)}function Ax(e,t){let n=[];for(let r of e){let e=Mx(r,t);n.push({file:{fileName:r,xml:t[r]},rels:e?{fileName:e,xml:t[e]}:void 0})}return n}function jx(e,t){let n=t[`[Content_Types].xml`].querySelectorAll(`Override[ContentType="${e}"]`),r=[];for(let e of n){let t=e?.attributes.PartName.value;r.push(t.substring(1))}return r}function Mx(e,t){if(e===`[Content_Types].xml`)return`_rels/.rels`;let n=``,r=e.split(`/`);for(let e=0;e<r.length-1;e++)n+=r[e]+`/`;return n+=`_rels/`,n+=r[r.length-1]+`.rels`,t[n]||(n=void 0),n}var Nx=class{warningManager;xmls;images;constructor(e){this.warningManager=new Yv,this.xmls={},this.images=[];for(let t of Object.keys(e))if(t.endsWith(`.xml`)||t.endsWith(`.rels`)){let n=px(e[t]);this.xmls[t]=sx(new B_(n))}else t.includes(`media/image`)&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){let e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){let e=this.buildXlsxFileStructure(),t=e.theme?new vx(e.theme,e,this.warningManager).getTheme():void 0,n=e.sharedStrings?new vx(e.sharedStrings,e,this.warningManager).getSharedStrings():[],r=new vx(e.workbook,e,this.warningManager).getNamedRanges(),i=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(n=>new Dx(n,e,this.warningManager,t).getSheet()),a=e.externalLinks.map(t=>new _x(t,e,this.warningManager).getExternalBook()),o=new Ox(e,this.warningManager,t);return{fonts:o.getFonts(),fills:o.getFills(),borders:o.getBorders(),dxfs:o.getDxfs(),numFmts:o.getNumFormats(),styles:o.getStyles(),sheets:i,sharedStrings:n,externalBooks:a,chartIds:[],imageIds:[],namedRanges:r}}buildXlsxFileStructure(){let e={sheets:kx(ip.sheet,this.xmls),workbook:kx(ip.workbook,this.xmls)[0]||kx(ip.macroEnabledWorkbook,this.xmls)[0]||kx(ip.templateWorkbook,this.xmls)[0]||kx(ip.macroEnabledTemplateWorkbook,this.xmls)[0]||kx(ip.excelAddInWorkbook,this.xmls)[0],styles:kx(ip.styles,this.xmls)[0],sharedStrings:kx(ip.sharedStrings,this.xmls)[0],theme:kx(ip.themes,this.xmls)[0],charts:kx(ip.chart,this.xmls),figures:kx(ip.drawing,this.xmls),tables:kx(ip.table,this.xmls),pivots:kx(ip.pivot,this.xmls),externalLinks:kx(ip.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(j(`Cannot find workbook relations file`));return e}convertImportedData(e){let t={version:`18.4.2`,sheets:xb(e,this.warningManager),styles:Fy(e,this.warningManager),formats:Ly(e,this.warningManager),borders:Ny(e,this.warningManager),namedRanges:K_(e,this.warningManager),revisionId:Ze};return Xb(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Qt(e.styles[t])}),t}};function Px(e){let t=!1,n=!0;return Co(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function Fx(e){let t=!1,n=!1;return Co(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function Ix(e,t){return go(e,(e,t)=>e+t,0,t)}function Lx(e){return ho(e,(e,t)=>Po(t)?e.add(t?.value):e,new Set).size}function Rx(e,t){if(!e)throw new N(t)}function zx(e,t=j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Wa(t)}function Bx(e){return e.length===1||e[0].length===1}function Vx(...e){if(e.every(gt)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function Hx(e){return e.length===e[0].length}let Ux=e=>j(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function Wx(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function Gx(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=Wx(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){Kx(i,e,a),Kx(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function Kx(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function qx(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function Jx(e){if(!gt(e))return e;if(!Yx(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Yx(e){return e.length===1&&e[0].length===1}function Xx(e){return gt(e)&&!Yx(e)}function Zx(...e){let t=e[0].length;e.forEach((e,n)=>Rx(e.length===t,j(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Qx(e,t){let n=0,r=go(e,(e,t)=>(n+=1,e+t),0,t);return zx(n),r/n}function $x(e,t){let n=[];po(e,e=>{n.push(e.value)},t),n.sort((e,t)=>e-t);let r=n.length;if(r===0)return;let i=Math.floor(r/2);return r%2==0?(n[i-1]+n[i])/2:n[i]}function eS(e,t){let n=0;for(let r of e)if(gt(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!Ja(e)&&(typeof e!=`string`||Ta(e,t)||Yi(e,t))&&(n+=1)}return n}function tS(e){return ho(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function nS(e,t){let n={value:-1/0};return po(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function rS(e,t){let n={value:1/0};return po(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function iS(e,t,n){let r=e[0].length?e:[C(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?xo(a):a,{_X:r,_newX:a}}function aS(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=iS(e,t,[[]]);o=o.length===a?xo(o):o.slice(),Zx(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=xo(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=sS(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=Gx(qx(p,xo(p)));if(h===void 0)throw new N(j(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),ee=_/(_+g),y=_/s/(g/c),b=[];for(let e=0;e<s;e++)b.push(v*Math.sqrt(h[e][e]));if(n){let e=qx(h,[d]),t=qx(xo([d]),e);b.push(v*Math.sqrt(t[0][0]+1/i.length))}let te=[[m[0][0],b[0],ee,y,_],[m[1][0],b[1],v,c,g]];for(let e=2;e<s;e++)te.push([m[e][0],b[e],``,``,``]);return n?te.push([m[s][0],b[s],``,``,``]):te.push([0,``,``,``,``]),te}function oS(e,t,n,r){Zx(t,e),Rx(n>=1,j(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>C(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=sS(a,i);return r||o.push([0]),o}function sS(e,t){let{inverted:n}=Gx(qx(e,xo(e)));if(n===void 0)throw new N(j(`Matrix is not invertible`));return xo(qx(n,qx(e,t)))}function cS(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function lS(e){return e.map(e=>e.map(e=>Math.exp(e)))}function uS(e){return e.map(e=>e.map(e=>Math.log(e)))}function dS(e,t,n,r){let{_X:i,_newX:a}=iS(t,e,n),o=aS(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:xo(c)}function fS(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}function pS(e){let[t,n]=e.split(`/`);return Number(n)*100+Number(t)}let mS=new O;function hS(e){return mS.get(e)}let gS={normalizeFunctionValue(e){return P(e,R)},toValueAndFormat(e,t){return{value:P(e,R),format:`dd mmm yyyy`}},toFunctionValue(e){let t=co(e,R);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},_S={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>31)throw new N(j(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},vS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>7)throw new N(j(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:ps[(e-1+(t||R).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},yS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>53)throw new N(j(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},bS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>12)throw new N(j(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:fs[P(e,R)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},xS={normalizeFunctionValue(e){return z(P(e,R),{locale:R,format:`mm/yyyy`})},toValueAndFormat(e){return{value:P(e,R),format:`mmmm yyyy`}},toFunctionValue(e){let t=co(e,R);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`},toComparableValue(e){return pS(e)}},SS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>4)throw new N(j(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:j(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},CS={normalizeFunctionValue(e){let t=P(e,R);return t>3e3?co(t,R).getFullYear():t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},wS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>23)throw new N(j(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:j(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},TS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>59)throw new N(j(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},ES={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>59)throw new N(j(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function DS(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:j(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)},toComparableValue(t){if(t!==null)return e.toComparableValue?.(t)}}}mS.add(`day`,DS(gS)).add(`year`,DS(CS)).add(`day_of_month`,DS(_S)).add(`iso_week_number`,DS(yS)).add(`month_number`,DS(bS)).add(`month`,DS(xS)).add(`quarter_number`,DS(SS)).add(`day_of_week`,DS(vS)).add(`hour_number`,DS(wS)).add(`minute_number`,DS(TS)).add(`second_number`,DS(ES));let OS={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:`None`,bandedRows:!1,bandedColumns:!1,hasFilters:!1,tabularForm:!1},kS={count:j(`Count`),count_distinct:j(`Count Distinct`),bool_and:j(`Boolean And`),bool_or:j(`Boolean Or`),max:j(`Maximum`),min:j(`Minimum`),avg:j(`Average`),sum:j(`Sum`)},AS=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],jS={integer:AS,char:AS,datetime:AS,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},MS={};for(let e in jS){MS[e]={};for(let t of jS[e])MS[e][t]=kS[t]}let NS={count:e=>({value:tS([e]),format:`0`}),count_distinct:e=>({value:Lx([e]),format:`0`}),bool_and:e=>({value:Px([e]).result}),bool_or:e=>({value:Fx([e]).result}),max:(e,t)=>nS([e],t),min:(e,t)=>rS([e],t),avg:(e,t)=>({value:Qx([e],t),format:qa(e)}),sum:(e,t)=>({value:Ix([e],t),format:qa(e)})};function PS(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let FS={year:j(`Year`),quarter:j(`Quarter & Year`),month:j(`Month & Year`),week:j(`Week & Year`),day:j(`Day`),quarter_number:j(`Quarter`),month_number:j(`Month`),iso_week_number:j(`Week`),day_of_month:j(`Day of Month`),day_of_week:j(`Day of Week`),hour_number:j(`Hour`),minute_number:j(`Minute`),second_number:j(`Second`)},IS=[`date`,`datetime`];function LS(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function RS(e){return IS.includes(e.type)}function zS(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=LS(e),a=WS(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function BS(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function VS(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${zS(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${zS(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${zS(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function HS(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(Ja(n))return n;if(e.type===`custom`)return lo(t)??null;let r=typeof t==`boolean`?F(t).toLocaleLowerCase():F(t);if(r===`null`)return null;if(!KS.contains(e.type))throw new N(j(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:KS.get(e.type)(r,e.granularity)}function US(e,t){return hS(t??`month`).normalizeFunctionValue(e)}function WS(e,t){return e===null?`"null"`:qS.contains(t.type)?qS.get(t.type)(e,t.granularity):`"${e}"`}function GS(e,t){return hS(t??`month`).toFunctionValue(e)}let KS=new O;KS.add(`date`,US).add(`datetime`,US).add(`integer`,e=>P(e,R)).add(`boolean`,e=>I(e)).add(`char`,e=>F(e)).add(`custom`,e=>e);let qS=new O;qS.add(`date`,GS).add(`datetime`,GS).add(`integer`,e=>`${P(e,R)}`).add(`boolean`,e=>I(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${F(e).replace(/"/g,`\\"`)}"`).add(`custom`,e=>typeof e==`string`?`"${e}"`:String(e));function JS(e){return e.displayName+(e.granularity?` (${FS[e.granularity]})`:``)}function YS(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function XS(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}function ZS(e,t){return vn(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function QS(e,t){return vn(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(w),{compute:(e,t)=>`${e}${t}`,start:2})}function $S(e,t){let n={};for(let r of Object.values(e.customFields||{}))t[r.parentField]&&(n[r.name]={type:`custom`,isCustomField:!0,name:r.name,string:r.name,customGroups:r.groups,parentField:r.parentField});return n}function eC(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function tC(e,t,n){let r=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=r.findIndex(e=>e.fieldName===t);return i===-1||r.some(e=>e.fieldName===n)||r.splice(i,0,{fieldName:n}),e}function nC(e,t,n){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:QS(t.string,n),groups:[]}}function rC(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>T(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}function iC(e,t,n,r,i,a,o){let s=e.style;return{numberOfRows:t===void 0?s?.numberOfRows??OS.numberOfRows:P(t,o),numberOfColumns:i===void 0?s?.numberOfColumns??OS.numberOfColumns:P(i,o),displayTotals:n===void 0?s?.displayTotals??OS.displayTotals:I(n),displayColumnHeaders:r===void 0?s?.displayColumnHeaders??OS.displayColumnHeaders:I(r),displayMeasuresRow:a===void 0?s?.displayMeasuresRow??OS.displayMeasuresRow:I(a),tableStyleId:s?.tableStyleId||OS.tableStyleId,bandedRows:s?.bandedRows??OS.bandedRows,bandedColumns:s?.bandedColumns??OS.bandedColumns,hasFilters:s?.hasFilters??OS.hasFilters,tabularForm:s?.tabularForm??OS.tabularForm}}function aC(e,t=`>`){let n=e.indexOf(t),r=e.lastIndexOf(t);return!e||!n||n===r?e:`${e.slice(0,n+1)} … ${e.slice(r)}`}function oC(e,t,n){return n.map(n=>{if(n.id===e.id)return t;if(!n.computedBy||e.id===t.id)return n;let r=fu(n.computedBy.formula,e.id,t.id);return{...n,computedBy:{...n.computedBy,formula:r}}})}let sC=[`line`,`bar`,`pie`,`scorecard`,`gauge`,`scatter`,`bubble`,`combo`,`waterfall`,`pyramid`,`radar`,`geo`,`funnel`,`sunburst`,`treemap`,`calendar`];function cC(e){let t=Jf[e];return t===void 0?void 0:{minColor:t[0],midColor:t.length===3?t[1]:void 0,maxColor:t[t.length-1]}}function lC(e){let t=ml(e),n=[];return{text:``.concat(...t.map(e=>{if(e.type===`REFERENCE`&&xc.test(e.value)){let t=e.value.trim();return n.includes(t)||n.push(t),`|${n.indexOf(t)}|`}else return e.value})),dependencies:n}}let uC={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},dC=new O;dC.add(`0.1`,{migrate(e){return e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e}}).add(`0.2`,{migrate(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}}).add(`0.3`,{migrate(e){return e.sheets&&e.activeSheet&&(e.activeSheet=e.sheets.find(t=>t.name===e.activeSheet).id),e}}).add(`0.4`,{migrate(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}}).add(`0.5`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];n.content&&n.content.startsWith(`=`)&&(n.formula=lC(n.content))}return e}}).add(`0.6`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let{dataSets:n,...r}=t.figures[e].data,i=[];for(let e of n)if(e.labelCell){let t=Wn(e.dataRange),n=e.labelCell+`:`+E(t.right,t.bottom);i.push(n)}else i.push(e.dataRange);r.dataSetsHaveTitle=!!n[0].labelCell,r.dataSets=i,t.figures[e].data=r}return e}}).add(`0.7`,{migrate(e){let t=[];for(let n of e.sheets||[]){if(!n.name)continue;let e=n.name,r=vn(Dt(e,`_`),t,{compute:(e,t)=>`${e}${t}`});n.name=r,t.push(r);let i=t=>{if(t===void 0)return t;let n=t.replace(e,r),i=t;for(;i!==n;)i=n,n=i.replace(e,r);return i};for(let e in n.cells){let t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(i))}for(let e of n.figures||[])if(e.tag===`chart`){let t=e.data.dataSets.map(i),n=i(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:n}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(i);for(let t of[`minimum`,`maximum`,`midpoint`,`upperInflectionPoint`,`lowerInflectionPoint`])e.rule[t]?.type===`formula`&&(e.rule[t].value=i(e.rule[t].value))}}return e}}).add(`0.8`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.data.background=`#FFFFFF`,e.data.verticalAxisPosition=`left`,e.data.legendPosition=`top`,e.data.stacked=!1;return e}}).add(`0.9`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];if(n.formula){let{text:e,dependencies:t}=n.formula;for(let[n,r]of Object.entries(t)){let t=`\\|${n}\\|`;e=e.replace(new RegExp(t,`g`),r)}n.content=e,delete n.formula}}return e}}).add(`0.10`,{migrate(e){let t={};for(let n of e.sheets||[])for(let e in n.cells||[]){let r=n.cells[e];r.format&&=Y_(r.format,t)}return e.formats=t,e}}).add(`15.4`,{migrate(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}).add(`15.4.1`,{migrate(e){return fC(e)}}).add(`16.3`,{migrate(e){for(let t in e.borders){let n=e.borders[t];for(let e in n)Array.isArray(n[e])&&(n[e]={style:n[e][0],color:n[e][1]})}return e}}).add(`16.4`,{migrate(e){return e.settings||={},e.settings.locale||(e.settings.locale=R),e}}).add(`16.4.1`,{migrate(e){return fC(e)}}).add(`17.2`,{migrate(e){for(let t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add(`17.3`,{migrate(e){return e.pivots||={},e.pivotNextId||=PS(e.pivots)+1,e}}).add(`17.4`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let n=t.figures[e];`title`in n.data&&typeof n.data.title==`string`&&(n.data.title={text:n.data.title});let r=n.data.type;if(![`line`,`bar`,`pie`,`scatter`,`waterfall`,`combo`].includes(r))continue;let{dataSets:i,...a}=t.figures[e].data;a.dataSets=i.map(e=>({dataRange:e})),t.figures[e].data=a}return e}}).add(`18.0`,{migrate(e){return e}}).add(`18.0.1`,{migrate(e){for(let t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add(`18.0.2`,{migrate(e){let t=e.settings?.locale;return t&&(t.weekStart=uC[t.code]||1),e}}).add(`18.0.3`,{migrate(e){for(let t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(let e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add(`18.0.4`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`gauge`)continue;let t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator=`<=`),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator=`<=`)}return e}}).add(`18.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.tables||[])e.config||={...Mb,hasFilters:!0};return e}}).add(`18.1.1`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells){let n=t.cells[e];n&&(t.cells[e]=n.content)}return e}}).add(`18.2`,{migrate(e){return e}}).add(`18.3`,{migrate(e){if(!e.pivots)return e;for(let t of Object.values(e.pivots))t.sortedColumn&&(t.measures.map(e=>e.id).includes(t.sortedColumn.measure)||delete t.sortedColumn);return e}}).add(`18.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){let t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add(`18.4.1`,{migrate(e){let t={textContains:`containsText`,textNotContains:`notContainsText`,textIs:`isEqualText`,textIsEmail:`isEmail`,textIsLink:`isLink`},n={BeginsWith:`beginsWithText`,Between:`isBetween`,ContainsText:`containsText`,EndsWith:`endsWithText`,Equal:`isEqual`,GreaterThan:`isGreaterThan`,GreaterThanOrEqual:`isGreaterOrEqualTo`,IsEmpty:`isEmpty`,IsNotEmpty:`isNotEmpty`,LessThan:`isLessThan`,LessThanOrEqual:`isLessOrEqualTo`,NotBetween:`isNotBetween`,NotContains:`notContainsText`,NotEqual:`isNotEqual`};for(let t of e.sheets||[])for(let e of t.conditionalFormats||[])e.rule.type===`CellIsRule`&&(e.rule.operator=n[e.rule.operator]);for(let n of e.sheets||[])for(let e of n.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add(`18.4.2`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`scorecard`)continue;let t=e.data;t.baselineDescr&&={text:t.baselineDescr}}return e}}).add(`18.4.3`,{migrate(e){if(!e.pivots)return e;for(let t in e.pivots){let n=e.pivots[t];if(n.sortedColumn){let e=n.measures.find(e=>e.fieldName===n.sortedColumn?.measure);e&&(n.sortedColumn.measure=e.id)}}return e}}).add(`18.5.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.tag===`chart`&&(e.data.chartId=e.id);return e}}).add(`19.1.0`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&e.data.type===`geo`&&`colorScale`in e.data&&typeof e.data.colorScale==`string`&&(e.data.colorScale=cC(e.data.colorScale)),e.tag===`carousel`)for(let t of Object.values(e.data.chartDefinitions)||[])t.type===`geo`&&`colorScale`in t&&typeof t.colorScale==`string`&&(t.colorScale=cC(t.colorScale));return e}}).add(`19.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&!(`humanize`in e.data))e.data.humanize=!0;else if(e.tag===`carousel`)for(let t in e.data.chartDefinitions){let n=e.data.chartDefinitions[t];`humanize`in n||(n.humanize=!0)}return e}}).add(`19.3.2`,{migrate(e){function t(e){if(!(`dataSets`in e))return e;e={...e};let t={};return e.dataSource={type:`range`,dataSetsHaveTitle:e.dataSetsHaveTitle,labelRange:e.labelRange,dataSets:e.dataSets.map((e,n)=>{let r=n.toString(),i=e.dataRange;return delete e.dataRange,Object.keys(e).length&&(t[r]={...e}),{dataRange:i,dataSetId:r}})},delete e.dataSetsHaveTitle,delete e.labelRange,delete e.dataSets,e.dataSetStyles=t,e}for(let n of e.sheets||[])for(let e of n.figures||[])if(e.tag===`chart`&&`dataSets`in e.data)e.data=t(e.data);else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions){let r=e.data.chartDefinitions[n];e.data.chartDefinitions[n]=t(r)}return e}});function fC(e){for(let t of e.sheets||[]){let e=[];for(let n of t.filterTables||[]){let t=Wn(n.range),r=e.findIndex(e=>ir(e,t));r===-1?e.push(t):e[r]=t}t.filterTables=e.map(e=>({range:Yn(e)}))}return e}function pC(){return mC().at(-1)}function mC(){return dC.getKeys().sort(yC)}let hC=`Sheet1`;function gC(e,t){if(!e)return jC();console.debug(`### Loading data ###`);let n=performance.now();if(e[`[Content_Types].xml`]){let n=new Nx(e);if(e=n.convertXlsx(),t)for(let e of n.warningManager.warnings.sort())console.warn(e)}return`version`in e&&(vC(e)&&(e.version=_C[e.version]),e.version!==pC()&&(console.debug(`Migrating data from version`,e.version),e=bC(e))),e=xC(e),console.debug(`Data loaded in`,performance.now()-n,`ms`),console.debug(`###`),e}let _C={25:`18.2`,24:`18.1.1`,23:`18.1`,22:`18.0.4`,21:`18.0.3`,20:`18.0.2`,19:`18.0.1`,18:`18.0`,17:`17.4`,16:`17.3`,15:`17.2`,"14.5":`16.4.1`,14:`16.4`,13:`16.3`,"12.5":`15.4.1`,12:`15.4`,11:`0.10`,10:`0.9`,9:`0.8`,8:`0.7`,7:`0.6`,6:`0.5`,5:`0.4`,4:`0.3`,3:`0.2`,2:`0.1`,1:`0`};function vC(e){return typeof e.version==`number`}function yC(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function bC(e){let t=performance.now(),n=mC(),r=n.findIndex(t=>yC(t,e.version)>=0);if(r===-1)throw Error(`Data version ${e.version} postdates the current version of o-spreadsheet (version ${pC()}). It cannot be loaded.`);for(let t=r+1;t<n.length;t++){let r=n[t];e=dC.get(r).migrate(e)}return console.debug(`Data migrated in`,performance.now()-t,`ms`),e}function xC(e){return e=SC(e),e=CC(e),e}function SC(e){if(e.uniqueFigureIds)return e;let t=new Set,n=new Set;for(let r of e.sheets||[])for(let e of r.figures||[])t.has(e.id)&&(e.id+=G.smallUuid()),t.add(e.id),e.tag===`chart`&&(n.has(e.data?.chartId)&&(e.data.chartId+=G.smallUuid()),n.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}function CC(e){let t=Object.assign(jC(),e,{version:pC()});return t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(AC(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],t.sheets.length===0&&t.sheets.push(AC(hC,`Sheet1`)),S_(t.settings.locale)||(t.settings.locale=R),t}function wC(e,t){return t=TC(e,t),t=EC(t,`SORT_CELLS`),t=EC(t,`SET_DECIMAL`),t=DC(e,t),t=OC(e,t),t=kC(e,t),t}function TC(e,t){if(Object.keys(e).length!==0)return t;let n=[],r=[],i=e=>{if(e.type===`CREATE_SHEET`)n.push(e.sheetId);else if(`sheetId`in e&&!n.includes(e.sheetId))return{...e,sheetId:hC};return e};for(let e of t)e.type===`REMOTE_REVISION`?r.push({...e,commands:e.commands.map(i)}):r.push(e);return r}function EC(e,t){let n=[];for(let r of e)r.type===`REMOTE_REVISION`?n.push({...r,commands:r.commands.filter(e=>e.type!==t)}):n.push(r);return n}function DC(e,t){if(!e.version||yC(String(e.version),`18.5.1`)>=0)return t;let n=[],r={};e=gC(x(e));for(let t of e.sheets||[])t.figures?.forEach(e=>{e.tag===`chart`&&(r[e.id]=e.data)});for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let n of e.commands){let e=n;switch(n.type){case`CREATE_CHART`:r[n.chartId]=n.definition;break;case`UPDATE_CHART`:if(!r[n.chartId]){console.log(`Fix chart definition: chart with id ${n.chartId} not found.`);continue}let t={...r[n.chartId],...n.definition};e={...n,definition:t},delete t.chartId,r[n.chartId]=t;break}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}function OC(e,t){let n={};for(let t of e.sheets||[])t.figures?.forEach(e=>{n[e.id]=e.offset});for(let e of t)if(e.type===`REMOTE_REVISION`)for(let t of e.commands)switch(t.type){case`UPDATE_FIGURE`:t.offset&&(t.offset.x===void 0&&(t.offset.x=n[t.figureId]||0),t.offset.y===void 0&&(t.offset.y=n[t.figureId]||0),n[t.figureId]=n);break;case`CREATE_IMAGE`:case`CREATE_CHART`:case`CREATE_FIGURE`:n[t.figureId]=t.offset;break}return t}function kC(e,t){let n={};for(let t of e.sheets||[])n[t.id]=t.name;let r=[];for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let r of e.commands){switch(r.type){case`DUPLICATE_SHEET`:r.sheetNameTo=r.sheetNameTo??ru(n[r.sheetId],Object.values(n));break;case`CREATE_SHEET`:n[r.sheetId]=r.name||nu(Object.values(n));break;case`RENAME_SHEET`:n[r.sheetId]=r.newName||nu(Object.values(n));break}t.push(r)}r.push({...e,commands:t})}else r.push(e);return t}function AC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function jC(e=`Sheet1`){return{version:pC(),sheets:[AC(hC,e)],styles:{},formats:{},borders:{},revisionId:Ze,uniqueFigureIds:!0,settings:{locale:R},pivots:{},pivotNextId:1,customTableStyles:{},namedRanges:{}}}function MC(e,t){return{...AC(e,t),charts:[],images:[],cellValues:{}}}function NC(){return{...jC(),sheets:[MC(hC,`Sheet1`)]}}let PC=(e,t)=>{e.model.dispatch(t.type).isCancelledBecause(`WillRemoveExistingMerge`)&&e.raiseError(m_)},FC={wrongPasteSelection:j(`This operation is not allowed with multiple selections.`),willRemoveExistingMerge:__.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:j(`Cannot do a special paste of a figure.`),frozenPaneOverlap:j(`This operation is not allowed due to an overlapping frozen pane.`)};function IC(e,t){t.isSuccessful||(t.reasons.includes(`WrongPasteSelection`)?e.raiseError(FC.wrongPasteSelection):t.reasons.includes(`WillRemoveExistingMerge`)?e.raiseError(FC.willRemoveExistingMerge):t.reasons.includes(`WrongFigurePasteOption`)?e.raiseError(FC.wrongFigurePasteOption):t.reasons.includes(`FrozenPaneOverlap`)&&e.raiseError(FC.frozenPaneOverlap))}function LC(e,t,n){IC(e,e.model.dispatch(`PASTE`,{target:t,pasteOption:n}))}async function RC(e,t,n,r){if(n.data&&n.data.version!==pC()&&e.notifyUser({type:`warning`,text:j(`You copied content from a different version of the application. Only text and image content will be pasted.`),sticky:!1}),n.imageBlob){let t=n;try{t.imageData=await e.imageProvider?.uploadFile(n.imageBlob)}catch(t){let n=j(`An error occurred while uploading the image. %s`,t.message);console.error(t),e.raiseError(n)}delete n.imageBlob}IC(e,e.model.dispatch(`PASTE_FROM_OS_CLIPBOARD`,{target:t,clipboardContent:n,pasteOption:r}))}let zC=new O;var BC=class extends Vr{mutators=[`open`,`close`];persistentPopover;hoveredCell=this.get(c_);handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.close()}}open({col:e,row:t},n){let r=this.getters.getActiveSheetId();zC.contains(n)&&(this.persistentPopover={col:e,row:t,sheetId:r,type:n})}close(){if(!this.persistentPopover)return`noStateChange`;this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return this.persistentPopover!==void 0}get cellPopover(){let e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){let e=this.getters.getMainCellPosition(this.persistentPopover),t=zC.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}let{col:t,row:n}=this.hoveredCell;if(t===void 0||n===void 0||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:n}))return{isOpen:!1};let r=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),i=zC.getAll().map(e=>e.onHover?.(r,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(r)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){let n=this.getters.getActiveSheetId(),r=this.getters.getMerge({sheetId:n,col:e,row:t});return r?this.getters.getVisibleRect(r):this.getters.getVisibleRect(D({col:e,row:t}))}};let VC=function(e){return e.PlainText=`text/plain`,e.Html=`text/html`,e.Image=`image`,e}({}),HC=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function UC(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?gr(t):[t[t.length-1]],s=o.map(e=>dr(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function WC(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function GC(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>WC(e,n,r)).flat()}function KC(e){let t;e[`text/html`]&&(t=JC(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of HC)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function qC(e){return e?.match(/<div data-osheet-clipboard-id=(['"])([^'"]+)\1/)?.[2]}function JC(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let YC=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function XC(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureIds&&(s.figureIds={...s.figureIds,...u.figureIds});for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=er(a,e)}}return{target:s,zone:a,selectedZones:o}}let ZC=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:er(...n)},{scrollIntoView:!1})},QC={type:`bar`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,humanize:!0},$C={type:`line`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,cumulative:!1,labelsAsText:!1,humanize:!0};function ew(e,t){return Yn(e.getUnboundedZone(e.getActiveSheetId(),t))}function tw(e){if(!e.length)return`empty`;let t={number:0,text:0,date:0,percentage:0},n=0,r=`empty`;for(let i of e){let e=null;if(i.type===`number`?e=i.format&&Os(i.format)?`date`:i.format?.includes(`%`)?`percentage`:`number`:i.type===`text`&&(e=`text`),e){let i=++t[e];i>n&&(n=i,r=e)}}return r}function nw(e,t){let n=[];for(let r of Dr(e)){let e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),r);n.push({zone:r,type:tw(e)})}return n}function rw(e,t){let n=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||``).filter(e=>e);return{uniqueCount:new Set(n).size,totalCount:n.length}}function iw(e,t){let n=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![`number`,`empty`].includes(n.type)}function aw(e,t){let{type:n,zone:r}=e,i=t.getActiveSheetId(),a=iw(t,e),o=ew(t,r),s=t.getEvaluatedCell({sheetId:i,col:r.left,row:r.top});if(xr(r)===1)return cw(r,t);switch(n){case`percentage`:return{type:`pie`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{},legendPosition:`none`};case`text`:let e=t.getEvaluatedCellsInZone(i,r).reduce((e,t)=>t.value===s.value?e+1:e,0),n=s.value!==null&&e===1;return{type:`pie`,title:n?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],labelRange:o,dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!0,legendPosition:`top`};case`date`:return{...$C,type:`line`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}return{...QC,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}function ow(e,t){if(e.length!==2)throw Error(`buildTwoColumnChart expects exactly two columns`);if(e[1].type===`percentage`)return{type:`pie`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{},aggregated:!0,legendPosition:`none`};if(e[0].type===`number`&&e[1].type===`number`)return{type:`scatter`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{},labelsAsText:!1,legendPosition:`none`};if(e[0].type===`date`&&e[1].type===`number`)return{...$C,type:`line`,dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[0])},dataSetStyles:{}};if(e[0].type===`text`&&e[1].type===`number`){let n=e[0],r=e[1],{uniqueCount:i,totalCount:a}=rw(t,n.zone),o=iw(t,r);if(i!==a)return{type:`treemap`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,n.zone),dataSetId:`0`}],labelRange:ew(t,r.zone),dataSetsHaveTitle:o},dataSetStyles:{},legendPosition:`none`}}return{...QC,dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{}}}function sw(e,t){if(e.length<3)throw Error(`buildMultiColumnChart expects at least three columns`);let n=e.some(e=>e.type!==`text`&&iw(t,e)),r=e[e.length-1],i=e.slice(0,e.length-1);if((r.type===`percentage`||r.type===`number`)&&i.every(e=>e.type===`text`)){let e=i.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return{type:i.length>=3?`sunburst`:`treemap`,title:{},dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:n,labelRange:ew(t,r.zone)},dataSetStyles:{},legendPosition:`none`}}let a=e[0],o=e.slice(1),s=o.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return o.every(e=>e.type===`percentage`)?{type:`pie`,title:{},dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!1,legendPosition:`top`}:a.type===`date`&&o.every(e=>e.type===`number`)?{...$C,type:`line`,dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}:{...QC,dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}}function cw(e,t){let n=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:`scorecard`,title:{},keyValue:ew(t,e),background:n?.style?.fillColor,baselineMode:Qe,baselineColorUp:$e,baselineColorDown:et}}function lw(e,t){let n=nw(e,t);if(n.length===0||n.every(e=>e.type===`empty`)){let e=n.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return{...QC,dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:!1}}}let r=n.filter(e=>e.type!==`empty`);switch(r.length){case 1:return{humanize:!0,...aw(r[0],t)};case 2:return{humanize:!0,...ow(r,t)};default:return{humanize:!0,...sw(r,t)}}}function uw(e,t,n=Mb){let r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r);r.length===1&&!i&&xr(r[0])===1&&(e.model.selection.selectTableAroundSelection(),r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r));let a=r.map(n=>e.model.getters.getRangeDataFromZone(t,n)),o=e.model.dispatch(`CREATE_TABLE`,{ranges:a,sheetId:t,config:n,tableType:i?`dynamic`:`static`});return o.isCancelledBecause(`TableOverlap`)?e.raiseError(y_.Errors.TableOverlap):o.isCancelledBecause(`NonContinuousTargets`)&&e.raiseError(y_.Errors.NonContinuousTargets),o}function dw(e,t){e.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function fw(e,t){e.model.dispatch(`SET_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}let pw=async e=>hw(e),mw=async e=>hw(e,`asValue`);async function hw(e,t){let n=await e.clipboard.read();switch(n.status){case`ok`:let r=e.model.getters.getClipboardId(),i=e.model.getters.getSelectedZones();r===qC(n.content[`text/html`])?LC(e,i,t):await RC(e,i,KC(n.content),t),e.model.getters.isCutOperation()&&t!==`asValue`&&await e.clipboard.write({"text/plain":``});break;case`notImplemented`:e.raiseError(j(`Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead.`));break;case`permissionDenied`:e.raiseError(j(`Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings.`));break}}let gw=e=>hw(e,`onlyFormat`),_w=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Clear row %s`,(t+1).toString()):j(`Clear rows %s - %s`,(t+1).toString(),(n+1).toString())},vw=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveRows()].map(n=>e.model.getters.getRowsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},yw=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Clear column %s`,Cn(t)):j(`Clear columns %s - %s`,Cn(t),Cn(n))},bw=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveCols()].map(n=>e.model.getters.getColsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},xw=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Delete row %s`,(t+1).toString()):j(`Delete rows %s - %s`,(t+1).toString(),(n+1).toString())},Sw=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.top;e<=n.bottom;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},Cw=(e,t)=>{if(e===`COL`&&t.model.getters.getActiveRows().size>0||e===`ROW`&&t.model.getters.getActiveCols().size>0)return!1;let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(n,e,r),a=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(n,e,r);return!i&&!a},ww=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Delete column %s`,Cn(t)):j(`Delete columns %s - %s`,Cn(t),Cn(n))},Tw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`ROW`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`ROW`,n)},Ew=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.left;e<=n.right;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`COL`,elements:t})},Dw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`COL`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`COL`,n)},Ow=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=mn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.top,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,base:n,quantity:r,dimension:`ROW`})},kw=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=pn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.bottom,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,base:n,quantity:r,dimension:`ROW`})},Aw=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=mn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.left,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,dimension:`COL`,base:n,quantity:r})},jw=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=pn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.right,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,dimension:`COL`,base:n,quantity:r})},Mw=e=>{let t=e.model.getters.getElementsFromSelection(`COL`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide column %s`,Cn(n).toString()):r-n+1===t.length?j(`Hide columns %s - %s`,Cn(n).toString(),Cn(r).toString()):j(`Hide columns`)},Nw=e=>{let t=e.model.getters.getElementsFromSelection(`ROW`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide row %s`,(n+1).toString()):r-n+1===t.length?j(`Hide rows %s - %s`,(n+1).toString(),(r+1).toString()):j(`Hide rows`)},Pw=e=>{let t=e.model.getters,n=G.smallUuid(),r=t.getActiveSheetId(),i=t.getSelectedZones();i.length===1&&xr(i[0])===1&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());let a={width:536,height:335},{col:o,row:s,offset:c}=Wh(t,a);e.model.dispatch(`CREATE_CHART`,{sheetId:r,figureId:n,chartId:G.smallUuid(),col:o,row:s,offset:c,size:a,definition:lw(i,e.model.getters)}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`ChartPanel`))},Fw=e=>{let t=e.model.getters,n=G.smallUuid(),r=t.getActiveSheetId(),i={width:536,height:335},{col:a,row:o,offset:s}=Wh(t,i);e.model.dispatch(`CREATE_CAROUSEL`,{sheetId:r,figureId:n,col:a,row:o,offset:s,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`CarouselPanel`,{figureId:n}))},Iw=e=>{let t=G.smallUuid(),n=G.smallUuid();e.model.dispatch(`INSERT_NEW_PIVOT`,{pivotId:t,newSheetId:n}).isSuccessful&&e.openSidePanel(`PivotSidePanel`,{pivotId:t})},Lw=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r,col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`dynamic`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),Rw=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getExpandedTableStructure();if(r.numberOfCells>5e5){e.notifyUser({type:`warning`,text:x_(r.numberOfCells,e.model.getters.getLocale()),sticky:!0});return}e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r.export(),col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`static`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),zw=async e=>{if(e.imageProvider){let t=e.model.getters.getActiveSheetId(),n=G.smallUuid(),r=await e.imageProvider.requestImage(),i=Gh(e.model.getters,r.size),{col:a,row:o,offset:s}=Wh(e.model.getters,i);e.model.dispatch(`CREATE_IMAGE`,{sheetId:t,figureId:n,col:a,row:o,offset:s,size:i,definition:r})}},Bw=e=>dw(e,`0.00%`),Vw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getConditionalFormats(t),i=e.model.getters.getRulesSelection(t,n);return i.length===1?e.openSidePanel(`ConditionalFormattingEditor`,{cf:r.find(e=>e.id===i[0]),isNewCf:!1}):e.openSidePanel(`ConditionalFormatting`)},Hw=e=>{let{col:t,row:n}=e.model.getters.getActivePosition();e.getStore(BC).open({col:t,row:n},`LinkEditor`)},Uw=e=>{let t=e.model.getters.getActiveSheetId(),{col:n,row:r}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:n,row:r});return i&&i.link?j(`Edit link`):j(`Insert link`)},Ww=e=>e.model.getters.getFirstTableInSelection()?.config.hasFilters||!1,Gw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getTablesOverlappingZones(t,n);return r.length===1&&!r[0].isPivotTable},Kw=e=>Tr(e.model.getters.getSelectedZones()),qw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n?e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!0}}):uw(e,t,{...Mb,hasFilters:!0,bandedRows:!1,styleId:`TableStyleLight11`})},Jw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n&&e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!1}})},Yw=e=>{uw(e,e.model.getters.getActiveSheetId()).isSuccessful&&e.openSidePanel(`TableSidePanel`,{})},Xw=e=>{let t=e.model.getters.getFirstTableInSelection();t&&e.model.dispatch(`REMOVE_TABLE`,{sheetId:e.model.getters.getActiveSheetId(),target:[t.range.zone]})},Zw=e=>e.model.getters.getSelectedZones().length===1,Qw=(e,t)=>{if(!Zw(e))return!1;let n=t===`COL`?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),r=t===`COL`?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),a=rr(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return an(n)&&(r.size===0||a)},$w={name:e=>Ww(e)?j(`Remove selected filters`):j(`Add filters`),isEnabled:e=>Kw(e),execute:e=>Ww(e)?Jw(e):qw(e),icon:`o-spreadsheet-Icon.FILTER_ICON_ACTIVE`},eT={name:e=>{let t=PT(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW`},tT={name:e=>{let t=PT(e);return t===1?j(`Insert row above`):j(`Insert %s rows above`,t.toString())},execute:Ow,isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},nT={...tT,name:e=>{let t=PT(e);return t===1?j(`Row above`):j(`%s Rows above`,t.toString())}},rT={...tT,name:e=>{let t=PT(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:Zw,icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},iT={execute:kw,name:e=>{let t=PT(e);return t===1?j(`Insert row below`):j(`Insert %s rows below`,t.toString())},isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_AFTER`},aT={...iT,name:e=>{let t=PT(e);return t===1?j(`Row below`):j(`%s Rows below`,t.toString())}},oT={name:e=>{let t=FT(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL`},sT={name:e=>{let t=FT(e);return t===1?j(`Insert column left`):j(`Insert %s columns left`,t.toString())},execute:Aw,isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},cT={...sT,name:e=>{let t=FT(e);return t===1?j(`Column left`):j(`%s Columns left`,t.toString())}},lT={...sT,name:e=>{let t=FT(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:Zw,icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},uT={name:e=>{let t=FT(e);return t===1?j(`Insert column right`):j(`Insert %s columns right`,t.toString())},execute:jw,isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_AFTER`},dT={...uT,name:e=>{let t=FT(e);return t===1?j(`Column right`):j(`%s Columns right`,t.toString())},execute:jw},fT={name:j(`Insert cells`),isVisible:e=>Zw(e)&&e.model.getters.getActiveCols().size===0&&e.model.getters.getActiveRows().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL`},pT={name:j(`Insert cells and shift down`),execute:e=>{let t=e.model.getters.getSelectedZone();IC(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`ROW`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN`},mT={name:j(`Insert cells and shift right`),execute:e=>{let t=e.model.getters.getSelectedZone();IC(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`COL`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT`},hT={name:j(`Chart`),execute:Pw,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_CHART`},gT={name:j(`Carousel`),execute:Fw,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.CAROUSEL`},_T={name:j(`Pivot table`),execute:Iw,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},vT={name:j(`Image`),shortcut:`Ctrl+O`,execute:zw,isVisible:e=>e.imageProvider!==void 0,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_IMAGE`},yT={name:()=>j(`Table`),shortcut:`Alt+T`,execute:Yw,isVisible:e=>Kw(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.PAINT_TABLE`},bT={name:j(`Function`),icon:`o-spreadsheet-Icon.FORMULA`},xT={name:j(`SUM`),execute:e=>e.startCellEdition(`=SUM(`)},ST={name:j(`AVERAGE`),execute:e=>e.startCellEdition(`=AVERAGE(`)},CT={name:j(`COUNT`),execute:e=>e.startCellEdition(`=COUNT(`)},wT={name:j(`MAX`),execute:e=>e.startCellEdition(`=MAX(`)},TT={name:j(`MIN`),execute:e=>e.startCellEdition(`=MIN(`)},ET={name:j(`All`),children:[DT]};function DT(){return NT(bc.getKeys().filter(e=>!bc.get(e).hidden))}let OT=()=>{let e=bc.content;return[...new Set(bc.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(w).sort().map((t,n)=>({name:t,children:NT(Object.keys(e).filter(n=>e[n].category===t&&!e[n].hidden)),sequence:60+n}))},kT={name:j(`Link`),shortcut:`Ctrl+Shift+K`,execute:Hw,icon:`o-spreadsheet-Icon.INSERT_LINK`},AT={name:j(`Checkbox`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t));e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:G.smallUuid(),criterion:{type:`isBoolean`,values:[]}}})},icon:`o-spreadsheet-Icon.INSERT_CHECKBOX`},jT={name:j(`Dropdown list`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t)),i=G.smallUuid();e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:i,criterion:{type:`isValueInList`,values:[],displayStyle:`chip`}}}),e.model.getters.getDataValidationRule(n,i)&&e.openSidePanel(`DataValidationEditor`,{ruleId:i,onCancel:()=>{e.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:n,id:i})}})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_DROPDOWN`},MT={name:j(`Insert sheet`),shortcut:`Shift+F11`,execute:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSheetIds().indexOf(t)+1,r=G.smallUuid();e.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:e.model.getters.getNextSheetName()}),e.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})},icon:`o-spreadsheet-Icon.INSERT_SHEET`};function NT(e){return e.sort().map((e,t)=>({name:e,sequence:t*10,execute:t=>t.startCellEdition(`=${e}(`)}))}function PT(e){let t=e.model.getters.getActiveRows();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function FT(e){let t=e.model.getters.getActiveCols();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function IT(e,t){let n=()=>{window.removeEventListener(`pointerup`,r,{capture:!0}),window.removeEventListener(`dragstart`,i),window.removeEventListener(`pointermove`,e),window.removeEventListener(`wheel`,e)},r=e=>{t(e),n()};function i(e){e.preventDefault()}return window.addEventListener(`pointerup`,r,{capture:!0}),window.addEventListener(`dragstart`,i),window.addEventListener(`pointermove`,e),window.addEventListener(`wheel`,e,{passive:!1}),n}function LT(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new VT(a.scrollableContainerEl):new BT(a.scrollableContainerEl);e=new RT({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=IT(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.proxy)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var RT=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),H(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},zT=class{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},BT=class extends zT{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},VT=class extends zT{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}};function HT(e){(0,t.useEffect)(()=>e()?.focus())}let UT={value:W.or([W.number(),W.string()]),onChange:W.function([W.string()]),"onFocused?":W.function([]),"onBlur?":W.function([]),"onInput?":W.function([W.string()]),"class?":W.string(),"id?":W.string(),"placeholder?":W.string(),"autofocus?":W.boolean(),"alwaysShowBorder?":W.boolean(),"selectContentOnFocus?":W.boolean(),"resetOnBlur?":W.boolean()};var WT=class extends k{props=(0,t.props)(UT);genericInputRef=(0,t.signal)(null);lastOnChangeValue=this.props.value.toString();setup(){(0,t.useListener)(window,`click`,e=>{let t=this.genericInputRef();!t||e.target===t||t.value===this.props.value.toString()||(this.props.resetOnBlur?t.value=this.props.value.toString():this.save())},{capture:!0}),this.props.autofocus&&HT(this.genericInputRef),(0,t.onWillUpdateProps)(e=>{let t=this.genericInputRef();document.activeElement!==t&&t&&(t.value=e.value),this.lastOnChangeValue=e.value.toString()}),(0,t.onMounted)(()=>{let e=this.genericInputRef();e&&(e.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:let t=this.genericInputRef();t&&(t.value=this.props.value.toString(),t.blur()),e.preventDefault(),e.stopPropagation();break}}save(){let e=(this.genericInputRef()?.value||``).trim();e!==this.lastOnChangeValue&&(this.lastOnChangeValue=e,this.props.onChange(e)),document.activeElement===this.genericInputRef()&&this.genericInputRef()?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}onFocus(){this.props.onFocused?.()}onBlur(){if(this.props.onBlur?.(),this.props.resetOnBlur){let e=this.genericInputRef();e&&(e.value=this.props.value.toString())}else this.save()}onInput(e){let t=e.target;this.props.onInput?.(t.value)}},GT=class extends WT{static template=`o-spreadsheet-TextInput`;static components={};props=(0,t.props)({...UT,value:W.string(),"errorMessage?":W.string()});get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(w).join(` `)}},KT=class extends k{static template=`o-spreadsheet-ActionButton`;props=(0,t.props)({action:W.ActionSpec(),"hasTriangleDownIcon?":W.boolean(),"selectedColor?":W.string(),"class?":W.string(),"onClick?":W.function()});actionButton=xe(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=xe(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){let e=this.actionButton.isEnabledOnLockedSheet||!this.env.model.getters.isCurrentSheetLocked();return this.actionButton.isEnabled(this.env)&&e}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){let e=this.actionButton.name(this.env),t=this.actionButton.description(this.env)||this.actionButton.shortcut;return e+(t?` (${t})`:``)}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?H({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}},qT=class extends k{static template=`o-spreadsheet-ColorPicker`;static components={Popover:Xg};props=(0,t.props)({onColorPicked:W.function([W.string()]),"currentColor?":W.string(),"maxHeight?":W.Pixel(),anchorRect:W.Rect(),"disableNoColor?":W.boolean()},{currentColor:``});COLORS=Ve;state=(0,t.proxy)({showGradient:!1,currentHslaColor:df(this.props.currentColor)?{...Sf(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:df(this.props.currentColor)?uf(this.props.currentColor):``});get colorPickerStyle(){return this.props.maxHeight!==void 0&&this.props.maxHeight<=0?H({display:`none`}):``}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,verticalOffset:0}}get gradientHueStyle(){return H({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){let e=this.state.currentHslaColor?.h||0;return H({"margin-left":`${S(Math.round(e/360*216),1,216)-18/2}px`})}get pointerStyle(){let{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0},n=Math.round(216*S(e/100,0,1)),r=Math.round(186*S(1-2*t/(200-e),0,1));return H({left:`${-16/2+n}px`,top:`${-16/2+r}px`,background:xf(this.state.currentHslaColor)})}get colorPreviewStyle(){return H({"background-color":xf(this.state.currentHslaColor)})}get checkmarkColor(){return xp(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||df(this.state.customHexColor)}setCustomGradient({x:e,y:t}){let n=S(e,0,216),r=S(t,0,186),i=n/216,a=r/186,o=100*i,s=100*(1-a)*(1-.5*i);this.updateColor({s:o,l:s})}setCustomHue(e){let t=Math.round(S(360*e/216,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=xf(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(uf(e))}resetColor(){this.props.onColorPicked(``)}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){let t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);let n={x:e.clientX,y:e.clientY};IT(e=>{let r={x:e.clientX,y:e.clientY},i=r.x-n.x,a=r.y-n.y,o={x:t.x+i,y:t.y+a};this.setCustomGradient(o)},()=>{})}dragHuePointer(e){let t=e.offsetX,n=e.clientX;this.setCustomHue(t),IT(e=>{let r=t+(e.clientX-n);this.setCustomHue(r)},()=>{})}setHexColor(e){let t=e.target.value.replace(`##`,`#`).slice(0,7);this.state.customHexColor=t,df(t)&&(this.state.currentHslaColor={...Sf(t),a:1})}addCustomColor(e){!ff(this.state.currentHslaColor)||!df(this.state.customHexColor)||this.props.onColorPicked(uf(this.state.customHexColor))}isSameColor(e,t){return Tf(e,t)}},JT=class extends k{static template=`o-spreadsheet-ColorPickerWidget`;static components={ColorPicker:qT};props=(0,t.props)({"currentColor?":W.string(),toggleColorPicker:W.function([]),showColorPicker:W.boolean(),onColorPicked:W.function([W.string()]),icon:W.string(),"title?":W.string(),"disabled?":W.boolean(),"dropdownMaxHeight?":W.Pixel(),"class?":W.string()});colorPickerButtonRef=(0,t.signal)(null);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){return y(this.colorPickerButtonRef())}},YT=class extends k{static template=`o-spreadsheet-NumberEditor`;static components={Popover:Xg};props=(0,t.props)({currentValue:W.number(),onValueChange:W.function([W.number()]),"onToggle?":W.function([]),"onFocusInput?":W.function([]),class:W.string(),"valueIcon?":W.string(),min:W.number(),max:W.number(),title:W.string(),valueList:W.array(W.number())},{onFocusInput:()=>{}});dropdown=(0,t.proxy)({isOpen:!1});inputRef=(0,t.signal)(null);rootEditorRef=(0,t.signal)(null);valueListRef=(0,t.signal)(null);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=A(Cg),mi(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{let t=this.inputRef();t&&document.activeElement!==t&&(t.value=e.currentValue)}),(0,t.onMounted)(()=>{let e=this.inputRef();e&&(e.value=this.props.currentValue.toString())})}get popoverProps(){return{anchorRect:y(this.rootEditorRef()),positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){let t=this.valueListRef(),n=this.rootEditorRef();t&&n&&!_(t,e)&&!_(n,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef()?.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=S(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},XT=class extends k{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:YT};props=(0,t.props)({currentFontSize:W.number(),onFontSizeChanged:W.function([W.number()]),"onToggle?":W.function([]),"onFocusInput?":W.function([]),class:W.string()},{onFocusInput:()=>{}});fontSizes=st},ZT=class extends k{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:JT,ActionButton:KT,FontSizeEditor:XT};props=(0,t.props)({style:W.ChartStyle(),updateStyle:W.function([W.ChartStyle()]),"defaultStyle?":W.object({}),"hasVerticalAlign?":W.boolean(),"hasHorizontalAlign?":W.boolean(),"hasBackgroundColor?":W.boolean(),"class?":W.string()});openedEl=null;setup(){mi(window,`click`,this.onExternalClick)}state=(0,t.proxy)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??Ue.fontSize}get boldButtonAction(){return{name:j(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:j(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:j(`Horizontal alignment`),icon:e,isEnabledOnLockedSheet:!0}}get horizontalAlignActions(){return[{name:j(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:j(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:j(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:j(`Vertical alignment`),icon:e,isEnabledOnLockedSheet:!0}}get verticalAlignActions(){return[{name:j(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:j(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:j(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},QT=class extends k{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:e_};props=(0,t.props)({items:W.array(W.ActionSpec())});buttonRef=(0,t.signal)(null);menuState=(0,t.proxy)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=G.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=b(this.buttonRef()),this.menuState.menuItems=ve(this.props.items))}},Z=class extends k{static template=`o_spreadsheet.Section`;props=(0,t.props)({"class?":W.string(),"title?":W.string(),slots:W.object()})},$T=class extends k{static template=`o-spreadsheet-CarouselPanel`;static components={Section:Z,TextInput:GT,TextStyler:ZT,CogWheelMenu:QT};props=(0,t.props)({onCloseSidePanel:W.function([]),figureId:W.UID()});DEFAULT_CAROUSEL_TITLE_STYLE=dt;dragAndDrop=LT();previewListRef=(0,t.signal)(null);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{T(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return T(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>T(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!T(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:G.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=this.previewListRef();if(!n)return;let r=Array.from(n.children).map(e=>b(e)),i=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:r[t].height,position:r[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:i,scrollableContainerEl:n,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>T(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return ag(this.env.model.getters,e)}getItemPreview(e){return ig(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return j(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:j(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:j(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:j(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:j(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return j(`The data view makes the carousel transparent, revealing the data underneath.`)}};let eE=new O;var tE=class extends k{static template=`o-spreadsheet.Checkbox`;props=(0,t.props)({"label?":W.string(),"value?":W.boolean(),"className?":W.string(),"name?":W.string(),"title?":W.string(),"disabled?":W.boolean(),onChange:W.function([W.boolean()])},{value:!1});onChange(e){let t=e.target.checked;this.props.onChange(t)}};let nE={chartId:W.UID(),definition:W.object({}),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())},rE={ArrowDown:`down`,ArrowLeft:`left`,ArrowRight:`right`,ArrowUp:`up`};function iE(e,t){let n=rE[e.key];e.shiftKey?t.resizeAnchorZone(n,le(e)?`end`:1):t.moveAnchorCell(n,le(e)?`end`:1)}function aE(e,t,n){let{anchor:{zone:r,cell:i}}=e.getSelection(),a={...i},o=xr(r);do a=oE(a,r,n),o--;while(o>0&&!sE(e,a));o>0&&t.updateAnchorCell(a.col,a.row,{scrollIntoView:!0})}function oE(e,t,n){let{col:r,row:i}=e;switch(n){case`right`:r<t.right?r++:(r=t.left,i=i<t.bottom?i+1:t.top);break;case`left`:r>t.left?r--:(r=t.right,i=i>t.top?i-1:t.bottom);break;case`down`:i<t.bottom?i++:(i=t.top,r=r<t.right?r+1:t.left);break;case`up`:i>t.top?i--:(i=t.bottom,r=r>t.left?r-1:t.right);break}return{col:r,row:i}}function sE(e,t){let n=e.getActiveSheetId();if(e.isHeaderHidden(n,`COL`,t.col)||e.isHeaderHidden(n,`ROW`,t.row))return!1;let r=e.getMainCellPosition({sheetId:n,col:t.col,row:t.row});return r.col===t.col&&r.row===t.row}function cE(e,t,n){let{x:r,y:i,width:a,height:o}=n;if(a<0||o<0)return;let s=t.color||`#017E84`,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=s,t.thinLine?(c.lineWidth=1,c.strokeRect(r,i,a,o)):(c.lineWidth=2,c.strokeRect(r+.5,i+.5,a,o))),t.noFill||(c.fillStyle=Ef(uf(s),t.fillAlpha??.12),c.fillRect(r,i,a,o)),c.restore()}var lE=class extends Vr{mutators=[`register`,`unRegister`];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return[`Highlights`]}get highlights(){let e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{let{numberOfRows:t,numberOfCols:n}=cr(e.range.zone),r=t*n===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,r)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if(t===`Highlights`)for(let t of this.highlights)cE(e,t,e.viewports.getVisibleRect(e.sheetId,t.range.zone))}},uE=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},dE=class extends Vr{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`,`toggleEditMode`];ranges=[];focusedRangeIndex=null;mode=`text-edit`;inputSheetId;focusStore=this.get(uE);highlightStore=this.get(lE);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}this.mode=`select-range`}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,D({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=Nc(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return rr(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new Gf(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){let t=this.getIndex(e);if(this.focusedRangeIndex!==t||this.mode===`select-range`){this.focus(t),this.mode=`text-edit`;return}return`noStateChange`}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new Gf(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=Nc(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=Nc(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}toggleEditMode(){this.mode=this.mode===`select-range`?`text-edit`:`select-range`}},fE=class extends k{static template=`o-spreadsheet-SelectionInput`;props=(0,t.props)({ranges:W.array(W.string()),"hasSingleRange?":W.boolean(),"required?":W.boolean(),"autofocus?":W.boolean(),"isInvalid?":W.boolean(),"class?":W.string(),"onSelectionChanged?":W.function([W.array(W.string())]),"onSelectionConfirmed?":W.function([]),"onSelectionReordered?":W.function([W.array(W.number())]),"onSelectionRemoved?":W.function([W.number()]),"onInputFocused?":W.function([]),"colors?":W.ArrayOf(),"disabledRanges?":W.array(W.boolean()),"disabledRangeTitle?":W.string()},{colors:[],disabledRanges:[]});state=(0,t.proxy)({isMissing:!1});dragAndDrop=LT();focusedInputRef=(0,t.signal)(null);unfocusedInputRef=(0,t.signal)(null);selectionRef=(0,t.signal)(null);DOMFocusableElementStore;store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){(0,t.onWillStart)(()=>{}),(0,t.onWillUpdateProps)(async()=>{}),this.DOMFocusableElementStore=A(Cg),this.store=Ei(dE,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&(this.store.focusById(this.store.selectionInputs[0]?.id),this.props.onInputFocused?.()),(0,t.useEffect)(()=>{this.focusedInputRef()?.focus()}),hi(()=>{let e=this.selectionRef();(this.store.isResettable||this.store.hasFocus)&&e?.offsetParent===null&&this.reset()}),(0,t.onWillUpdateProps)(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),!T(e.disabledRanges,this.props.disabledRanges)&&!T(e.disabledRanges,this.store.disabledRanges)&&this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getRangeElementsRects(),r=this.ranges.map(e=>e.id),i=r.map((e,t)=>({id:e.toString(),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef(),onDragEnd:(t,n)=>{let i=r.findIndex(t=>t===e);if(i===n)return;let a=C(0,r.length);a.splice(i,1),a.splice(n,0,i),this.props.onSelectionReordered?.(a),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef().children).map(e=>e.getBoundingClientRect())}getColor(e){let t={};return e.color&&(t.color=e.color),this.store.mode===`select-range`&&(t[`caret-color`]=`transparent`),H(t)}triggerChange(){let e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){e.key===`F2`?(e.preventDefault(),e.stopPropagation(),this.store.toggleEditMode()):e.key.startsWith(`Arrow`)?(e.stopPropagation(),this.store.mode===`select-range`&&(e.preventDefault(),iE(e,this.env.model.selection))):e.key===`Enter`?(e.target.blur(),this.isConfirmable&&this.confirm()):e.key===`Escape`&&(this.reset(),this.DOMFocusableElementStore.focus())}extractRanges(e){return this.props.hasSingleRange?e.split(`,`)[0]:e}focus(e){this.state.isMissing=!1,this.store.focusById(e),this.props.onInputFocused?.()}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){let t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){let n=t.target,r=this.extractRanges(n.value);this.store.changeRange(e,r),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();let e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}},pE=class extends k{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:fE,Section:Z};props=(0,t.props)({ranges:W.ArrayOf(),"dataSetStyles?":W.DataSetStyle(),"hasSingleRange?":W.boolean(),onSelectionChanged:W.function([W.array(W.string())]),"onSelectionReordered?":W.function([W.array(W.number())]),"onSelectionRemoved?":W.function([W.number()]),onSelectionConfirmed:W.function([]),"maxNumberOfUsedRanges?":W.number(),"title?":W.string(),"datasetOrientation?":W.or([W.literal(`rows`),W.literal(`columns`)]),"canChangeDatasetOrientation?":W.boolean(),"onFlipAxis?":W.function([W.string()])});get ranges(){return this.props.ranges.map(e=>e.dataRange)}setup(){(0,t.onWillUpdateProps)(async()=>{})}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>this.props.dataSetStyles?.[e.dataSetId]?.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?j(`Data range`):j(`Data series`)}},mE=class extends k{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:fE,Checkbox:tE,Section:Z};props=(0,t.props)({"title?":W.string(),range:W.string(),"class?":W.string(),isInvalid:W.boolean(),onSelectionChanged:W.function([W.string()]),onSelectionConfirmed:W.function([]),"options?":W.ArrayOf()},{title:j(`Categories / Labels`),options:[]});get sectionClass(){return`o-data-labels`+(this.props.class?` ${this.props.class}`:``)}},hE=class extends k{static template=`o-spreadsheet-ChartDataSourceComponent`;static components={ChartDataSeries:pE,ChartLabelRange:mE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),updateChart:W.function([]),canUpdateChart:W.function([]),"onErrorMessagesChanged?":W.function([W.array(W.string())]),"dataSeriesTitle?":W.string(),"labelRangeTitle?":W.string(),"getLabelRangeOptions?":W.function([])});get DataSourceComponent(){let e=this.props.definition.dataSource.type;return eE.get(e)}},gE=class extends k{static template=`o-spreadsheet-ValidationMessages`;props=(0,t.props)({messages:W.array(W.string()),msgType:W.or([W.literal(`warning`),W.literal(`error`),W.literal(`info`)]),"singleBox?":W.boolean()});get divClasses(){return this.props.msgType===`warning`?`o-validation-warning`:this.props.msgType===`info`?`o-validation-info`:`o-validation-error`}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}},_E=class extends k{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:Z,ValidationMessages:gE};props=(0,t.props)({messages:W.array(W.string())})},vE=class extends k{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSourceComponent:hE,Section:Z,Checkbox:tE,ChartErrorSection:_E};props=(0,t.props)(nE);chartTerms=f_;state=(0,t.proxy)({errorMessages:[]});onErrorMessagesChanged(e){this.state.errorMessages=e}get errorMessages(){return this.state.errorMessages}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}getAggregateLabelRangeOption(){return{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in this.props.definition?this.props.definition.aggregated:!1)??!1,onChange:e=>{this.props.updateChart(this.props.chartId,{aggregated:e})}}}},yE=class extends vE{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}},bE=class extends k{static template=`o-spreadsheet-Collapse`;props=(0,t.props)({isCollapsed:W.boolean()});contentRef=(0,t.signal)(null);setup(){(0,t.onMounted)(()=>{this.props.isCollapsed&&this.contentRef()?.classList.add(`d-none`)}),(0,t.onWillUpdateProps)(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){let t=this.contentRef();if(!t)return;t.classList.remove(`d-none`),t.classList.add(`overflow-hidden`);let n=e?t.scrollHeight:0,r=e?0:t.scrollHeight,i=t.animate([{maxHeight:n+`px`},{maxHeight:r+`px`}],{duration:350,easing:`ease`});i.onfinish=()=>{t.classList.remove(`overflow-hidden`),this.props.isCollapsed&&t.classList.add(`d-none`)}}},xE=class extends k{static template=`o-spreadsheet-SidePanelCollapsible`;static components={Collapse:bE};props=(0,t.props)({"title?":W.string(),"isInitiallyCollapsed?":W.boolean(),"class?":W.string()});state=(0,t.proxy)({isCollapsed:!!this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}},SE=class extends WT{static template=`o-spreadsheet-NumberInput`;static components={};props=(0,t.props)({...UT,"min?":W.number(),"max?":W.number()});debouncedOnChange=Ht(this.props.onChange.bind(this),100,!0);save(){let e=(this.genericInputRef()?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},CE=class extends SE{static template=`o-spreadsheet-DateInput`},wE=class extends k{static template=`o-spreadsheet.BadgeSelection`;props=(0,t.props)({choices:W.ArrayOf(),onChange:W.function([W.string()]),selectedValue:W.string()})},TE=class extends k{static template=`o-spreadsheet.ChartTitle`;static components={Section:Z,TextStyler:ZT,TextInput:GT};props=(0,t.props)({"title?":W.string(),"placeholder?":W.string(),updateTitle:W.function([W.string()]),"name?":W.string(),style:W.TitleDesign(),"defaultStyle?":W.object({}),updateStyle:W.function([W.object({})])},{title:``,placeholder:``});updateTitle(e){this.props.updateTitle(e)}},EE=class extends k{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:Z,ChartTitle:TE,BadgeSelection:wE,Checkbox:tE,NumberInput:SE,DateInput:CE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartWithAxisDefinition(),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),axesList:W.ArrayOf()});state=(0,t.proxy)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title?.text||``}updateAxisTitle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}get axisMin(){let e=this.currentAxisDesign?.min;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get axisMax(){let e=this.currentAxisDesign?.max;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get isMajorGridEnabled(){let e=this.currentAxisDesign?.gridLines;return e===void 0?this.getDefaultMajorGridValue(this.state.currentAxis):e===`major`||e===`both`}get isMinorGridEnabled(){return this.currentAxisDesign?.gridLines===`minor`||this.currentAxisDesign?.gridLines===`both`}get isValueAxis(){return`horizontal`in this.props.definition&&this.props.definition.horizontal?this.state.currentAxis===`x`:this.state.currentAxis!==`x`}get majorGridLabel(){return this.state.currentAxis===`x`?j(`Major vertical gridlines`):j(`Major horizontal gridlines`)}get minorGridLabel(){return this.state.currentAxis===`x`?j(`Minor vertical gridlines`):j(`Minor horizontal gridlines`)}updateAxisMin(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMin(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}updateAxisMax(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMax(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}toggleMajorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMinorGridEnabled?e?`both`:`minor`:e?`major`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}toggleMinorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMajorGridEnabled?e?`both`:`major`:e?`minor`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}get currentAxisDesign(){return this.props.definition.axesDesign?.[this.state.currentAxis]}getDefaultMajorGridValue(e){let{useLeftAxis:t,useRightAxis:n}=Dp(this.props.definition);if(e===`x`){if(`horizontal`in this.props.definition&&this.props.definition.horizontal||this.props.definition.type===`scatter`)return!0}else if(e===`y`)return!0;else if(e===`y1`)return!t&&n;return!1}get isCategoricalAxis(){if(this.isValueAxis)return!1;let e=this.getXAxisType();return e===void 0||e===`category`}get isTimeAxis(){return this.state.currentAxis===`x`&&this.getXAxisType()===`time`}get canChangeMinorGridVisibility(){if(this.isValueAxis)return!0;if(this.isCategoricalAxis)return!1;let e=this.props.definition.type;return e===`line`||e===`scatter`}parseTimeAxisBoundaryValue(e){let t=P(e,this.env.model.getters.getLocale());return Number.isNaN(t)?null:t}formatAxisBoundary(e){if(e!==void 0)return z(e,{format:`yyyy-mm-dd`,locale:this.env.model.getters.getLocale()})}getXAxisType(){return this.env.model.getters.getChartRuntime(this.props.chartId)?.chartJsConfig.options?.scales?.x?.type}},DE=class extends k{static template=`o-spreadsheet.RadioSelection`;props=(0,t.props)({choices:W.ArrayOf(),onChange:W.function([W.any()]),selectedValue:W.string(),name:W.string(),"direction?":W.or([W.literal(`horizontal`),W.literal(`vertical`)])},{direction:`horizontal`})},OE=class extends k{static template=`o-spreadsheet.RoundColorPicker`;static components={Section:Z,ColorPicker:qT};props=(0,t.props)({"currentColor?":W.string(),"title?":W.string(),onColorPicked:W.function([W.string()]),"disableNoColor?":W.boolean()});colorPickerButtonRef=(0,t.signal)(null);state;setup(){this.state=(0,t.proxy)({pickerOpened:!1}),mi(window,`click`,this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return y(this.colorPickerButtonRef())}get buttonStyle(){return H({background:this.props.currentColor})}},kE=class extends k{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:OE,ChartTitle:TE,Section:Z,SidePanelCollapsible:xE,RadioSelection:DE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinition(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),"defaultChartTitleFontSize?":W.number()},{defaultChartTitleFontSize:16});state;setup(){this.state=(0,t.proxy)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},AE=class extends k{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:tE};props=(0,t.props)(nE);get title(){let e=this.env.model.getters.getLocale();return j(`E.g. 1234567 -> %(value)s`,{value:z(1234567,{format:Hs({value:1234567},void 0,e),locale:e})})}},jE=class extends k{static template=`o-spreadsheet-ChartLegend`;static components={Section:Z,Select:t_};props=(0,t.props)({chartId:W.string(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function(),updateChart:W.function(),"isDisabled?":W.boolean()},{isDisabled:!1});updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:j(`None`)},{value:`top`,label:j(`Top`)},{value:`bottom`,label:j(`Bottom`)},{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}]}},ME=class extends k{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:xE,Section:Z,RoundColorPicker:OE,Select:t_};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())});state=(0,t.proxy)({dataSetId:this.getDataSeries()[0]?.dataSetId||``});getRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!e||!(`customizableSeries`in e))throw Error(`SeriesDesignEditor: chart runtime is not compatible with series customization.`);return e}getDataSeries(){return this.getRuntime().customizableSeries}updateEditedSeries(e){this.state.dataSetId=e}updateDataSeriesColor(e){let t={...this.props.definition.dataSetStyles};t[this.state.dataSetId]={...t[this.state.dataSetId],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSetStyles:t})}getDataSeriesColor(){let e=this.props.definition.dataSetStyles?.[this.state.dataSetId]?.backgroundColor,t=this.getDataSeries(),n=t.findIndex(e=>e.dataSetId===this.state.dataSetId);return e?uf(e):Hf(n,Uf(t.length))}updateDataSeriesLabel(e){let t=e.target.value,n={...this.props.definition.dataSetStyles};n[this.state.dataSetId]={...n[this.state.dataSetId],label:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesLabel(){return this.props.definition.dataSetStyles?.[this.state.dataSetId]?.label||this.getDataSeries().find(e=>e.dataSetId===this.state.dataSetId)?.label||``}get selectOptions(){return this.getDataSeries().map(({label:e,dataSetId:t})=>({value:t,label:e}))}},NE=class extends k{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:ME,Checkbox:tE,RadioSelection:DE,Section:Z,RoundColorPicker:OE,NumberInput:SE,Select:t_};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())});axisChoices=Ap;updateDataSeriesAxis(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSerieAxis(e){let t=this.props.definition.dataSetStyles;return t?.[e]&&t[e]?.yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e]?.trend,display:t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getTrendLineConfiguration(e){return this.props.definition.dataSetStyles?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n;switch(t){case`linear`:case`polynomial`:n={type:`polynomial`,order:t===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:n={type:t};break;default:return}this.updateTrendLineValue(e,n)}get trendOptions(){return[{value:`linear`,label:j(`Linear`)},{value:`polynomial`,label:j(`Polynomial`)},{value:`exponential`,label:j(`Exponential`)},{value:`logarithmic`,label:j(`Logarithmic`)},{value:`trailingMovingAverage`,label:j(`Trailing moving average`)}]}getPolynomialDegrees(e){return C(1,this.getMaxPolynomialDegree(e)+1).map(e=>({value:e.toString(),label:e.toString()}))}onChangePolynomialDegree(e,t){this.updateTrendLineValue(e,{order:parseInt(t)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId),n=t.customizableSeries.findIndex(t=>t.dataSetId===e);return Math.min(10,t.chartJsConfig.data.datasets[n].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSetStyles;if(!t?.[e])return``;let n=t[e]?.backgroundColor,r=this.env.model.getters.getChartRuntime(this.props.chartId),i=r.customizableSeries.findIndex(t=>t.dataSetId===e);return n?uf(n):Hf(i,Uf(r.customizableSeries.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Ef(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{...n[e]?.trend,...t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}},PE=class extends k{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:tE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([]),updateChart:W.function([]),"defaultValue?":W.boolean()})},FE=class extends k{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:kE,SidePanelCollapsible:xE,Section:Z,AxisDesignEditor:EE,SeriesWithAxisDesignEditor:NE,ChartLegend:jE,ChartShowValues:PE,ChartHumanizeNumbers:AE};props=(0,t.props)(nE);get axesList(){let{useLeftAxis:e,useRightAxis:t}=Dp(this.props.definition),n=[{id:`x`,name:j(`Horizontal axis`)}];return e&&n.push({id:`y`,name:j(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:j(e?`Right axis`:`Vertical axis`)}),n}},IE=class extends FE{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...FE.components,Checkbox:tE};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},LE=class extends IE{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}},RE=class extends k{static template=`o-spreadsheet-BubbleChartConfigPanel`;static components={ChartDataSeries:pE,ChartLabelRange:mE,ChartErrorSection:_E};props=(0,t.props)(nE);state=(0,t.proxy)({datasetDispatchResult:void 0,labelsDispatchResult:void 0,xRangeDispatchResult:void 0,sizeRangeDispatchResult:void 0});yRanges=[];labelRange;datasetOrientation;xRange;sizeRange;setup(){let e=this.props.definition;this.yRanges=e.yRanges||[],this.labelRange=e.labelRange,this.xRange=e.xRange,this.sizeRange=e.sizeRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.xRangeDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[],...this.state.sizeRangeDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>f_.Errors[e]||f_.Errors.Unexpected)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(`InvalidLabelRange`)}get isXDataInvalid(){return!!this.state.xRangeDispatchResult?.isCancelledBecause(`InvalidXRange`)}get isYDataInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(`InvalidYRange`)}get isBubbleSizeRangeInvalid(){return!!this.state.sizeRangeDispatchResult?.isCancelledBecause(`InvalidBubbleSizeRange`)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?j(`Use col %(column_name)s as headers`,{column_name:Cn(this.calculateHeaderPosition()||0)}):j(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getDataSeriesRanges(){return this.yRanges.map((e,t)=>({dataRange:e,dataSetId:`${t}`}))}onDataSeriesRangesChanged(e){this.yRanges=e,this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesConfirmed(){this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesReordered(e){this.yRanges=e.map(e=>this.yRanges[e]),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesRemoved(e){this.yRanges=this.yRanges.filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}onXDataRangeChanged(e){this.xRange=e[0],this.state.xRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{xRange:this.xRange})}onXDataRangeConfirmed(){this.state.xRangeDispatchResult=this.props.updateChart(this.props.chartId,{xRange:this.xRange})}onBubbleSizeRangeChanged(e){this.sizeRange=e[0],this.state.sizeRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{sizeRange:this.sizeRange})}onBubbleSizeRangeConfirmed(){this.state.sizeRangeDispatchResult=this.props.updateChart(this.props.chartId,{sizeRange:this.sizeRange})}getLabelRangeOptions(){let e=this.props.definition;return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}calculateHeaderPosition(){if(this.isYDataInvalid)return;let e=this.yRanges[0]??this.xRange??``,t=this.env.model.getters,n=Bl(t,t.getActiveSheetId(),e||``)?.zone;if(n)return this.datasetOrientation===`rows`?n.left:n.top+1}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.yRanges){let r=this.env.model.getters,i=Bl(r,r.getActiveSheetId(),n)?.zone;if(!i)return;i.top===i.bottom&&(e=!0),i.left===i.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}},zE=class extends k{static template=`o-spreadsheet-BubbleChartDesignPanel`;static components={GeneralDesignEditor:kE,SidePanelCollapsible:xE,Section:Z,AxisDesignEditor:EE,ChartLegend:jE,ChartShowValues:PE,ChartHumanizeNumbers:AE,RadioSelection:DE,RoundColorPicker:OE,Checkbox:tE};props=(0,t.props)(nE);get axesList(){return[{id:`x`,name:j(`Horizontal axis`)},{id:this.verticalAxisPosition===`right`?`y1`:`y`,name:j(`Vertical axis`)}]}colorModeChoices=[{value:`single`,label:j(`Single color`)},{value:`multiple`,label:j(`Multiple colors`)}];axisChoices=Ap;get colorMode(){return this.props.definition.bubbleColor.color===`multiple`?`multiple`:`single`}onColorModeChange(e){this.updateBubbleColor(e===`multiple`?`multiple`:Pf)}get verticalAxisPosition(){return this.props.definition.verticalAxisPosition??`left`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}updateBubbleColor(e){let t=this.props.definition.bubbleColor;this.props.updateChart(this.props.chartId,{bubbleColor:{...t,color:e}})}get currentBubbleColor(){return this.colorMode===`multiple`?Pf:this.props.definition.bubbleColor.color}get areBubblesTransparent(){return this.props.definition.bubbleColor.transparent||!1}updateBubbleTransparency(e){let t=this.props.definition.bubbleColor;this.props.updateChart(this.props.chartId,{bubbleColor:{...t,transparent:e}})}};function BE(e){return e=uf(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let VE=Symbol(`NULL`);function HE(e,t,n){let r=e.granularity||`month`;if(!(r in UE))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:VE;if(!UE[r].set.has(t)){UE[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=co(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(P(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(P(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}UE[r].values[i]=HS(e,a)}return UE[r].values[i]}let UE={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function WE(){for(let e in UE)UE[e].set.clear(),UE[e].values={}}let GE=Object.freeze({value:null}),KE=Object.freeze({value:0});function qE(e,{labelValues:t,dataSetsValues:n},r){let i=r.getLocale(),a=t.map(({value:e,format:t})=>z(e,{format:t,locale:i}));({labels:a,dataSetsValues:n}=bD(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=wD(a,n));let o=ED(e.dataSetStyles,n,`left`),s=ED(e.dataSetStyles,n,`right`),c=e.horizontal?{x:o||s}:{y:o,y1:s},l=[];for(let t in n){let{data:r,dataSetId:i}=n[t],a=e.dataSetStyles?.[i]?.trend;if(!a?.display||e.horizontal){l.push(void 0);continue}let o=oD(a,r);l.push(o)}return{dataSetsValues:n,trendDataSetsValues:l,axisFormats:c,labels:a,locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function JE(e,t){switch(t){case`day_of_week`:return ps[e-1].toString();case`hour_number`:{let t=String(e%12).padStart(2,`0`);return j(e<12?`%(hour)s AM`:`%(hour)s PM`,{hour:t})}case`month_number`:return fs[e-1].toString();case`iso_week_number`:return j(`W%(weekNumber)s`,{weekNumber:String(e).padStart(2,`0`)});case`quarter_number`:return j(`Q%(value)s`,{value:e});default:return e.toString()}}function YE(e,t,n,r,i){let a={},o=[],s=[],c=[];for(let l=0;l<e?.length;l++){let u=P(HE({granularity:n,type:`date`,displayName:`date`},e[l].value,R),i);u in a||(o.push(u),a[u]={});let d=P(HE({granularity:r,type:`date`,displayName:`date`},e[l].value,R),i);c.includes(d)||(s.push(d),c.push(d)),d in a[u]||(a[u][d]={value:0});let f=t[l];V(f)&&(a[u][d].value+=f.value)}return o.sort((e,t)=>e-t),s.sort((e,t)=>t-e),{dataSetsValues:s.map(e=>({data:o.map(t=>a?.[t]?.[e]),label:JE(e,r),hidden:!1,dataSetId:`0`})),labels:o.map(e=>({value:JE(e,n)}))}}function XE(e,{labelValues:t,dataSetsValues:n},r){let i=t,a=r.getLocale();({labels:i,dataSetsValues:n}=xD(i,n));let o={y:ED(e.dataSetStyles,n,`left`)};return{labels:i,dataSetsValues:n}=YE(i,n[0]?.data??[],e.horizontalGroupBy??`day_of_week`,e.verticalGroupBy??`hour_number`,a),{dataSetsValues:n,axisFormats:o,labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function ZE(e,{labelValues:t,dataSetsValues:n},r){let i=qE(e,{labelValues:t,dataSetsValues:n.slice(0,2)},r),a=i.dataSetsValues.filter(e=>!e.hidden),o=[];if(a[0]){let e=a[0].data.map(e=>V(e)&&e.value>0?e:KE);o.push({...a[0],data:e})}if(a[1]){let e=a[1].data.map(e=>V(e)&&e.value>0?{value:-e.value}:KE);o.push({...a[1],data:e})}return{...i,dataSetsValues:o}}function QE(e,{labelValues:t,dataSetsValues:n},r){let i=uD(e,{labelValues:t,dataSetsValues:n}),a=i===`linear`?t.map(({value:e})=>String(e??``)):t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:a,dataSetsValues:n}=bD(a,n)),i===`time`&&({labels:a,dataSetsValues:n}=yD(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=wD(a,n)),e.cumulative&&(n=DD(n,`asc`));let o={y:ED(e.dataSetStyles,n,`left`),y1:ED(e.dataSetStyles,n,`right`),x:TD(t)},s=[];for(let t in n){let{data:o,dataSetId:c}=n[t],l=e.dataSetStyles?.[c]?.trend;if(!l?.display){s.push(void 0);continue}s.push(sD(l,o,a,i,r.getLocale()))}return{dataSetsValues:n,axisFormats:o,labels:a,locale:r.getLocale(),trendDataSetsValues:s,axisType:i,topPadding:OD(e,r),background:Pp(e,r)}}function $E(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n)),{dataSetsValues:n,labels:i}=vD(i,n);let a=ED(e.dataSetStyles,n,`left`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function eD(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n));let a={r:ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`)};return{dataSetsValues:n,axisFormats:a,labels:i,locale:r.getLocale(),background:Pp(e,r)}}function tD(e,{labelValues:t,dataSetsValues:n},r){n=n.slice(0,1);let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=wD(i,n));let a=ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),availableRegions:r.getGeoChartAvailableRegions(),geoFeatureNameToId:r.geoFeatureNameToId,getGeoJsonFeatures:r.getGeoJsonFeatures,background:Pp(e,r)}}function nD(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n)),e.cumulative&&(n=DD(n,`desc`));let a=ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{x:a},labels:i,locale:r.getLocale(),background:Pp(e,r)}}function rD(e,{labelValues:t,dataSetsValues:n},r){let i=t;return{labels:i,dataSetsValues:n}=CD(i,n),{labels:i,dataSetsValues:n}=SD(i,n),{dataSetsValues:n,axisFormats:{y:TD(i)},labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),background:Pp(e,r)}}function iD(e,t){let n=aD(e,t),r=QE(e,n,t),i=e.labelRange?t.getVisibleRangeValues(e.labelRange):[],a=e.sizeRange?t.getVisibleRangeValues(e.sizeRange):[];n.shouldRemoveFirstLabel&&(i=i.slice(1),a=a.slice(1));let o=[],s=[],c=TD(a);for(let e=0;e<r.dataSetsValues[0].data.length;e++){let t=a[e]?.value,n=i[e],c=n?z(n.value,{format:n.format,locale:r.locale}):``,l=t===null?void 0:eo(t,r.locale);l!==void 0&&l<0&&(l=void 0),o.push(c?String(c):``),s.push(l)}let l=C(0,s.length).sort((e,t)=>{let n=s[e],r=s[t];return n===void 0&&r===void 0?0:n===void 0?1:r===void 0?-1:r-n});return r.dataSetsValues[0]={...r.dataSetsValues[0],data:l.map(e=>r.dataSetsValues[0].data[e])},{...r,axisFormats:{...r.axisFormats||{},size:c},labels:l.map(e=>r.labels[e]),bubbleLabels:l.map(e=>o[e]),bubbleSizes:l.map(e=>s[e])}}function aD(e,t){let n=e.yRanges[0],r=e.xRange?t.getVisibleRangeValues(e.xRange):n?Array.from({length:t.getVisibleRangeValues(n).length},()=>GE):[],i=n?t.getVisibleRangeValues(n):[],a=Tp(r.length,i.length,e.dataSetsHaveTitle||!1);return{labelValues:a?r.slice(1):r,dataSetsValues:[{dataSetId:`0`,label:``,data:a?i.slice(1):i}],shouldRemoveFirstLabel:a}}function oD(e,t){let n=[],r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e];V(a)&&(n.push(a.value),r.push(e+1)),i.push(e+1)}let a=cD(e,n,r,C(.5,i.length+.55,.2));return a.length?a:void 0}function sD(e,t,n,r,i){let a=[],o=[],s=[],c=t.length;if(c<2)return;switch(r){case`category`:for(let e=0;e<c;e++){let n=t[e];V(n)&&(a.push(n.value),o.push(e+1)),s.push(e+1)}break;case`linear`:for(let e=0;e<t.length;e++){let r=Number(n[e]);if(isNaN(r))continue;let i=t[e];V(i)&&(a.push(i.value),o.push(r)),s.push(r)}break;case`time`:for(let e=0;e<t.length;e++){let r=P({value:n[e]},i),c=t[e];V(c)&&(a.push(c.value),o.push(r)),s.push(r)}break}let l=Math.min(...s),u=Math.max(...s);if(u===l)return;let d=5*s.length,f=(u-l)/d,p=cD(e,a,o,C(l,u+f/2,f));if(p.length)return p}function cD(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=lD(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return r.map(e=>({x:e,y:NaN}));if(n===1)return dS([t],[i],[a],!0)[0].map((e,t)=>({x:r[t],y:e}));let o=oS(t,i,n,!0).flat();return a.map((e,t)=>({x:r[t],y:cS(o,e,n)}))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?lS(dS([e],[n],[a],!0))[0].map((e,t)=>({x:r[t],y:e})):r.map(e=>({x:e,y:NaN}))}case`logarithmic`:return dS([t],uS([i]),uS([a]),!0)[0].map((e,t)=>({x:r[t],y:e}));case`trailingMovingAverage`:return fS(t,n,e.window);default:return r.map(e=>({x:e,y:NaN}))}}catch{return r.map(e=>({x:e,y:NaN}))}}function lD(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function uD(e,t){return dD(e,t)&&_D()?`time`:fD(e,t)?`linear`:`category`}function dD(e,t){return!e.labelsAsText&&mD(t)}function fD(e,t){return!e.labelsAsText&&hD(t)}function pD(e){return mD(e)||hD(e)}function mD(e){if(!hD(e))return!1;let t=TD(e.labelValues);return!!(t&&Kp.test(t))}function hD(e){let t=e.labelValues;return!(t.some(e=>!V(e)&&e.value)||t.every(e=>!e.value))}let gD=!1;function _D(){if(!window.Chart)return!1;let e=new window.Chart._adapters._date({})._id===`luxon`;return!e&&!gD&&(gD=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),e}function vD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(e=>t.some(t=>V(t.data[e])&&t.data[e].value>0));return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])&&e.data[t].value>0?e.data[t]:GE)}))}}function yD(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=x(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=qt(n,e);for(let t of r)t.data[e]=GE}return{labels:n,dataSetsValues:r}}function bD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return r||i.some(V)});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])?e.data[t]:GE)}))}}function xD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return V(r)&&V(i[0])});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])?e.data[t]:GE)}))}}function SD(e,t){let n=Math.max(e.length,...t.map(e=>e.data?.length||0)),r=e=>e===null||e===``,i=C(0,n).filter(n=>{let i=t.map(e=>e.data?.[n]);if(r(i[0]?.value))return!1;let a=!1;for(let e of i)if(a||=r(e?.value),a&&!r(e?.value))return!1;return e[n]&&V(e[n])});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function CD(e,t){let n=[],r=[];for(let t=0;t<e.length;t++)Number(e[t].value)<=0?r.push(t):Number(e[t].value)>0&&n.push(t);let i=n.length?n:r;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function wD(e,t){let n=e=>typeof e==`number`?e:0,r=new Set(e),i={};r.forEach(e=>{i[e]=Array(t.length)});for(let r of C(0,e.length)){let a=e[r];for(let e of C(0,t.length)){let o=t[e].data[r];i[a][e]?i[a][e].value+=n(o?.value):i[a][e]={...o,value:n(o?.value)}}}return{labels:Array.from(r),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(r).map(e=>i[e][t])}))}}function TD(e){return e.find(({format:e})=>e!==void 0)?.format}function ED(e,t,n){let r=t.filter(t=>n===`right`==(e?.[t.dataSetId]?.yAxisId===`y1`));for(let e of r){let t=e.data.find(({format:e})=>e!==void 0&&!Os(e));if(t)return t.format}}function DD(e,t){return e.map(e=>{let n=[],r=0,i=t===`asc`?C(0,e.data.length):C(0,e.data.length).reverse();for(let t of i){let i=e.data[t];V(i)?(r+=i.value,n[t]={...i,value:r}):n[t]=GE}return{...e,data:n}})}function OD(e,t){let{title:n,legendPosition:r}=e,i=n&&n.text||r===`top`;return t.isDashboard()&&!i?30:0}function kD(e,t){return{padding:{left:20,right:20,top:Math.max(15,t.topPadding||0),bottom:10}}}function AD(e,t){let n=e.legendPosition;return{padding:{left:20+(n===`left`?70:0),right:20+(n===`right`?70:0),top:Math.max(15,t.topPadding||0),bottom:10}}}let jD=.2;function MD(e,t){let n=e.datasetIndex;for(let e=0;e<t.length;e++){if(e===n)continue;let r=t[e];for(let t of[`borderColor`,`backgroundColor`])t in r&&(r[t]=Ef(r[t],e===n?1:jD))}}function ND(e){for(let t of e)for(let e of[`borderColor`,`backgroundColor`])e in t&&(t[e]=Ef(t[e],1))}function PD(e,t){let n=e.datasetIndex;for(let e=0;e<t.length;e++){let r=t[e],i=Ef(r.borderColor,e===n?1:jD);r.borderColor=i,r.pointBackgroundColor=i,r.backgroundColor=Ef(r.backgroundColor,tt*(e===n?1:jD))}}function FD(e){for(let t of e){let e=Ef(t.borderColor,1);t.borderColor=e,t.pointBackgroundColor=e,t.backgroundColor=Ef(t.backgroundColor,tt)}}function ID(e,t){let n=t.datasetIndex;n!==void 0&&(e.isDatasetVisible(n)?e.hide(n):e.show(n))}function LD(e,t){for(let n of t){let t=n.backgroundColor;if(!t)return;t.forEach((t,n,r)=>{r[n]=Ef(t,n===e.index?1:jD)})}}function RD(e){for(let t of e){let e=t.backgroundColor;if(!e)return;e.forEach((e,t,n)=>{n[t]=Ef(e,1)})}}function zD(e,t){let n=t.index;n!==void 0&&e.toggleDataVisibility(n)}function BD({legendPosition:e}){return{display:e!==`none`,position:e===`none`?void 0:e}}function VD(e,t){return{...ZD({highlightItem:MD,unHighlightItems:ND,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{lineWidth:3})}}function HD(e,t){return{...BD(e),...$D(xp(e.background),{pointStyle:`rect`,lineWidth:3})}}function UD(e,t){let n=e.fillArea,r=n?`rect`:`line`,i=n?2:3;return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{pointStyle:r,lineWidth:i})}}function WD(e,t){let{dataSetsValues:n}=t,r=jp(new Gf(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n),i=xp(e.background);return{...ZD({highlightItem:LD,unHighlightItems:RD,toggleDataVisibility:zD}),...BD(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((t,n)=>({text:Mp(String(t)),strokeStyle:r[n],fillStyle:r[n],pointStyle:`rect`,lineWidth:2,fontColor:i,index:n,hidden:!e.getDataVisibility?.(n)}))||[]).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function GD(e,t){return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...tO(xp(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8})}}function KD(e,t){return e.bubbleColor.color===`multiple`?{...QD,...BD(e),...eO(xp(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8},t.bubbleLabels)}:{display:!1}}function qD(e,t){return{...ZD({highlightItem:MD,unHighlightItems:ND,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{lineWidth:3})}}function JD(e,t){let n=xp(e.background),r=e.negativeValuesColor||`#EA6175`,i=e.positiveValuesColor||`#4EA7F2`,a=e.subTotalValuesColor||`#AAAAAA`;return{...BD(e),labels:{usePointStyle:!0,generateLabels:()=>{let t=[{text:j(`Positive values`),fontColor:n,fillStyle:i,strokeStyle:i,pointStyle:`rect`},{text:j(`Negative values`),fontColor:n,fillStyle:r,strokeStyle:r,pointStyle:`rect`}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:j(`Subtotals`),fontColor:n,fillStyle:a,strokeStyle:a,pointStyle:`rect`}),t},filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0},onClick:()=>{}}}function YD(e,t){let n=e.fillArea??!1,r=n?`rect`:`line`,i=n?2:3;return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{pointStyle:r,lineWidth:i})}}function XD(e,t){let n=xp(e.background);return{...BD(e),labels:{usePointStyle:!0,generateLabels:e=>{let t=e.data.datasets.at(-1);return t?t.groupColors.map(({color:e,label:t})=>({text:Mp(t),fontColor:n,fillStyle:e,strokeStyle:e,pointStyle:`rect`})):[]}}}}function ZD({highlightItem:e,unHighlightItems:t,toggleDataVisibility:n}){return{onHover:(t,n,r)=>{if(!n.hidden){let t=r.chart.data.datasets;e(n,t),r.chart.update()}let i=t.native?.target;i&&i instanceof HTMLElement&&(i.style.cursor=`pointer`)},onLeave:(e,n,r)=>{if(!n.hidden){let e=r.chart.data.datasets;t(e),r.chart.update()}let i=e.native?.target;i&&i instanceof HTMLElement&&(i.style.cursor=`default`)},onClick:(r,i,a)=>{r.type!==`click`||!a.legendItems||(a.chart.options.animation&&(a.chart.options.animation=!1),n(a.chart,i),i.hidden?e(i,a.chart.data.datasets):t(a.chart.data.datasets),a.chart.update(),r.native.preventDefault(),r.native.stopPropagation())}}}let QD={...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),onClick:(e,t,n)=>{if(e.type!==`click`)return;let r=t.datasetIndex;if(r===void 0)return;let i=n.chart.getDatasetMeta(0),a=i.data[r].hidden;i.data[r].hidden=!a,n.chart.update(),e.native.preventDefault(),e.native.stopPropagation()}};function $D(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>Np(r.xAxisID)?{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.backgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:r.type===`line`?`line`:`rect`,datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function eO(e,t,n){return{labels:{color:e,usePointStyle:!0,generateLabels:r=>{if(!r.data.datasets[0])return[];let i=r.data.datasets[0].backgroundColor,a=typeof i==`string`?r.data.datasets[0].data.map(()=>i):i;return r.data.datasets[0].data.map((i,o)=>({text:n[o],fontColor:e,strokeStyle:a?.[o],fillStyle:a?.[o],hidden:r.getDatasetMeta(0).data[o].hidden,pointStyle:`rect`,datasetIndex:o,...t})).filter(e=>e.text)},filter:(e,t)=>!0}}}function tO(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>Np(r.xAxisID)?{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.pointBackgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:`circle`,datasetIndex:i,lineWidth:8,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}let nO={showValues:!1,showLabels:!0,valuesDesign:{align:`center`,fontSize:13}};function rO(e,t){let{axisFormats:n,locale:r}=t;return{type:e.type,horizontal:`horizontal`in e&&e.horizontal,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i)=>{let a=cO(e,i);return Op(n,r,e.humanize)(t,a)}}}function iO(e,t){let{locale:n,axisFormats:r}=t,i=(t,n,r)=>e.background,a=t.dataSetsValues.flat().flatMap(e=>e?.data.filter(V)).map(e=>e.value);if(a.length){let t=Math.min(...a),n=Math.max(...a),r=pm(e.colorScale??cC(`oranges`),t,n);i=(t,n,i)=>{let a=n._dataset.values[i];return a===void 0?e.background:xp(r(a))}}return{type:`calendar`,horizontal:!1,showValues:`showValues`in e?!!e.showValues:!1,background:i,callback:(e,t,i)=>{let a=t._dataset.values[i];return a===void 0?``:Vs({value:a,format:r?.y},n)}}}function aO(e,t){let{axisFormats:n,locale:r}=t;return{callback:Op(n,r,e.humanize),showLabels:e.showLabels??nO.showLabels,showValues:e.showValues??nO.showValues,style:{fontSize:Rd(e.valuesDesign?.fontSize??nO.valuesDesign.fontSize),align:e.valuesDesign?.align??nO.valuesDesign.align,bold:e.valuesDesign?.bold??nO.valuesDesign.bold,italic:e.valuesDesign?.italic??nO.valuesDesign.italic,textColor:e.valuesDesign?.color??nO.valuesDesign.color}}}function oO(e,t){let{axisFormats:n,locale:r}=t;return{type:`pyramid`,horizontal:!0,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(e,t)=>(e=Math.abs(Number(e)),e===0?``:Op(n,r)(e,t.xAxisID||`x`))}}function sO(e,t){let{axisFormats:n,locale:r,dataSetsValues:i}=t,a=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:`waterfall`,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i,o)=>{let s=i._dataset.data[o],c=s[1]-s[0],l=c>=0?`+`:``;return e.showSubTotals&&a.includes(o)&&l===`+`&&(l=``),`${l}${Op(n,r,e.humanize)(c,i.yAxisID)}`}}}function cO(e,t){return t.rAxisID?t.rAxisID:(`horizontal`in e&&e.horizontal?t.xAxisID:t.yAxisID)||`y`}function lO({title:e,legendPosition:t,background:n},r){let i=Sp(n);return{display:!!e.text,text:e.text?r.dynamicTranslate(e.text):``,color:e?.color??i,align:e.align===`center`?`center`:e.align===`right`?`end`:`start`,font:{size:Rd(e.fontSize??16),weight:e.bold?`bold`:`normal`,style:e.italic?`italic`:`normal`},padding:{bottom:t===`top`?0:20}}}let uO;function dO(e,t={}){return fO(e,t).innerHTML}function fO(e,n={}){uO||=new t.App({templates:`
38
+ `))}extractAttr(e,t,n){let r=e.attributes[t];r||this.handleMissingValue(e,`attribute "${t}"`,n);let i=r?.value?r.value:n?.default;return i===void 0?void 0:new hx(i)}extractTextContent(e,t){if(t?.default!==void 0&&typeof t.default!=`string`)throw Error(`extractTextContent default value should be a string`);let n=e?.attributes[`xml:space`]?.value===`preserve`,r=e?.textContent;return(!e||r===null)&&this.handleMissingValue(e,`text content`,t),r&&=n?r:r.trim(),r?xy(r):t?.default}extractChildAttr(e,t,n,r){let i;i=typeof t==`number`?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,typeof t==`number`?`child at index ${t}`:`child <${t}>`,r);let a=i?this.extractAttr(i,n,r)?.asString():r?.default;return a===void 0?void 0:new hx(a)}extractChildTextContent(e,t,n){if(n?.default!==void 0&&typeof n.default!=`string`)throw Error(`extractTextContent default value should be a string`);let r=this.querySelector(e,t);return r||this.handleMissingValue(e,`child <${t}>`,n),r?this.extractTextContent(r,n):n?.default}handleMissingValue(e,t,n){if(n?.required)if(n?.default!==void 0)this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${n.default}`);else throw Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`)}extractColor(e,t,n){if(!e)return n?{rgb:n}:void 0;let r=this.extractAttr(e,`theme`)?.asString(),i;if(r!==void 0){if(!t||!t.clrScheme)throw Error(`Color referencing a theme but no theme was provided`);i=this.getThemeColor(r,t.clrScheme)}else i=this.extractAttr(e,`rgb`)?.asString(),i=i===`FF000000`?void 0:i;return{rgb:i||n,auto:this.extractAttr(e,`auto`)?.asBool(),indexed:this.extractAttr(e,`indexed`)?.asNum(),tint:this.extractAttr(e,`tint`)?.asNum()}}getTargetXmlFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!n||!n.file)throw Error(`Cannot find target file`);return n}getTargetImageFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!n)throw Error(`Cannot find target file`);return n}querySelector(e,t){let n=mx(t);return e.querySelector(n)}querySelectorAll(e,t){let n=mx(t);return e.querySelectorAll(n)}getThemeColor(e,t){switch(e){case`0`:return`FFFFFF`;case`1`:return`000000`;case`2`:return t[3].value;case`3`:return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,``)}},_x=class extends gx{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`externalBook`},e=>({rId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:`sheetName`},e=>this.extractAttr(e,`val`,{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:`sheetData`},e=>{let t=this.mapOnElements({parent:e,query:`cell`},e=>({xc:this.extractAttr(e,`r`,{required:!0}).asString(),value:this.extractChildTextContent(e,`v`,{required:!0})})),n={};for(let e of t)n[e.xc]=e.value;return{sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asNum(),data:n}})}},vx=class extends gx{getTheme(){return{clrScheme:this.mapOnElements({query:`a:clrScheme`,parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,`val`,{required:!0,default:$f}).asString(),lastClr:this.extractChildAttr(e,0,`lastClr`,{default:$f}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`si`},e=>this.mapOnElements({parent:e,query:`t`},e=>this.extractTextContent(e)||``).join(``))}getNamedRanges(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`definedNames definedName`},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),value:this.extractTextContent(e)||``}))}},yx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractConditionalFormattings(){let e=this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > conditionalFormatting`},e=>({sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),pivot:this.extractAttr(e,`pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:`extLst x14:conditionalFormatting`},e=>({sqref:this.extractChildTextContent(e,`xm:sqref`,{required:!0}).split(` `),pivot:this.extractAttr(e,`xm:pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:`cfRule, x14:cfRule`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),priority:this.extractAttr(e,`priority`,{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,`dxfId`)?.asNum(),stopIfTrue:this.extractAttr(e,`stopIfTrue`)?.asBool(),aboveAverage:this.extractAttr(e,`aboveAverage`)?.asBool(),percent:this.extractAttr(e,`percent`)?.asBool(),bottom:this.extractAttr(e,`bottom`)?.asBool(),operator:this.extractAttr(e,`operator`)?.asString(),text:this.extractAttr(e,`text`)?.asString(),timePeriod:this.extractAttr(e,`timePeriod`)?.asString(),rank:this.extractAttr(e,`rank`)?.asNum(),stdDev:this.extractAttr(e,`stdDev`)?.asNum(),equalAverage:this.extractAttr(e,`equalAverage`)?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:`formula`},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){let n=this.querySelector(e,`colorScale`);if(n)return{colors:this.mapOnElements({parent:n,query:`color`},e=>this.extractColor(e,t,`ffffff`)),cfvos:this.extractCFVos(n)}}extractCfDataBar(e,t){let n=this.querySelector(e,`dataBar`);if(n)return{color:this.extractColor(n.querySelector(`color`),t,`EFF7FF`),cfvos:this.extractCFVos(n)}}extractCfIconSet(e){let t=this.querySelector(e,`iconSet, x14:iconSet`);if(t)return{iconSet:this.extractAttr(t,`iconSet`,{default:`3TrafficLights1`}).asString(),showValue:this.extractAttr(t,`showValue`,{default:!0}).asBool(),percent:this.extractAttr(t,`percent`,{default:!0}).asBool(),reverse:this.extractAttr(t,`reverse`)?.asBool(),custom:this.extractAttr(t,`custom`)?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){let t=this.mapOnElements({parent:e,query:`cfIcon, x14:cfIcon`},e=>({iconSet:this.extractAttr(e,`iconSet`,{required:!0}).asString(),iconId:this.extractAttr(e,`iconId`,{required:!0}).asNum()}));return t.length===0?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:`cfvo, x14:cfvo`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),gte:this.extractAttr(e,`gte`,{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,`val`)?.asString():this.extractChildTextContent(e,`f, xm:f`)}))}},bx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > dataValidations > dataValidation`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),operator:this.extractAttr(e,`operator`,{default:`between`})?.asString(),sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),errorStyle:this.extractAttr(e,`errorStyle`)?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,`showErrorMessage`)?.asBool(),errorTitle:this.extractAttr(e,`errorTitle`)?.asString(),error:this.extractAttr(e,`error`)?.asString(),showInputMessage:this.extractAttr(e,`showInputMessage`)?.asBool(),promptTitle:this.extractAttr(e,`promptTitle`)?.asString(),prompt:this.extractAttr(e,`prompt`)?.asString(),allowBlank:this.extractAttr(e,`allowBlank`)?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}},xx=class extends gx{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`c:chartSpace`},e=>{let t=this.getChartType(e);if(!hv[t])throw Error(`Unsupported chart type ${t}`);if(hv[t]===`combo`)return this.extractComboChart(e);let n=this.mapOnElements({parent:e,query:`c:chart > c:title a:t`},e=>e.textContent||``).join(``),r=this.extractTitleStyle(e,`c:chart > c:title a:p a:pPr a:defRPr`),i=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),a=this.extractChildAttr(e,`c:barDir`,`val`,{default:`col`}).asString(),o=this.extractChildAttr(e,`c:holeSize`,`val`,{default:`0`}).asNum(),s=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:n,...r},type:hv[t],axesDesign:this.extractAxesDesign(e),dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:mv[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:i===`stacked`,fontColor:`000000`,horizontal:a===`bar`,isDoughnut:o>0,pieHolePercentage:o,showValues:s}})[0]}extractLabelRange(e,t){return e===`scatterChart`?this.extractChildTextContent(t,`c:ser c:strRef c:f`)||this.extractChildTextContent(t,`c:ser c:numRef c:f`):this.extractChildTextContent(t,`c:ser c:cat c:f`)}extractComboChart(e){let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``),n=this.extractTitleStyle(e,`c:chart > c:title a:p a:pPr a:defRPr`),r=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString(),i=[...this.querySelectorAll(e,`c:chart c:showVal`)].some(e=>e.attributes.getNamedItem(`val`)?.value===`1`);return{title:{text:t,...n},type:`combo`,axesDesign:this.extractAxesDesign(e),dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,`c:barChart`),`comboChart`),...this.extractChartDatasets(this.querySelectorAll(e,`c:lineChart`),`comboChart`)],labelRange:this.extractChildTextContent(e,`c:ser c:cat c:f`),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:mv[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:r===`stacked`,fontColor:`000000`,showValues:i}}extractTitleStyle(e,t){let n=this.querySelector(e,t);if(!n)return{};let r=n.getAttribute(`b`),i=r===`1`||r===`true`?!0:void 0,a=n.getAttribute(`i`),o=a===`1`||a===`true`?!0:void 0,s=n.getAttribute(`sz`);return{bold:i,italic:o,fontSize:s?Math.round(parseInt(s)/100):void 0,color:this.extractDrawingFillColor(n)}}extractDrawingFillColor(e){let t=this.querySelector(e,`a:solidFill a:srgbClr`);if(t){let e=t.getAttribute(`val`);return e&&df(e)?uf(e):void 0}let n=this.querySelector(e,`a:solidFill a:schemeClr`);if(n){let e=n.getAttribute(`val`);if(e)return this.resolveSchemeColor(e)}}resolveSchemeColor(e){let t=this.xlsxFileStructure.theme;if(!t)return;let n=this.querySelector(t.file.xml,`a:clrScheme a:${e}`);if(!n)return;let r=this.querySelector(n,`a:srgbClr`);if(r){let e=r.getAttribute(`val`);return e&&df(e)?uf(e):void 0}let i=this.querySelector(n,`a:sysClr`);if(i){let e=i.getAttribute(`lastClr`);return e&&df(e)?uf(e):void 0}}extractAxisTitleDesign(e){if(e===null)return;let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``);if(t)return{text:t,...this.extractTitleStyle(e,`c:title a:p a:pPr a:defRPr`)}}extractAxesDesign(e){let t=this.querySelector(e,`c:catAx`),n=this.querySelector(e,`c:valAx`),r=t?this.extractChildAttr(t,`c:axPos`,`val`)?.asString():void 0,i=r===`l`||r===`r`,a=i?n:t,o=i?t:n,s=this.extractAxisTitleDesign(a),c=this.extractAxisTitleDesign(o);if(!s&&!c)return;let l={};return s&&(l.x={title:s}),c&&(l.y={title:c}),l}extractChartDatasets(e,t){return Array.from(e).map(e=>t===`scatterChart`?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}let r=this.querySelectorAll(e,`c:spPr a:solidFill`),i=r.length?this.querySelector(r[0],`a:srgbClr`):void 0,a=i?i.getAttribute(`val`):void 0;return{label:t,range:this.extractChildTextContent(e,`c:val c:f`,{required:!0}),backgroundColor:a&&df(a)?`${uf(a)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){let t=this.querySelector(e,`c:trendline`);if(!t)return;let n=this.extractChildAttr(t,`c:trendlineType`,`val`),r=this.extractChildAttr(t,`a:solidFill a:srgbClr`,`val`);return{type:n?n.asString():void 0,order:this.extractChildAttr(t,`c:order`,`val`)?.asNum(),window:this.extractChildAttr(t,`c:period`,`val`)?.asNum(),color:r&&df(r.asString())?`${uf(r.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.querySelectorAll(e,`c:spPr a:solidFill a:srgbClr`),r=n.length?n[0].getAttribute(`val`):void 0,i=this.extractChildTextContent(e,`c:tx c:f`);if(i)t={reference:i};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}return{label:t,range:this.extractChildTextContent(e,`c:yVal c:f`,{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:r&&df(r)?`${uf(r)}`:void 0}})}getChartType(e){let t=this.querySelector(e,`c:plotArea`);if(!t)throw Error(`Missing plot area in the chart definition.`);let n;for(let e of t.children){let t=fx(e.tagName);V_.some(e=>e===t)&&(n?n!==t&&(n=`comboChart`):n=t)}if(n)return n;throw Error(`Unknown chart type`)}};let Sx=`oneCellAnchor`,Cx=`twoCellAnchor`;var wx=class extends gx{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`xdr:wsDr`,children:!0},e=>{let t=fx(e.tagName),n=this.extractFigureAnchorsByType(e,t),r=this.querySelector(e,`c:chart`),i=this.querySelector(e,`a:blip`);if(!r&&!i)throw Error(`Only chart and image figures are currently supported.`);return{anchors:n,data:r?this.extractChart(r):this.extractImage(e),figureSize:t===Sx?this.extractFigureSizeFromSizeTag(e,`xdr:ext`):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case Sx:return[this.extractFigureAnchor(`xdr:from`,e)];case Cx:return[this.extractFigureAnchor(`xdr:from`,e),this.extractFigureAnchor(`xdr:to`,e)];default:throw Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){let n=this.querySelector(e,t);if(!n)throw Error(`Missing size element '${t}'`);return{cx:this.extractAttr(n,`cx`,{required:!0}).asNum(),cy:this.extractAttr(n,`cy`,{required:!0}).asNum()}}extractFigureAnchor(e,t){let n=this.querySelector(t,e);if(!n)throw Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(n,`xdr:col`,{required:!0})),colOffset:Number(this.extractChildTextContent(n,`xdr:colOff`,{required:!0})),row:Number(this.extractChildTextContent(n,`xdr:row`,{required:!0})),rowOffset:Number(this.extractChildTextContent(n,`xdr:rowOff`,{required:!0}))}}extractChart(e){let t=this.extractAttr(e,`r:id`,{required:!0}).asString(),n=new xx(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw Error(`Unable to extract chart definition`);return n}extractImage(e){let t=this.querySelector(e,`a:blip`),n=this.extractAttr(t,`r:embed`,{required:!0}).asString(),r=this.getTargetImageFile(this.relationships[n]);if(!r)throw Error(`Unable to extract image`);let i=r.fileName.split(`.`).at(-1),a=fx(e.tagName),o=a===Cx?this.querySelector(e,`a:xfrm`):e,s=a===Cx?`a:ext`:`xdr:ext`,c=this.extractFigureSizeFromSizeTag(o,s);return{imageSrc:r.imageSrc,mimetype:i?Sv[i]:void 0,size:c}}},Tx=class extends gx{getPivotTable(){return this.mapOnElements({query:`:root`,parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,`rowGrandTotals`,{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:`location`,parent:e},e=>({ref:this.extractAttr(e,`ref`,{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,`firstHeaderRow`,{required:!0}).asNum(),firstDataRow:this.extractAttr(e,`firstDataRow`,{required:!0}).asNum(),firstDataCol:this.extractAttr(e,`firstDataCol`,{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:`pivotTableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),showRowHeaders:this.extractAttr(e,`showRowHeaders`,{required:!0}).asBool(),showColHeaders:this.extractAttr(e,`showColHeaders`,{required:!0}).asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`,{required:!0}).asBool(),showColStripes:this.extractAttr(e,`showColStripes`,{required:!0}).asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool()}))[0]}},Ex=class extends gx{getTable(){return this.mapOnElements({query:`table`,parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,`displayName`,{required:!0}).asString(),name:this.extractAttr(e,`name`)?.asString(),id:this.extractAttr(e,`id`,{required:!0}).asString(),ref:this.extractAttr(e,`ref`,{required:!0}).asString(),headerRowCount:this.extractAttr(e,`headerRowCount`,{default:1}).asNum(),totalsRowCount:this.extractAttr(e,`totalsRowCount`,{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:`tableColumn`,parent:e},e=>({id:this.extractAttr(e,`id`,{required:!0}).asString(),name:this.extractAttr(e,`name`,{required:!0}).asString(),colFormula:this.extractChildTextContent(e,`calculatedColumnFormula`)}))}extractTableStyleInfo(e){return this.mapOnElements({query:`tableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`)?.asString(),showFirstColumn:this.extractAttr(e,`showFirstColumn`)?.asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`)?.asBool(),showColumnStripes:this.extractAttr(e,`showColumnStripes`)?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:`autoFilter`,parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,`ref`,{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:`tableColumn`,parent:e},t=>({colId:this.extractAttr(e,`colId`,{required:!0}).asNum(),hiddenButton:this.extractAttr(e,`hiddenButton`,{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:`filter`,parent:e},e=>({val:this.extractAttr(e,`val`,{required:!0}).asString()}))}},Dx=class extends gx{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}getSheet(){return this.mapOnElements({query:`worksheet`,parent:this.rootFile.file.xml},e=>{let t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:t.state===`visible`,isLocked:this.extractProtection(e)}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:`sheetView`},e=>{let t=this.querySelector(e,`pane`);return{tabSelected:this.extractAttr(e,`tabSelected`,{default:!1}).asBool(),showFormulas:this.extractAttr(e,`showFormulas`,{default:!1}).asBool(),showGridLines:this.extractAttr(e,`showGridLines`,{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,`showRowColHeaders`,{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,`xSplit`,{default:0}).asNum():0,ySplit:t?this.extractAttr(t,`ySplit`,{default:0}).asNum():0}}})}extractSheetName(){let e=yy(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,`sheet`))if(e.attributes[`r:id`].value===t)return e.attributes.name.value;throw Error(`Missing sheet name`)}getSheetWorkbookInfo(){let e=yy(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,n=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:`sheet`},e=>({relationshipId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asString(),sheetName:this.extractAttr(e,`name`,{required:!0}).asString(),state:this.extractAttr(e,`state`,{default:`visible`}).asString()})).find(e=>e.relationshipId===t);if(!n)throw Error(`Cannot find corresponding workbook sheet`);return n}extractConditionalFormats(){return new yx(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new bx(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:`drawing`},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new wx(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:`tablePart`,parent:e},e=>{let t=this.extractAttr(e,`r:id`,{required:!0})?.asString();return new Ex(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith(`pivotTable`)).map(e=>new Tx(this.getTargetXmlFile(e),this.xlsxFileStructure,this.warningManager).getPivotTable())}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:`mergeCell`},e=>this.extractAttr(e,`ref`,{required:!0}).asString())}extractSheetFormat(e){let t=this.querySelector(e,`sheetFormatPr`);if(t)return{defaultColWidth:this.extractAttr(t,`defaultColWidth`,{default:`8.43`}).asNum(),defaultRowHeight:this.extractAttr(t,`defaultRowHeight`,{default:`12.75`}).asNum()}}extractSheetProperties(e){let t=this.querySelector(e,`sheetPr`);if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,`tabColor`),this.theme)}}extractSheetOutlineProperties(e){let t=this.querySelector(e,`outlinePr`);if(t)return{summaryBelow:this.extractAttr(t,`summaryBelow`,{default:!0}).asBool(),summaryRight:this.extractAttr(t,`summaryRight`,{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:`cols col`},e=>({width:this.extractAttr(e,`width`)?.asNum(),customWidth:this.extractAttr(e,`customWidth`)?.asBool(),bestFit:this.extractAttr(e,`bestFit`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),min:this.extractAttr(e,`min`,{required:!0})?.asNum(),max:this.extractAttr(e,`max`,{required:!0})?.asNum(),styleIndex:this.extractAttr(e,`style`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractRows(e){let t=new Set;return this.mapOnElements({parent:e,query:`sheetData row`},e=>({index:this.extractAttr(e,`r`,{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,`ht`)?.asNum(),customHeight:this.extractAttr(e,`customHeight`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),styleIndex:this.extractAttr(e,`s`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:`c`},e=>{let n=this.extractAttr(e,`r`,{required:!0})?.asString(),r=this.extractCellFormula(e);if(r?.ref&&r.sharedIndex===void 0){let e=Wn(r.ref);for(let{col:r,row:i}of dr(e)){let e=E(r,i);e!==n&&t.add(e)}}let i=t.has(n);return{xc:n,styleIndex:this.extractAttr(e,`s`)?.asNum(),type:av[this.extractAttr(e,`t`,{default:`n`})?.asString()],value:i?void 0:this.extractChildTextContent(e,`v`)??void 0,formula:i?void 0:r}})}extractCellFormula(e){let t=this.querySelector(e,`f`);if(!t)return;let n=this.extractTextContent(t),r=this.extractAttr(t,`si`)?.asNum(),i=this.extractAttr(t,`ref`)?.asString();if(!((n===void 0||n.trim()===``)&&r===void 0))return{content:n,sharedIndex:r,ref:i}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:`hyperlink`},e=>{let t=this.extractAttr(e,`r:id`)?.asString();return{xc:this.extractAttr(e,`ref`,{required:!0})?.asString(),location:this.extractAttr(e,`location`)?.asString(),display:this.extractAttr(e,`display`)?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){let t=this.querySelectorAll(e,`f[si][ref]`),n={};for(let e of t){let t=this.extractAttr(e,`si`,{required:!0}).asNum();n[t]=this.extractTextContent(e,{required:!0})}let r=[];for(let e=0;e<Object.keys(n).length;e++)n[e]?r.push(n[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),r.push(``));return r}extractProtection(e){let t=this.querySelector(e,`sheetProtection`);return t?this.extractAttr(t,`sheet`,{default:!1}).asBool():!1}},Ox=class extends gx{theme;constructor(e,t,n){super(e.styles,e,t),this.theme=n}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`numFmt`},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,`numFmtId`,{required:!0}).asNum(),format:this.extractAttr(e,`formatCode`,{required:!0,default:``}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`font`},e=>this.extractFont(e))}extractFont(e){let t=this.extractChildAttr(e,`name`,`val`,{default:`Arial`}).asString(),n=this.extractChildAttr(e,`sz`,`val`,{default:Je.toString()}).asNum(),r=this.extractColor(this.querySelector(e,`color`),this.theme),i=this.querySelector(e,`i`)||void 0,a=i&&i.attributes.val?.value!==`0`,o=this.querySelector(e,`b`)||void 0,s=o&&o.attributes.val?.value!==`0`,c=this.querySelector(e,`strike`)||void 0,l=c&&c.attributes.val?.value!==`0`,u=this.querySelector(e,`u`)||void 0;return{name:t,size:n,color:r,italic:a,bold:s,underline:u&&u.attributes.val?.value!==`none`,strike:l}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`fill`},e=>this.extractFill(e))}extractFill(e){let t=e.children[0];return t.tagName===`patternFill`?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,`bgColor`),this.theme),fgColor:this.extractColor(this.querySelector(t,`fgColor`),this.theme)}:{patternType:`solid`,fgColor:this.extractColor(this.querySelectorAll(t,`color`)[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`border`},e=>this.extractBorder(e))}extractBorder(e){let t={left:this.extractSingleBorder(e,`left`,this.theme),right:this.extractSingleBorder(e,`right`,this.theme),top:this.extractSingleBorder(e,`top`,this.theme),bottom:this.extractSingleBorder(e,`bottom`,this.theme),diagonal:this.extractSingleBorder(e,`diagonal`,this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,`diagonalUp`)?.asBool(),t.diagonalDown=this.extractAttr(e,`diagonalDown`)?.asBool()),t}extractSingleBorder(e,t,n){let r=this.querySelector(e,t);if(!(!r||!r.attributes.style))return{style:this.extractAttr(r,`style`,{required:!0,default:`thin`}).asString(),color:this.extractColor(r.children[0],n,`000000`)}}extractAlignment(e){return{horizontal:this.extractAttr(e,`horizontal`,{default:`general`}).asString(),vertical:this.extractAttr(e,`vertical`,{default:`bottom`}).asString(),textRotation:this.extractAttr(e,`textRotation`)?.asNum(),wrapText:this.extractAttr(e,`wrapText`)?.asBool(),indent:this.extractAttr(e,`indent`)?.asNum(),relativeIndent:this.extractAttr(e,`relativeIndent`)?.asNum(),justifyLastLine:this.extractAttr(e,`justifyLastLine`)?.asBool(),shrinkToFit:this.extractAttr(e,`shrinkToFit`)?.asBool(),readingOrder:this.extractAttr(e,`readingOrder`)?.asNum()}}getDxfs(){return this.mapOnElements({query:`dxf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`font`),n=this.querySelector(e,`fill`),r=this.querySelector(e,`border`),i=this.querySelector(e,`numFmt`),a=this.querySelector(e,`alignment`);return{font:t?this.extractFont(t):void 0,fill:n?this.extractFill(n):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:a?this.extractAlignment(a):void 0,border:r?this.extractBorder(r):void 0}})}getStyles(){return this.mapOnElements({query:`cellXfs xf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`alignment`);return{fontId:this.extractAttr(e,`fontId`,{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,`fillId`,{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,`borderId`,{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,`numFmtId`,{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}};function kx(e,t){return Ax(jx(e,t),t)}function Ax(e,t){let n=[];for(let r of e){let e=Mx(r,t);n.push({file:{fileName:r,xml:t[r]},rels:e?{fileName:e,xml:t[e]}:void 0})}return n}function jx(e,t){let n=t[`[Content_Types].xml`].querySelectorAll(`Override[ContentType="${e}"]`),r=[];for(let e of n){let t=e?.attributes.PartName.value;r.push(t.substring(1))}return r}function Mx(e,t){if(e===`[Content_Types].xml`)return`_rels/.rels`;let n=``,r=e.split(`/`);for(let e=0;e<r.length-1;e++)n+=r[e]+`/`;return n+=`_rels/`,n+=r[r.length-1]+`.rels`,t[n]||(n=void 0),n}var Nx=class{warningManager;xmls;images;constructor(e){this.warningManager=new Yv,this.xmls={},this.images=[];for(let t of Object.keys(e))if(t.endsWith(`.xml`)||t.endsWith(`.rels`)){let n=px(e[t]);this.xmls[t]=sx(new B_(n))}else t.includes(`media/image`)&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){let e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){let e=this.buildXlsxFileStructure(),t=e.theme?new vx(e.theme,e,this.warningManager).getTheme():void 0,n=e.sharedStrings?new vx(e.sharedStrings,e,this.warningManager).getSharedStrings():[],r=new vx(e.workbook,e,this.warningManager).getNamedRanges(),i=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(n=>new Dx(n,e,this.warningManager,t).getSheet()),a=e.externalLinks.map(t=>new _x(t,e,this.warningManager).getExternalBook()),o=new Ox(e,this.warningManager,t);return{fonts:o.getFonts(),fills:o.getFills(),borders:o.getBorders(),dxfs:o.getDxfs(),numFmts:o.getNumFormats(),styles:o.getStyles(),sheets:i,sharedStrings:n,externalBooks:a,chartIds:[],imageIds:[],namedRanges:r}}buildXlsxFileStructure(){let e={sheets:kx(ip.sheet,this.xmls),workbook:kx(ip.workbook,this.xmls)[0]||kx(ip.macroEnabledWorkbook,this.xmls)[0]||kx(ip.templateWorkbook,this.xmls)[0]||kx(ip.macroEnabledTemplateWorkbook,this.xmls)[0]||kx(ip.excelAddInWorkbook,this.xmls)[0],styles:kx(ip.styles,this.xmls)[0],sharedStrings:kx(ip.sharedStrings,this.xmls)[0],theme:kx(ip.themes,this.xmls)[0],charts:kx(ip.chart,this.xmls),figures:kx(ip.drawing,this.xmls),tables:kx(ip.table,this.xmls),pivots:kx(ip.pivot,this.xmls),externalLinks:kx(ip.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(j(`Cannot find workbook relations file`));return e}convertImportedData(e){let t={version:`18.4.2`,sheets:xb(e,this.warningManager),styles:Fy(e,this.warningManager),formats:Ly(e,this.warningManager),borders:Ny(e,this.warningManager),namedRanges:K_(e,this.warningManager),revisionId:Ze};return Xb(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Qt(e.styles[t])}),t}};function Px(e){let t=!1,n=!0;return Co(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function Fx(e){let t=!1,n=!1;return Co(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function Ix(e,t){return go(e,(e,t)=>e+t,0,t)}function Lx(e){return ho(e,(e,t)=>Po(t)?e.add(t?.value):e,new Set).size}function Rx(e,t){if(!e)throw new N(t)}function zx(e,t=j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Wa(t)}function Bx(e){return e.length===1||e[0].length===1}function Vx(...e){if(e.every(gt)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function Hx(e){return e.length===e[0].length}let Ux=e=>j(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function Wx(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function Gx(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=Wx(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){Kx(i,e,a),Kx(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function Kx(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function qx(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function Jx(e){if(!gt(e))return e;if(!Yx(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Yx(e){return e.length===1&&e[0].length===1}function Xx(e){return gt(e)&&!Yx(e)}function Zx(...e){let t=e[0].length;e.forEach((e,n)=>Rx(e.length===t,j(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Qx(e,t){let n=0,r=go(e,(e,t)=>(n+=1,e+t),0,t);return zx(n),r/n}function $x(e,t){let n=[];po(e,e=>{n.push(e.value)},t),n.sort((e,t)=>e-t);let r=n.length;if(r===0)return;let i=Math.floor(r/2);return r%2==0?(n[i-1]+n[i])/2:n[i]}function eS(e,t){let n=0;for(let r of e)if(gt(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!Ja(e)&&(typeof e!=`string`||Ta(e,t)||Yi(e,t))&&(n+=1)}return n}function tS(e){return ho(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function nS(e,t){let n={value:-1/0};return po(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function rS(e,t){let n={value:1/0};return po(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function iS(e,t,n){let r=e[0].length?e:[C(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?xo(a):a,{_X:r,_newX:a}}function aS(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=iS(e,t,[[]]);o=o.length===a?xo(o):o.slice(),Zx(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=xo(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=sS(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=Gx(qx(p,xo(p)));if(h===void 0)throw new N(j(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),ee=_/(_+g),y=_/s/(g/c),b=[];for(let e=0;e<s;e++)b.push(v*Math.sqrt(h[e][e]));if(n){let e=qx(h,[d]),t=qx(xo([d]),e);b.push(v*Math.sqrt(t[0][0]+1/i.length))}let te=[[m[0][0],b[0],ee,y,_],[m[1][0],b[1],v,c,g]];for(let e=2;e<s;e++)te.push([m[e][0],b[e],``,``,``]);return n?te.push([m[s][0],b[s],``,``,``]):te.push([0,``,``,``,``]),te}function oS(e,t,n,r){Zx(t,e),Rx(n>=1,j(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>C(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=sS(a,i);return r||o.push([0]),o}function sS(e,t){let{inverted:n}=Gx(qx(e,xo(e)));if(n===void 0)throw new N(j(`Matrix is not invertible`));return xo(qx(n,qx(e,t)))}function cS(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function lS(e){return e.map(e=>e.map(e=>Math.exp(e)))}function uS(e){return e.map(e=>e.map(e=>Math.log(e)))}function dS(e,t,n,r){let{_X:i,_newX:a}=iS(t,e,n),o=aS(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:xo(c)}function fS(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}function pS(e){let[t,n]=e.split(`/`);return Number(n)*100+Number(t)}let mS=new O;function hS(e){return mS.get(e)}let gS={normalizeFunctionValue(e){return P(e,R)},toValueAndFormat(e,t){return{value:P(e,R),format:`dd mmm yyyy`}},toFunctionValue(e){let t=co(e,R);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},_S={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>31)throw new N(j(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},vS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>7)throw new N(j(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:ps[(e-1+(t||R).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},yS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>53)throw new N(j(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},bS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>12)throw new N(j(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:fs[P(e,R)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},xS={normalizeFunctionValue(e){return z(P(e,R),{locale:R,format:`mm/yyyy`})},toValueAndFormat(e){return{value:P(e,R),format:`mmmm yyyy`}},toFunctionValue(e){let t=co(e,R);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`},toComparableValue(e){return pS(e)}},SS={normalizeFunctionValue(e){let t=P(e,R);if(t<1||t>4)throw new N(j(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:j(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},CS={normalizeFunctionValue(e){let t=P(e,R);return t>3e3?co(t,R).getFullYear():t},toValueAndFormat(e){return{value:P(e,R),format:`0`}},toFunctionValue(e){return`${e}`}},wS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>23)throw new N(j(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:j(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},TS={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>59)throw new N(j(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},ES={normalizeFunctionValue(e){let t=P(e,R);if(t<0||t>59)throw new N(j(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function DS(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:j(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)},toComparableValue(t){if(t!==null)return e.toComparableValue?.(t)}}}mS.add(`day`,DS(gS)).add(`year`,DS(CS)).add(`day_of_month`,DS(_S)).add(`iso_week_number`,DS(yS)).add(`month_number`,DS(bS)).add(`month`,DS(xS)).add(`quarter_number`,DS(SS)).add(`day_of_week`,DS(vS)).add(`hour_number`,DS(wS)).add(`minute_number`,DS(TS)).add(`second_number`,DS(ES));let OS={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:`None`,bandedRows:!1,bandedColumns:!1,hasFilters:!1,tabularForm:!1},kS={count:j(`Count`),count_distinct:j(`Count Distinct`),bool_and:j(`Boolean And`),bool_or:j(`Boolean Or`),max:j(`Maximum`),min:j(`Minimum`),avg:j(`Average`),sum:j(`Sum`)},AS=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],jS={integer:AS,char:AS,datetime:AS,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},MS={};for(let e in jS){MS[e]={};for(let t of jS[e])MS[e][t]=kS[t]}let NS={count:e=>({value:tS([e]),format:`0`}),count_distinct:e=>({value:Lx([e]),format:`0`}),bool_and:e=>({value:Px([e]).result}),bool_or:e=>({value:Fx([e]).result}),max:(e,t)=>nS([e],t),min:(e,t)=>rS([e],t),avg:(e,t)=>({value:Qx([e],t),format:qa(e)}),sum:(e,t)=>({value:Ix([e],t),format:qa(e)})};function PS(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let FS={year:j(`Year`),quarter:j(`Quarter & Year`),month:j(`Month & Year`),week:j(`Week & Year`),day:j(`Day`),quarter_number:j(`Quarter`),month_number:j(`Month`),iso_week_number:j(`Week`),day_of_month:j(`Day of Month`),day_of_week:j(`Day of Week`),hour_number:j(`Hour`),minute_number:j(`Minute`),second_number:j(`Second`)},IS=[`date`,`datetime`];function LS(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function RS(e){return IS.includes(e.type)}function zS(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=LS(e),a=WS(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function BS(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function VS(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${zS(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${zS(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${zS(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function HS(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(Ja(n))return n;if(e.type===`custom`)return lo(t)??null;let r=typeof t==`boolean`?F(t).toLocaleLowerCase():F(t);if(r===`null`)return null;if(!KS.contains(e.type))throw new N(j(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:KS.get(e.type)(r,e.granularity)}function US(e,t){return hS(t??`month`).normalizeFunctionValue(e)}function WS(e,t){return e===null?`"null"`:qS.contains(t.type)?qS.get(t.type)(e,t.granularity):`"${e}"`}function GS(e,t){return hS(t??`month`).toFunctionValue(e)}let KS=new O;KS.add(`date`,US).add(`datetime`,US).add(`integer`,e=>P(e,R)).add(`boolean`,e=>I(e)).add(`char`,e=>F(e)).add(`custom`,e=>e);let qS=new O;qS.add(`date`,GS).add(`datetime`,GS).add(`integer`,e=>`${P(e,R)}`).add(`boolean`,e=>I(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${F(e).replace(/"/g,`\\"`)}"`).add(`custom`,e=>typeof e==`string`?`"${e}"`:String(e));function JS(e){return e.displayName+(e.granularity?` (${FS[e.granularity]})`:``)}function YS(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function XS(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}function ZS(e,t){return vn(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function QS(e,t){return vn(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(w),{compute:(e,t)=>`${e}${t}`,start:2})}function $S(e,t){let n={};for(let r of Object.values(e.customFields||{}))t[r.parentField]&&(n[r.name]={type:`custom`,isCustomField:!0,name:r.name,string:r.name,customGroups:r.groups,parentField:r.parentField});return n}function eC(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function tC(e,t,n){let r=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=r.findIndex(e=>e.fieldName===t);return i===-1||r.some(e=>e.fieldName===n)||r.splice(i,0,{fieldName:n}),e}function nC(e,t,n){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:QS(t.string,n),groups:[]}}function rC(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>T(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}function iC(e,t,n,r,i,a,o){let s=e.style;return{numberOfRows:t===void 0?s?.numberOfRows??OS.numberOfRows:P(t,o),numberOfColumns:i===void 0?s?.numberOfColumns??OS.numberOfColumns:P(i,o),displayTotals:n===void 0?s?.displayTotals??OS.displayTotals:I(n),displayColumnHeaders:r===void 0?s?.displayColumnHeaders??OS.displayColumnHeaders:I(r),displayMeasuresRow:a===void 0?s?.displayMeasuresRow??OS.displayMeasuresRow:I(a),tableStyleId:s?.tableStyleId||OS.tableStyleId,bandedRows:s?.bandedRows??OS.bandedRows,bandedColumns:s?.bandedColumns??OS.bandedColumns,hasFilters:s?.hasFilters??OS.hasFilters,tabularForm:s?.tabularForm??OS.tabularForm}}function aC(e,t=`>`){let n=e.indexOf(t),r=e.lastIndexOf(t);return!e||!n||n===r?e:`${e.slice(0,n+1)} … ${e.slice(r)}`}function oC(e,t,n){return n.map(n=>{if(n.id===e.id)return t;if(!n.computedBy||e.id===t.id)return n;let r=fu(n.computedBy.formula,e.id,t.id);return{...n,computedBy:{...n.computedBy,formula:r}}})}let sC=[`line`,`bar`,`pie`,`scorecard`,`gauge`,`scatter`,`bubble`,`combo`,`waterfall`,`pyramid`,`radar`,`geo`,`funnel`,`sunburst`,`treemap`,`calendar`];function cC(e){let t=Jf[e];return t===void 0?void 0:{minColor:t[0],midColor:t.length===3?t[1]:void 0,maxColor:t[t.length-1]}}function lC(e){let t=ml(e),n=[];return{text:``.concat(...t.map(e=>{if(e.type===`REFERENCE`&&xc.test(e.value)){let t=e.value.trim();return n.includes(t)||n.push(t),`|${n.indexOf(t)}|`}else return e.value})),dependencies:n}}let uC={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},dC=new O;dC.add(`0.1`,{migrate(e){return e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e}}).add(`0.2`,{migrate(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}}).add(`0.3`,{migrate(e){return e.sheets&&e.activeSheet&&(e.activeSheet=e.sheets.find(t=>t.name===e.activeSheet).id),e}}).add(`0.4`,{migrate(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}}).add(`0.5`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];n.content&&n.content.startsWith(`=`)&&(n.formula=lC(n.content))}return e}}).add(`0.6`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let{dataSets:n,...r}=t.figures[e].data,i=[];for(let e of n)if(e.labelCell){let t=Wn(e.dataRange),n=e.labelCell+`:`+E(t.right,t.bottom);i.push(n)}else i.push(e.dataRange);r.dataSetsHaveTitle=!!n[0].labelCell,r.dataSets=i,t.figures[e].data=r}return e}}).add(`0.7`,{migrate(e){let t=[];for(let n of e.sheets||[]){if(!n.name)continue;let e=n.name,r=vn(Dt(e,`_`),t,{compute:(e,t)=>`${e}${t}`});n.name=r,t.push(r);let i=t=>{if(t===void 0)return t;let n=t.replace(e,r),i=t;for(;i!==n;)i=n,n=i.replace(e,r);return i};for(let e in n.cells){let t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(i))}for(let e of n.figures||[])if(e.tag===`chart`){let t=e.data.dataSets.map(i),n=i(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:n}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(i);for(let t of[`minimum`,`maximum`,`midpoint`,`upperInflectionPoint`,`lowerInflectionPoint`])e.rule[t]?.type===`formula`&&(e.rule[t].value=i(e.rule[t].value))}}return e}}).add(`0.8`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.data.background=`#FFFFFF`,e.data.verticalAxisPosition=`left`,e.data.legendPosition=`top`,e.data.stacked=!1;return e}}).add(`0.9`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];if(n.formula){let{text:e,dependencies:t}=n.formula;for(let[n,r]of Object.entries(t)){let t=`\\|${n}\\|`;e=e.replace(new RegExp(t,`g`),r)}n.content=e,delete n.formula}}return e}}).add(`0.10`,{migrate(e){let t={};for(let n of e.sheets||[])for(let e in n.cells||[]){let r=n.cells[e];r.format&&=Y_(r.format,t)}return e.formats=t,e}}).add(`15.4`,{migrate(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}).add(`15.4.1`,{migrate(e){return fC(e)}}).add(`16.3`,{migrate(e){for(let t in e.borders){let n=e.borders[t];for(let e in n)Array.isArray(n[e])&&(n[e]={style:n[e][0],color:n[e][1]})}return e}}).add(`16.4`,{migrate(e){return e.settings||={},e.settings.locale||(e.settings.locale=R),e}}).add(`16.4.1`,{migrate(e){return fC(e)}}).add(`17.2`,{migrate(e){for(let t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add(`17.3`,{migrate(e){return e.pivots||={},e.pivotNextId||=PS(e.pivots)+1,e}}).add(`17.4`,{migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let n=t.figures[e];`title`in n.data&&typeof n.data.title==`string`&&(n.data.title={text:n.data.title});let r=n.data.type;if(![`line`,`bar`,`pie`,`scatter`,`waterfall`,`combo`].includes(r))continue;let{dataSets:i,...a}=t.figures[e].data;a.dataSets=i.map(e=>({dataRange:e})),t.figures[e].data=a}return e}}).add(`18.0`,{migrate(e){return e}}).add(`18.0.1`,{migrate(e){for(let t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add(`18.0.2`,{migrate(e){let t=e.settings?.locale;return t&&(t.weekStart=uC[t.code]||1),e}}).add(`18.0.3`,{migrate(e){for(let t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(let e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add(`18.0.4`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`gauge`)continue;let t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator=`<=`),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator=`<=`)}return e}}).add(`18.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.tables||[])e.config||={...Mb,hasFilters:!0};return e}}).add(`18.1.1`,{migrate(e){for(let t of e.sheets||[])for(let e in t.cells){let n=t.cells[e];n&&(t.cells[e]=n.content)}return e}}).add(`18.2`,{migrate(e){return e}}).add(`18.3`,{migrate(e){if(!e.pivots)return e;for(let t of Object.values(e.pivots))t.sortedColumn&&(t.measures.map(e=>e.id).includes(t.sortedColumn.measure)||delete t.sortedColumn);return e}}).add(`18.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){let t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add(`18.4.1`,{migrate(e){let t={textContains:`containsText`,textNotContains:`notContainsText`,textIs:`isEqualText`,textIsEmail:`isEmail`,textIsLink:`isLink`},n={BeginsWith:`beginsWithText`,Between:`isBetween`,ContainsText:`containsText`,EndsWith:`endsWithText`,Equal:`isEqual`,GreaterThan:`isGreaterThan`,GreaterThanOrEqual:`isGreaterOrEqualTo`,IsEmpty:`isEmpty`,IsNotEmpty:`isNotEmpty`,LessThan:`isLessThan`,LessThanOrEqual:`isLessOrEqualTo`,NotBetween:`isNotBetween`,NotContains:`notContainsText`,NotEqual:`isNotEqual`};for(let t of e.sheets||[])for(let e of t.conditionalFormats||[])e.rule.type===`CellIsRule`&&(e.rule.operator=n[e.rule.operator]);for(let n of e.sheets||[])for(let e of n.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add(`18.4.2`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`scorecard`)continue;let t=e.data;t.baselineDescr&&={text:t.baselineDescr}}return e}}).add(`18.4.3`,{migrate(e){if(!e.pivots)return e;for(let t in e.pivots){let n=e.pivots[t];if(n.sortedColumn){let e=n.measures.find(e=>e.fieldName===n.sortedColumn?.measure);e&&(n.sortedColumn.measure=e.id)}}return e}}).add(`18.5.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.tag===`chart`&&(e.data.chartId=e.id);return e}}).add(`19.1.0`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&e.data.type===`geo`&&`colorScale`in e.data&&typeof e.data.colorScale==`string`&&(e.data.colorScale=cC(e.data.colorScale)),e.tag===`carousel`)for(let t of Object.values(e.data.chartDefinitions)||[])t.type===`geo`&&`colorScale`in t&&typeof t.colorScale==`string`&&(t.colorScale=cC(t.colorScale));return e}}).add(`19.3.1`,{migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])if(e.tag===`chart`&&!(`humanize`in e.data))e.data.humanize=!0;else if(e.tag===`carousel`)for(let t in e.data.chartDefinitions){let n=e.data.chartDefinitions[t];`humanize`in n||(n.humanize=!0)}return e}}).add(`19.3.2`,{migrate(e){function t(e){if(!(`dataSets`in e))return e;e={...e};let t={};return e.dataSource={type:`range`,dataSetsHaveTitle:e.dataSetsHaveTitle,labelRange:e.labelRange,dataSets:e.dataSets.map((e,n)=>{let r=n.toString(),i=e.dataRange;return delete e.dataRange,Object.keys(e).length&&(t[r]={...e}),{dataRange:i,dataSetId:r}})},delete e.dataSetsHaveTitle,delete e.labelRange,delete e.dataSets,e.dataSetStyles=t,e}for(let n of e.sheets||[])for(let e of n.figures||[])if(e.tag===`chart`&&`dataSets`in e.data)e.data=t(e.data);else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions){let r=e.data.chartDefinitions[n];e.data.chartDefinitions[n]=t(r)}return e}});function fC(e){for(let t of e.sheets||[]){let e=[];for(let n of t.filterTables||[]){let t=Wn(n.range),r=e.findIndex(e=>ir(e,t));r===-1?e.push(t):e[r]=t}t.filterTables=e.map(e=>({range:Yn(e)}))}return e}function pC(){return mC().at(-1)}function mC(){return dC.getKeys().sort(yC)}let hC=`Sheet1`;function gC(e,t){if(!e)return jC();console.debug(`### Loading data ###`);let n=performance.now();if(e[`[Content_Types].xml`]){let n=new Nx(e);if(e=n.convertXlsx(),t)for(let e of n.warningManager.warnings.sort())console.warn(e)}return`version`in e&&(vC(e)&&(e.version=_C[e.version]),e.version!==pC()&&(console.debug(`Migrating data from version`,e.version),e=bC(e))),e=xC(e),console.debug(`Data loaded in`,performance.now()-n,`ms`),console.debug(`###`),e}let _C={25:`18.2`,24:`18.1.1`,23:`18.1`,22:`18.0.4`,21:`18.0.3`,20:`18.0.2`,19:`18.0.1`,18:`18.0`,17:`17.4`,16:`17.3`,15:`17.2`,"14.5":`16.4.1`,14:`16.4`,13:`16.3`,"12.5":`15.4.1`,12:`15.4`,11:`0.10`,10:`0.9`,9:`0.8`,8:`0.7`,7:`0.6`,6:`0.5`,5:`0.4`,4:`0.3`,3:`0.2`,2:`0.1`,1:`0`};function vC(e){return typeof e.version==`number`}function yC(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function bC(e){let t=performance.now(),n=mC(),r=n.findIndex(t=>yC(t,e.version)>=0);if(r===-1)throw Error(`Data version ${e.version} postdates the current version of o-spreadsheet (version ${pC()}). It cannot be loaded.`);for(let t=r+1;t<n.length;t++){let r=n[t];e=dC.get(r).migrate(e)}return console.debug(`Data migrated in`,performance.now()-t,`ms`),e}function xC(e){return e=SC(e),e=CC(e),e}function SC(e){if(e.uniqueFigureIds)return e;let t=new Set,n=new Set;for(let r of e.sheets||[])for(let e of r.figures||[])t.has(e.id)&&(e.id+=G.smallUuid()),t.add(e.id),e.tag===`chart`&&(n.has(e.data?.chartId)&&(e.data.chartId+=G.smallUuid()),n.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}function CC(e){let t=Object.assign(jC(),e,{version:pC()});return t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(AC(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],t.sheets.length===0&&t.sheets.push(AC(hC,`Sheet1`)),S_(t.settings.locale)||(t.settings.locale=R),t}function wC(e,t){return t=TC(e,t),t=EC(t,`SORT_CELLS`),t=EC(t,`SET_DECIMAL`),t=DC(e,t),t=OC(e,t),t=kC(e,t),t}function TC(e,t){if(Object.keys(e).length!==0)return t;let n=[],r=[],i=e=>{if(e.type===`CREATE_SHEET`)n.push(e.sheetId);else if(`sheetId`in e&&!n.includes(e.sheetId))return{...e,sheetId:hC};return e};for(let e of t)e.type===`REMOTE_REVISION`?r.push({...e,commands:e.commands.map(i)}):r.push(e);return r}function EC(e,t){let n=[];for(let r of e)r.type===`REMOTE_REVISION`?n.push({...r,commands:r.commands.filter(e=>e.type!==t)}):n.push(r);return n}function DC(e,t){if(!e.version||yC(String(e.version),`18.5.1`)>=0)return t;let n=[],r={};e=gC(x(e));for(let t of e.sheets||[])t.figures?.forEach(e=>{e.tag===`chart`&&(r[e.id]=e.data)});for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let n of e.commands){let e=n;switch(n.type){case`CREATE_CHART`:r[n.chartId]=n.definition;break;case`UPDATE_CHART`:if(!r[n.chartId]){console.log(`Fix chart definition: chart with id ${n.chartId} not found.`);continue}let t={...r[n.chartId],...n.definition};e={...n,definition:t},delete t.chartId,r[n.chartId]=t;break}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}function OC(e,t){let n={};for(let t of e.sheets||[])t.figures?.forEach(e=>{n[e.id]=e.offset});for(let e of t)if(e.type===`REMOTE_REVISION`)for(let t of e.commands)switch(t.type){case`UPDATE_FIGURE`:t.offset&&(t.offset.x===void 0&&(t.offset.x=n[t.figureId]||0),t.offset.y===void 0&&(t.offset.y=n[t.figureId]||0),n[t.figureId]=n);break;case`CREATE_IMAGE`:case`CREATE_CHART`:case`CREATE_FIGURE`:n[t.figureId]=t.offset;break}return t}function kC(e,t){let n={};for(let t of e.sheets||[])n[t.id]=t.name;let r=[];for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let r of e.commands){switch(r.type){case`DUPLICATE_SHEET`:r.sheetNameTo=r.sheetNameTo??ru(n[r.sheetId],Object.values(n));break;case`CREATE_SHEET`:n[r.sheetId]=r.name||nu(Object.values(n));break;case`RENAME_SHEET`:n[r.sheetId]=r.newName||nu(Object.values(n));break}t.push(r)}r.push({...e,commands:t})}else r.push(e);return t}function AC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function jC(e=`Sheet1`){return{version:pC(),sheets:[AC(hC,e)],styles:{},formats:{},borders:{},revisionId:Ze,uniqueFigureIds:!0,settings:{locale:R},pivots:{},pivotNextId:1,customTableStyles:{},namedRanges:{}}}function MC(e,t){return{...AC(e,t),charts:[],images:[],cellValues:{}}}function NC(){return{...jC(),sheets:[MC(hC,`Sheet1`)]}}let PC=(e,t)=>{e.model.dispatch(t.type).isCancelledBecause(`WillRemoveExistingMerge`)&&e.raiseError(m_)},FC={wrongPasteSelection:j(`This operation is not allowed with multiple selections.`),willRemoveExistingMerge:__.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:j(`Cannot do a special paste of a figure.`),frozenPaneOverlap:j(`This operation is not allowed due to an overlapping frozen pane.`)};function IC(e,t){t.isSuccessful||(t.reasons.includes(`WrongPasteSelection`)?e.raiseError(FC.wrongPasteSelection):t.reasons.includes(`WillRemoveExistingMerge`)?e.raiseError(FC.willRemoveExistingMerge):t.reasons.includes(`WrongFigurePasteOption`)?e.raiseError(FC.wrongFigurePasteOption):t.reasons.includes(`FrozenPaneOverlap`)&&e.raiseError(FC.frozenPaneOverlap))}function LC(e,t,n){IC(e,e.model.dispatch(`PASTE`,{target:t,pasteOption:n}))}async function RC(e,t,n,r){if(n.data&&n.data.version!==pC()&&e.notifyUser({type:`warning`,text:j(`You copied content from a different version of the application. Only text and image content will be pasted.`),sticky:!1}),n.imageBlob){let t=n;try{t.imageData=await e.imageProvider?.uploadFile(n.imageBlob)}catch(t){let n=j(`An error occurred while uploading the image. %s`,t.message);console.error(t),e.raiseError(n)}delete n.imageBlob}IC(e,e.model.dispatch(`PASTE_FROM_OS_CLIPBOARD`,{target:t,clipboardContent:n,pasteOption:r}))}let zC=new O;var BC=class extends Vr{mutators=[`open`,`close`];persistentPopover;hoveredCell=this.get(c_);handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.close()}}open({col:e,row:t},n){let r=this.getters.getActiveSheetId();zC.contains(n)&&(this.persistentPopover={col:e,row:t,sheetId:r,type:n})}close(){if(!this.persistentPopover)return`noStateChange`;this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return this.persistentPopover!==void 0}get cellPopover(){let e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){let e=this.getters.getMainCellPosition(this.persistentPopover),t=zC.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}let{col:t,row:n}=this.hoveredCell;if(t===void 0||n===void 0||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:n}))return{isOpen:!1};let r=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),i=zC.getAll().map(e=>e.onHover?.(r,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(r)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){let n=this.getters.getActiveSheetId(),r=this.getters.getMerge({sheetId:n,col:e,row:t});return r?this.getters.getVisibleRect(r):this.getters.getVisibleRect(D({col:e,row:t}))}};let VC=function(e){return e.PlainText=`text/plain`,e.Html=`text/html`,e.Image=`image`,e}({}),HC=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function UC(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?gr(t):[t[t.length-1]],s=o.map(e=>dr(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function WC(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function GC(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>WC(e,n,r)).flat()}function KC(e){let t;e[`text/html`]&&(t=JC(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of HC)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function qC(e){return e?.match(/<div data-osheet-clipboard-id=(['"])([^'"]+)\1/)?.[2]}function JC(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let YC=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function XC(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureIds&&(s.figureIds={...s.figureIds,...u.figureIds});for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=er(a,e)}}return{target:s,zone:a,selectedZones:o}}let ZC=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:er(...n)},{scrollIntoView:!1})},QC={type:`bar`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,humanize:!0},$C={type:`line`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,cumulative:!1,labelsAsText:!1,humanize:!0};function ew(e,t){return Yn(e.getUnboundedZone(e.getActiveSheetId(),t))}function tw(e){if(!e.length)return`empty`;let t={number:0,text:0,date:0,percentage:0},n=0,r=`empty`;for(let i of e){let e=null;if(i.type===`number`?e=i.format&&Os(i.format)?`date`:i.format?.includes(`%`)?`percentage`:`number`:i.type===`text`&&(e=`text`),e){let i=++t[e];i>n&&(n=i,r=e)}}return r}function nw(e,t){let n=[];for(let r of Dr(e)){let e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),r);n.push({zone:r,type:tw(e)})}return n}function rw(e,t){let n=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||``).filter(e=>e);return{uniqueCount:new Set(n).size,totalCount:n.length}}function iw(e,t){let n=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![`number`,`empty`].includes(n.type)}function aw(e,t){let{type:n,zone:r}=e,i=t.getActiveSheetId(),a=iw(t,e),o=ew(t,r),s=t.getEvaluatedCell({sheetId:i,col:r.left,row:r.top});if(xr(r)===1)return cw(r,t);switch(n){case`percentage`:return{type:`pie`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{},legendPosition:`none`};case`text`:let e=t.getEvaluatedCellsInZone(i,r).reduce((e,t)=>t.value===s.value?e+1:e,0),n=s.value!==null&&e===1;return{type:`pie`,title:n?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],labelRange:o,dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!0,legendPosition:`top`};case`date`:return{...$C,type:`line`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}return{...QC,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}function ow(e,t){if(e.length!==2)throw Error(`buildTwoColumnChart expects exactly two columns`);if(e[1].type===`percentage`)return{type:`pie`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{},aggregated:!0,legendPosition:`none`};if(e[0].type===`number`&&e[1].type===`number`)return{type:`scatter`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{},labelsAsText:!1,legendPosition:`none`};if(e[0].type===`date`&&e[1].type===`number`)return{...$C,type:`line`,dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[0])},dataSetStyles:{}};if(e[0].type===`text`&&e[1].type===`number`){let n=e[0],r=e[1],{uniqueCount:i,totalCount:a}=rw(t,n.zone),o=iw(t,r);if(i!==a)return{type:`treemap`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:ew(t,n.zone),dataSetId:`0`}],labelRange:ew(t,r.zone),dataSetsHaveTitle:o},dataSetStyles:{},legendPosition:`none`}}return{...QC,dataSource:{type:`range`,dataSets:[{dataRange:ew(t,e[1].zone),dataSetId:`0`}],labelRange:ew(t,e[0].zone),dataSetsHaveTitle:iw(t,e[1])},dataSetStyles:{}}}function sw(e,t){if(e.length<3)throw Error(`buildMultiColumnChart expects at least three columns`);let n=e.some(e=>e.type!==`text`&&iw(t,e)),r=e[e.length-1],i=e.slice(0,e.length-1);if((r.type===`percentage`||r.type===`number`)&&i.every(e=>e.type===`text`)){let e=i.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return{type:i.length>=3?`sunburst`:`treemap`,title:{},dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:n,labelRange:ew(t,r.zone)},dataSetStyles:{},legendPosition:`none`}}let a=e[0],o=e.slice(1),s=o.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return o.every(e=>e.type===`percentage`)?{type:`pie`,title:{},dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!1,legendPosition:`top`}:a.type===`date`&&o.every(e=>e.type===`number`)?{...$C,type:`line`,dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}:{...QC,dataSource:{type:`range`,dataSets:s,labelRange:ew(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}}function cw(e,t){let n=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:`scorecard`,title:{},keyValue:ew(t,e),background:n?.style?.fillColor,baselineMode:Qe,baselineColorUp:$e,baselineColorDown:et}}function lw(e,t){let n=nw(e,t);if(n.length===0||n.every(e=>e.type===`empty`)){let e=n.map(({zone:e},n)=>({dataRange:ew(t,e),dataSetId:n.toString()}));return{...QC,dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:!1}}}let r=n.filter(e=>e.type!==`empty`);switch(r.length){case 1:return{humanize:!0,...aw(r[0],t)};case 2:return{humanize:!0,...ow(r,t)};default:return{humanize:!0,...sw(r,t)}}}function uw(e,t,n=Mb){let r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r);r.length===1&&!i&&xr(r[0])===1&&(e.model.selection.selectTableAroundSelection(),r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r));let a=r.map(n=>e.model.getters.getRangeDataFromZone(t,n)),o=e.model.dispatch(`CREATE_TABLE`,{ranges:a,sheetId:t,config:n,tableType:i?`dynamic`:`static`});return o.isCancelledBecause(`TableOverlap`)?e.raiseError(y_.Errors.TableOverlap):o.isCancelledBecause(`NonContinuousTargets`)&&e.raiseError(y_.Errors.NonContinuousTargets),o}function dw(e,t){e.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function fw(e,t){e.model.dispatch(`SET_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}let pw=async e=>hw(e),mw=async e=>hw(e,`asValue`);async function hw(e,t){let n=await e.clipboard.read();switch(n.status){case`ok`:let r=e.model.getters.getClipboardId(),i=e.model.getters.getSelectedZones();r===qC(n.content[`text/html`])?LC(e,i,t):await RC(e,i,KC(n.content),t),e.model.getters.isCutOperation()&&t!==`asValue`&&await e.clipboard.write({"text/plain":``});break;case`notImplemented`:e.raiseError(j(`Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead.`));break;case`permissionDenied`:e.raiseError(j(`Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings.`));break}}let gw=e=>hw(e,`onlyFormat`),_w=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Clear row %s`,(t+1).toString()):j(`Clear rows %s - %s`,(t+1).toString(),(n+1).toString())},vw=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveRows()].map(n=>e.model.getters.getRowsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},yw=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Clear column %s`,Cn(t)):j(`Clear columns %s - %s`,Cn(t),Cn(n))},bw=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveCols()].map(n=>e.model.getters.getColsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},xw=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Delete row %s`,(t+1).toString()):j(`Delete rows %s - %s`,(t+1).toString(),(n+1).toString())},Sw=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.top;e<=n.bottom;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},Cw=(e,t)=>{if(e===`COL`&&t.model.getters.getActiveRows().size>0||e===`ROW`&&t.model.getters.getActiveCols().size>0)return!1;let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(n,e,r),a=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(n,e,r);return!i&&!a},ww=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=mn([...r]),n=pn([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Delete column %s`,Cn(t)):j(`Delete columns %s - %s`,Cn(t),Cn(n))},Tw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`ROW`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`ROW`,n)},Ew=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.left;e<=n.right;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`COL`,elements:t})},Dw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`COL`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`COL`,n)},Ow=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=mn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.top,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,base:n,quantity:r,dimension:`ROW`})},kw=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=pn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.bottom,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,base:n,quantity:r,dimension:`ROW`})},Aw=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=mn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.left,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,dimension:`COL`,base:n,quantity:r})},jw=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=pn([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.right,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,dimension:`COL`,base:n,quantity:r})},Mw=e=>{let t=e.model.getters.getElementsFromSelection(`COL`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide column %s`,Cn(n).toString()):r-n+1===t.length?j(`Hide columns %s - %s`,Cn(n).toString(),Cn(r).toString()):j(`Hide columns`)},Nw=e=>{let t=e.model.getters.getElementsFromSelection(`ROW`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide row %s`,(n+1).toString()):r-n+1===t.length?j(`Hide rows %s - %s`,(n+1).toString(),(r+1).toString()):j(`Hide rows`)},Pw=e=>{let t=e.model.getters,n=G.smallUuid(),r=t.getActiveSheetId(),i=t.getSelectedZones();i.length===1&&xr(i[0])===1&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());let a={width:536,height:335},{col:o,row:s,offset:c}=Wh(t,a);e.model.dispatch(`CREATE_CHART`,{sheetId:r,figureId:n,chartId:G.smallUuid(),col:o,row:s,offset:c,size:a,definition:lw(i,e.model.getters)}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`ChartPanel`))},Fw=e=>{let t=e.model.getters,n=G.smallUuid(),r=t.getActiveSheetId(),i={width:536,height:335},{col:a,row:o,offset:s}=Wh(t,i);e.model.dispatch(`CREATE_CAROUSEL`,{sheetId:r,figureId:n,col:a,row:o,offset:s,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`CarouselPanel`,{figureId:n}))},Iw=e=>{let t=G.smallUuid(),n=G.smallUuid();e.model.dispatch(`INSERT_NEW_PIVOT`,{pivotId:t,newSheetId:n}).isSuccessful&&e.openSidePanel(`PivotSidePanel`,{pivotId:t})},Lw=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r,col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`dynamic`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),Rw=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getExpandedTableStructure();if(r.numberOfCells>5e5){e.notifyUser({type:`warning`,text:x_(r.numberOfCells,e.model.getters.getLocale()),sticky:!0});return}e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r.export(),col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`static`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),zw=async e=>{if(e.imageProvider){let t=e.model.getters.getActiveSheetId(),n=G.smallUuid(),r=await e.imageProvider.requestImage(),i=Gh(e.model.getters,r.size),{col:a,row:o,offset:s}=Wh(e.model.getters,i);e.model.dispatch(`CREATE_IMAGE`,{sheetId:t,figureId:n,col:a,row:o,offset:s,size:i,definition:r})}},Bw=e=>dw(e,`0.00%`),Vw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getConditionalFormats(t),i=e.model.getters.getRulesSelection(t,n);return i.length===1?e.openSidePanel(`ConditionalFormattingEditor`,{cf:r.find(e=>e.id===i[0]),isNewCf:!1}):e.openSidePanel(`ConditionalFormatting`)},Hw=e=>{let{col:t,row:n}=e.model.getters.getActivePosition();e.getStore(BC).open({col:t,row:n},`LinkEditor`)},Uw=e=>{let t=e.model.getters.getActiveSheetId(),{col:n,row:r}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:n,row:r});return i&&i.link?j(`Edit link`):j(`Insert link`)},Ww=e=>e.model.getters.getFirstTableInSelection()?.config.hasFilters||!1,Gw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getTablesOverlappingZones(t,n);return r.length===1&&!r[0].isPivotTable},Kw=e=>Tr(e.model.getters.getSelectedZones()),qw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n?e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!0}}):uw(e,t,{...Mb,hasFilters:!0,bandedRows:!1,styleId:`TableStyleLight11`})},Jw=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n&&e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!1}})},Yw=e=>{uw(e,e.model.getters.getActiveSheetId()).isSuccessful&&e.openSidePanel(`TableSidePanel`,{})},Xw=e=>{let t=e.model.getters.getFirstTableInSelection();t&&e.model.dispatch(`REMOVE_TABLE`,{sheetId:e.model.getters.getActiveSheetId(),target:[t.range.zone]})},Zw=e=>e.model.getters.getSelectedZones().length===1,Qw=(e,t)=>{if(!Zw(e))return!1;let n=t===`COL`?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),r=t===`COL`?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),a=rr(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return an(n)&&(r.size===0||a)},$w={name:e=>Ww(e)?j(`Remove selected filters`):j(`Add filters`),isEnabled:e=>Kw(e),execute:e=>Ww(e)?Jw(e):qw(e),icon:`o-spreadsheet-Icon.FILTER_ICON_ACTIVE`},eT={name:e=>{let t=PT(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW`},tT={name:e=>{let t=PT(e);return t===1?j(`Insert row above`):j(`Insert %s rows above`,t.toString())},execute:Ow,isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},nT={...tT,name:e=>{let t=PT(e);return t===1?j(`Row above`):j(`%s Rows above`,t.toString())}},rT={...tT,name:e=>{let t=PT(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:Zw,icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},iT={execute:kw,name:e=>{let t=PT(e);return t===1?j(`Insert row below`):j(`Insert %s rows below`,t.toString())},isVisible:e=>Qw(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_AFTER`},aT={...iT,name:e=>{let t=PT(e);return t===1?j(`Row below`):j(`%s Rows below`,t.toString())}},oT={name:e=>{let t=FT(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL`},sT={name:e=>{let t=FT(e);return t===1?j(`Insert column left`):j(`Insert %s columns left`,t.toString())},execute:Aw,isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},cT={...sT,name:e=>{let t=FT(e);return t===1?j(`Column left`):j(`%s Columns left`,t.toString())}},lT={...sT,name:e=>{let t=FT(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:Zw,icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},uT={name:e=>{let t=FT(e);return t===1?j(`Insert column right`):j(`Insert %s columns right`,t.toString())},execute:jw,isVisible:e=>Qw(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_AFTER`},dT={...uT,name:e=>{let t=FT(e);return t===1?j(`Column right`):j(`%s Columns right`,t.toString())},execute:jw},fT={name:j(`Insert cells`),isVisible:e=>Zw(e)&&e.model.getters.getActiveCols().size===0&&e.model.getters.getActiveRows().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL`},pT={name:j(`Insert cells and shift down`),execute:e=>{let t=e.model.getters.getSelectedZone();IC(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`ROW`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN`},mT={name:j(`Insert cells and shift right`),execute:e=>{let t=e.model.getters.getSelectedZone();IC(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`COL`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT`},hT={name:j(`Chart`),execute:Pw,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_CHART`},gT={name:j(`Carousel`),execute:Fw,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.CAROUSEL`},_T={name:j(`Pivot table`),execute:Iw,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},vT={name:j(`Image`),shortcut:`Ctrl+O`,execute:zw,isVisible:e=>e.imageProvider!==void 0,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_IMAGE`},yT={name:()=>j(`Table`),shortcut:`Alt+T`,execute:Yw,isVisible:e=>Kw(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.PAINT_TABLE`},bT={name:j(`Function`),icon:`o-spreadsheet-Icon.FORMULA`},xT={name:j(`SUM`),execute:e=>e.startCellEdition(`=SUM(`)},ST={name:j(`AVERAGE`),execute:e=>e.startCellEdition(`=AVERAGE(`)},CT={name:j(`COUNT`),execute:e=>e.startCellEdition(`=COUNT(`)},wT={name:j(`MAX`),execute:e=>e.startCellEdition(`=MAX(`)},TT={name:j(`MIN`),execute:e=>e.startCellEdition(`=MIN(`)},ET={name:j(`All`),children:[DT]};function DT(){return NT(bc.getKeys().filter(e=>!bc.get(e).hidden))}let OT=()=>{let e=bc.content;return[...new Set(bc.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(w).sort().map((t,n)=>({name:t,children:NT(Object.keys(e).filter(n=>e[n].category===t&&!e[n].hidden)),sequence:60+n}))},kT={name:j(`Link`),shortcut:`Ctrl+Shift+K`,execute:Hw,icon:`o-spreadsheet-Icon.INSERT_LINK`},AT={name:j(`Checkbox`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t));e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:G.smallUuid(),criterion:{type:`isBoolean`,values:[]}}})},icon:`o-spreadsheet-Icon.INSERT_CHECKBOX`},jT={name:j(`Dropdown list`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t)),i=G.smallUuid();e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:i,criterion:{type:`isValueInList`,values:[],displayStyle:`chip`}}}),e.model.getters.getDataValidationRule(n,i)&&e.openSidePanel(`DataValidationEditor`,{ruleId:i,onCancel:()=>{e.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:n,id:i})}})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_DROPDOWN`},MT={name:j(`Insert sheet`),shortcut:`Shift+F11`,execute:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSheetIds().indexOf(t)+1,r=G.smallUuid();e.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:e.model.getters.getNextSheetName()}),e.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})},icon:`o-spreadsheet-Icon.INSERT_SHEET`};function NT(e){return e.sort().map((e,t)=>({name:e,sequence:t*10,execute:t=>t.startCellEdition(`=${e}(`)}))}function PT(e){let t=e.model.getters.getActiveRows();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function FT(e){let t=e.model.getters.getActiveCols();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function IT(e,t){let n=()=>{window.removeEventListener(`pointerup`,r,{capture:!0}),window.removeEventListener(`dragstart`,i),window.removeEventListener(`pointermove`,e),window.removeEventListener(`wheel`,e)},r=e=>{t(e),n()};function i(e){e.preventDefault()}return window.addEventListener(`pointerup`,r,{capture:!0}),window.addEventListener(`dragstart`,i),window.addEventListener(`pointermove`,e),window.addEventListener(`wheel`,e,{passive:!1}),n}function LT(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new VT(a.scrollableContainerEl):new BT(a.scrollableContainerEl);e=new RT({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=IT(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.proxy)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var RT=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),H(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},zT=class{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},BT=class extends zT{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},VT=class extends zT{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}};function HT(e){(0,t.useEffect)(()=>e()?.focus())}let UT={value:W.or([W.number(),W.string()]),onChange:W.function([W.string()]),"onFocused?":W.function([]),"onBlur?":W.function([]),"onInput?":W.function([W.string()]),"class?":W.string(),"id?":W.string(),"placeholder?":W.string(),"autofocus?":W.boolean(),"alwaysShowBorder?":W.boolean(),"selectContentOnFocus?":W.boolean(),"resetOnBlur?":W.boolean()};var WT=class extends k{props=(0,t.props)(UT);genericInputRef=(0,t.signal)(null);lastOnChangeValue=this.props.value.toString();setup(){(0,t.useListener)(window,`click`,e=>{let t=this.genericInputRef();!t||e.target===t||t.value===this.props.value.toString()||(this.props.resetOnBlur?t.value=this.props.value.toString():this.save())},{capture:!0}),this.props.autofocus&&HT(this.genericInputRef),(0,t.onWillUpdateProps)(e=>{let t=this.genericInputRef();document.activeElement!==t&&t&&(t.value=e.value),this.lastOnChangeValue=e.value.toString()}),(0,t.onMounted)(()=>{let e=this.genericInputRef();e&&(e.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:let t=this.genericInputRef();t&&(t.value=this.props.value.toString(),t.blur()),e.preventDefault(),e.stopPropagation();break}}save(){let e=(this.genericInputRef()?.value||``).trim();e!==this.lastOnChangeValue&&(this.lastOnChangeValue=e,this.props.onChange(e)),document.activeElement===this.genericInputRef()&&this.genericInputRef()?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}onFocus(){this.props.onFocused?.()}onBlur(){if(this.props.onBlur?.(),this.props.resetOnBlur){let e=this.genericInputRef();e&&(e.value=this.props.value.toString())}else this.save()}onInput(e){let t=e.target;this.props.onInput?.(t.value)}},GT=class extends WT{static template=`o-spreadsheet-TextInput`;static components={};props=(0,t.props)({...UT,value:W.string(),"errorMessage?":W.string()});get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(w).join(` `)}},KT=class extends k{static template=`o-spreadsheet-ActionButton`;props=(0,t.props)({action:W.ActionSpec(),"hasTriangleDownIcon?":W.boolean(),"selectedColor?":W.string(),"class?":W.string(),"onClick?":W.function()});actionButton=xe(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=xe(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){let e=this.actionButton.isEnabledOnLockedSheet||!this.env.model.getters.isCurrentSheetLocked();return this.actionButton.isEnabled(this.env)&&e}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){let e=this.actionButton.name(this.env),t=this.actionButton.description(this.env)||this.actionButton.shortcut;return e+(t?` (${t})`:``)}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?H({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}},qT=class extends k{static template=`o-spreadsheet-ColorPicker`;static components={Popover:Xg};props=(0,t.props)({onColorPicked:W.function([W.string()]),"currentColor?":W.string(),"maxHeight?":W.Pixel(),anchorRect:W.Rect(),"disableNoColor?":W.boolean()},{currentColor:``});COLORS=Ve;state=(0,t.proxy)({showGradient:!1,currentHslaColor:df(this.props.currentColor)?{...Sf(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:df(this.props.currentColor)?uf(this.props.currentColor):``});get colorPickerStyle(){return this.props.maxHeight!==void 0&&this.props.maxHeight<=0?H({display:`none`}):``}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,verticalOffset:0}}get gradientHueStyle(){return H({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){let e=this.state.currentHslaColor?.h||0;return H({"margin-left":`${S(Math.round(e/360*216),1,216)-18/2}px`})}get pointerStyle(){let{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0},n=Math.round(216*S(e/100,0,1)),r=Math.round(186*S(1-2*t/(200-e),0,1));return H({left:`${-16/2+n}px`,top:`${-16/2+r}px`,background:xf(this.state.currentHslaColor)})}get colorPreviewStyle(){return H({"background-color":xf(this.state.currentHslaColor)})}get checkmarkColor(){return xp(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||df(this.state.customHexColor)}setCustomGradient({x:e,y:t}){let n=S(e,0,216),r=S(t,0,186),i=n/216,a=r/186,o=100*i,s=100*(1-a)*(1-.5*i);this.updateColor({s:o,l:s})}setCustomHue(e){let t=Math.round(S(360*e/216,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=xf(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(uf(e))}resetColor(){this.props.onColorPicked(``)}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){let t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);let n={x:e.clientX,y:e.clientY};IT(e=>{let r={x:e.clientX,y:e.clientY},i=r.x-n.x,a=r.y-n.y,o={x:t.x+i,y:t.y+a};this.setCustomGradient(o)},()=>{})}dragHuePointer(e){let t=e.offsetX,n=e.clientX;this.setCustomHue(t),IT(e=>{let r=t+(e.clientX-n);this.setCustomHue(r)},()=>{})}setHexColor(e){let t=e.target.value.replace(`##`,`#`).slice(0,7);this.state.customHexColor=t,df(t)&&(this.state.currentHslaColor={...Sf(t),a:1})}addCustomColor(e){!ff(this.state.currentHslaColor)||!df(this.state.customHexColor)||this.props.onColorPicked(uf(this.state.customHexColor))}isSameColor(e,t){return Tf(e,t)}get canUseEyeDropper(){return!!globalThis.EyeDropper&&!this.env.model.getters.isDarkMode()}async activateEyedropper(){if(globalThis.EyeDropper)try{let e=await new globalThis.EyeDropper().open();e&&e.sRGBHex&&this.props.onColorPicked(uf(e.sRGBHex))}catch(e){if(e.name!==`AbortError`)throw e}}},JT=class extends k{static template=`o-spreadsheet-ColorPickerWidget`;static components={ColorPicker:qT};props=(0,t.props)({"currentColor?":W.string(),toggleColorPicker:W.function([]),showColorPicker:W.boolean(),onColorPicked:W.function([W.string()]),icon:W.string(),"title?":W.string(),"disabled?":W.boolean(),"dropdownMaxHeight?":W.Pixel(),"class?":W.string()});colorPickerButtonRef=(0,t.signal)(null);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){return y(this.colorPickerButtonRef())}},YT=class extends k{static template=`o-spreadsheet-NumberEditor`;static components={Popover:Xg};props=(0,t.props)({currentValue:W.number(),onValueChange:W.function([W.number()]),"onToggle?":W.function([]),"onFocusInput?":W.function([]),class:W.string(),"valueIcon?":W.string(),min:W.number(),max:W.number(),title:W.string(),valueList:W.array(W.number())},{onFocusInput:()=>{}});dropdown=(0,t.proxy)({isOpen:!1});inputRef=(0,t.signal)(null);rootEditorRef=(0,t.signal)(null);valueListRef=(0,t.signal)(null);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=A(Cg),mi(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{let t=this.inputRef();t&&document.activeElement!==t&&(t.value=e.currentValue)}),(0,t.onMounted)(()=>{let e=this.inputRef();e&&(e.value=this.props.currentValue.toString())})}get popoverProps(){return{anchorRect:y(this.rootEditorRef()),positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){let t=this.valueListRef(),n=this.rootEditorRef();t&&n&&!_(t,e)&&!_(n,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef()?.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=S(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},XT=class extends k{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:YT};props=(0,t.props)({currentFontSize:W.number(),onFontSizeChanged:W.function([W.number()]),"onToggle?":W.function([]),"onFocusInput?":W.function([]),class:W.string()},{onFocusInput:()=>{}});fontSizes=st},ZT=class extends k{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:JT,ActionButton:KT,FontSizeEditor:XT};props=(0,t.props)({style:W.ChartStyle(),updateStyle:W.function([W.ChartStyle()]),"defaultStyle?":W.object({}),"hasVerticalAlign?":W.boolean(),"hasHorizontalAlign?":W.boolean(),"hasBackgroundColor?":W.boolean(),"class?":W.string()});openedEl=null;setup(){mi(window,`click`,this.onExternalClick)}state=(0,t.proxy)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??Ue.fontSize}get boldButtonAction(){return{name:j(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:j(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:j(`Horizontal alignment`),icon:e,isEnabledOnLockedSheet:!0}}get horizontalAlignActions(){return[{name:j(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:j(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:j(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:j(`Vertical alignment`),icon:e,isEnabledOnLockedSheet:!0}}get verticalAlignActions(){return[{name:j(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:j(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:j(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},QT=class extends k{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:e_};props=(0,t.props)({items:W.array(W.ActionSpec())});buttonRef=(0,t.signal)(null);menuState=(0,t.proxy)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=G.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=b(this.buttonRef()),this.menuState.menuItems=ve(this.props.items))}},Z=class extends k{static template=`o_spreadsheet.Section`;props=(0,t.props)({"class?":W.string(),"title?":W.string(),slots:W.object()})},$T=class extends k{static template=`o-spreadsheet-CarouselPanel`;static components={Section:Z,TextInput:GT,TextStyler:ZT,CogWheelMenu:QT};props=(0,t.props)({onCloseSidePanel:W.function([]),figureId:W.UID()});DEFAULT_CAROUSEL_TITLE_STYLE=dt;dragAndDrop=LT();previewListRef=(0,t.signal)(null);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{T(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return T(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>T(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!T(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:G.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=this.previewListRef();if(!n)return;let r=Array.from(n.children).map(e=>b(e)),i=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:r[t].height,position:r[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:i,scrollableContainerEl:n,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>T(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return ag(this.env.model.getters,e)}getItemPreview(e){return ig(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return j(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:j(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:j(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:j(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:j(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return j(`The data view makes the carousel transparent, revealing the data underneath.`)}};let eE=new O;var tE=class extends k{static template=`o-spreadsheet.Checkbox`;props=(0,t.props)({"label?":W.string(),"value?":W.boolean(),"className?":W.string(),"name?":W.string(),"title?":W.string(),"disabled?":W.boolean(),onChange:W.function([W.boolean()])},{value:!1});onChange(e){let t=e.target.checked;this.props.onChange(t)}};let nE={chartId:W.UID(),definition:W.object({}),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())},rE={ArrowDown:`down`,ArrowLeft:`left`,ArrowRight:`right`,ArrowUp:`up`};function iE(e,t){let n=rE[e.key];e.shiftKey?t.resizeAnchorZone(n,le(e)?`end`:1):t.moveAnchorCell(n,le(e)?`end`:1)}function aE(e,t,n){let{anchor:{zone:r,cell:i}}=e.getSelection(),a={...i},o=xr(r);do a=oE(a,r,n),o--;while(o>0&&!sE(e,a));o>0&&t.updateAnchorCell(a.col,a.row,{scrollIntoView:!0})}function oE(e,t,n){let{col:r,row:i}=e;switch(n){case`right`:r<t.right?r++:(r=t.left,i=i<t.bottom?i+1:t.top);break;case`left`:r>t.left?r--:(r=t.right,i=i>t.top?i-1:t.bottom);break;case`down`:i<t.bottom?i++:(i=t.top,r=r<t.right?r+1:t.left);break;case`up`:i>t.top?i--:(i=t.bottom,r=r>t.left?r-1:t.right);break}return{col:r,row:i}}function sE(e,t){let n=e.getActiveSheetId();if(e.isHeaderHidden(n,`COL`,t.col)||e.isHeaderHidden(n,`ROW`,t.row))return!1;let r=e.getMainCellPosition({sheetId:n,col:t.col,row:t.row});return r.col===t.col&&r.row===t.row}function cE(e,t,n){let{x:r,y:i,width:a,height:o}=n;if(a<0||o<0)return;let s=t.color||`#017E84`,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=s,t.thinLine?(c.lineWidth=1,c.strokeRect(r,i,a,o)):(c.lineWidth=2,c.strokeRect(r+.5,i+.5,a,o))),t.noFill||(c.fillStyle=Ef(uf(s),t.fillAlpha??.12),c.fillRect(r,i,a,o)),c.restore()}var lE=class extends Vr{mutators=[`register`,`unRegister`];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return[`Highlights`]}get highlights(){let e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{let{numberOfRows:t,numberOfCols:n}=cr(e.range.zone),r=t*n===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,r)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if(t===`Highlights`)for(let t of this.highlights)cE(e,t,e.viewports.getVisibleRect(e.sheetId,t.range.zone))}},uE=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},dE=class extends Vr{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`,`toggleEditMode`];ranges=[];focusedRangeIndex=null;mode=`text-edit`;inputSheetId;focusStore=this.get(uE);highlightStore=this.get(lE);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}this.mode=`select-range`}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,D({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=Nc(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return rr(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new Gf(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){let t=this.getIndex(e);if(this.focusedRangeIndex!==t||this.mode===`select-range`){this.focus(t),this.mode=`text-edit`;return}return`noStateChange`}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new Gf(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=Nc(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=Nc(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}toggleEditMode(){this.mode=this.mode===`select-range`?`text-edit`:`select-range`}},fE=class extends k{static template=`o-spreadsheet-SelectionInput`;props=(0,t.props)({ranges:W.array(W.string()),"hasSingleRange?":W.boolean(),"required?":W.boolean(),"autofocus?":W.boolean(),"isInvalid?":W.boolean(),"class?":W.string(),"onSelectionChanged?":W.function([W.array(W.string())]),"onSelectionConfirmed?":W.function([]),"onSelectionReordered?":W.function([W.array(W.number())]),"onSelectionRemoved?":W.function([W.number()]),"onInputFocused?":W.function([]),"colors?":W.ArrayOf(),"disabledRanges?":W.array(W.boolean()),"disabledRangeTitle?":W.string()},{colors:[],disabledRanges:[]});state=(0,t.proxy)({isMissing:!1});dragAndDrop=LT();focusedInputRef=(0,t.signal)(null);unfocusedInputRef=(0,t.signal)(null);selectionRef=(0,t.signal)(null);DOMFocusableElementStore;store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){(0,t.onWillStart)(()=>{}),(0,t.onWillUpdateProps)(async()=>{}),this.DOMFocusableElementStore=A(Cg),this.store=Ei(dE,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&(this.store.focusById(this.store.selectionInputs[0]?.id),this.props.onInputFocused?.()),(0,t.useEffect)(()=>{this.focusedInputRef()?.focus()}),hi(()=>{let e=this.selectionRef();(this.store.isResettable||this.store.hasFocus)&&e?.offsetParent===null&&this.reset()}),(0,t.onWillUpdateProps)(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),!T(e.disabledRanges,this.props.disabledRanges)&&!T(e.disabledRanges,this.store.disabledRanges)&&this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getRangeElementsRects(),r=this.ranges.map(e=>e.id),i=r.map((e,t)=>({id:e.toString(),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef(),onDragEnd:(t,n)=>{let i=r.findIndex(t=>t===e);if(i===n)return;let a=C(0,r.length);a.splice(i,1),a.splice(n,0,i),this.props.onSelectionReordered?.(a),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef().children).map(e=>e.getBoundingClientRect())}getColor(e){let t={};return e.color&&(t.color=e.color),this.store.mode===`select-range`&&(t[`caret-color`]=`transparent`),H(t)}triggerChange(){let e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){e.key===`F2`?(e.preventDefault(),e.stopPropagation(),this.store.toggleEditMode()):e.key.startsWith(`Arrow`)?(e.stopPropagation(),this.store.mode===`select-range`&&(e.preventDefault(),iE(e,this.env.model.selection))):e.key===`Enter`?(e.target.blur(),this.isConfirmable&&this.confirm()):e.key===`Escape`&&(this.reset(),this.DOMFocusableElementStore.focus())}extractRanges(e){return this.props.hasSingleRange?e.split(`,`)[0]:e}focus(e){this.state.isMissing=!1,this.store.focusById(e),this.props.onInputFocused?.()}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){let t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){let n=t.target,r=this.extractRanges(n.value);this.store.changeRange(e,r),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();let e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}},pE=class extends k{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:fE,Section:Z};props=(0,t.props)({ranges:W.ArrayOf(),"dataSetStyles?":W.DataSetStyle(),"hasSingleRange?":W.boolean(),onSelectionChanged:W.function([W.array(W.string())]),"onSelectionReordered?":W.function([W.array(W.number())]),"onSelectionRemoved?":W.function([W.number()]),onSelectionConfirmed:W.function([]),"maxNumberOfUsedRanges?":W.number(),"title?":W.string(),"datasetOrientation?":W.or([W.literal(`rows`),W.literal(`columns`)]),"canChangeDatasetOrientation?":W.boolean(),"onFlipAxis?":W.function([W.string()])});get ranges(){return this.props.ranges.map(e=>e.dataRange)}setup(){(0,t.onWillUpdateProps)(async()=>{})}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>this.props.dataSetStyles?.[e.dataSetId]?.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?j(`Data range`):j(`Data series`)}},mE=class extends k{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:fE,Checkbox:tE,Section:Z};props=(0,t.props)({"title?":W.string(),range:W.string(),"class?":W.string(),isInvalid:W.boolean(),onSelectionChanged:W.function([W.string()]),onSelectionConfirmed:W.function([]),"options?":W.ArrayOf()},{title:j(`Categories / Labels`),options:[]});get sectionClass(){return`o-data-labels`+(this.props.class?` ${this.props.class}`:``)}},hE=class extends k{static template=`o-spreadsheet-ChartDataSourceComponent`;static components={ChartDataSeries:pE,ChartLabelRange:mE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),updateChart:W.function([]),canUpdateChart:W.function([]),"onErrorMessagesChanged?":W.function([W.array(W.string())]),"dataSeriesTitle?":W.string(),"labelRangeTitle?":W.string(),"getLabelRangeOptions?":W.function([])});get DataSourceComponent(){let e=this.props.definition.dataSource.type;return eE.get(e)}},gE=class extends k{static template=`o-spreadsheet-ValidationMessages`;props=(0,t.props)({messages:W.array(W.string()),msgType:W.or([W.literal(`warning`),W.literal(`error`),W.literal(`info`)]),"singleBox?":W.boolean()});get divClasses(){return this.props.msgType===`warning`?`o-validation-warning`:this.props.msgType===`info`?`o-validation-info`:`o-validation-error`}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}},_E=class extends k{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:Z,ValidationMessages:gE};props=(0,t.props)({messages:W.array(W.string())})},vE=class extends k{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSourceComponent:hE,Section:Z,Checkbox:tE,ChartErrorSection:_E};props=(0,t.props)(nE);chartTerms=f_;state=(0,t.proxy)({errorMessages:[]});onErrorMessagesChanged(e){this.state.errorMessages=e}get errorMessages(){return this.state.errorMessages}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}getAggregateLabelRangeOption(){return{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in this.props.definition?this.props.definition.aggregated:!1)??!1,onChange:e=>{this.props.updateChart(this.props.chartId,{aggregated:e})}}}},yE=class extends vE{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}},bE=class extends k{static template=`o-spreadsheet-Collapse`;props=(0,t.props)({isCollapsed:W.boolean()});contentRef=(0,t.signal)(null);setup(){(0,t.onMounted)(()=>{this.props.isCollapsed&&this.contentRef()?.classList.add(`d-none`)}),(0,t.onWillUpdateProps)(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){let t=this.contentRef();if(!t)return;t.classList.remove(`d-none`),t.classList.add(`overflow-hidden`);let n=e?t.scrollHeight:0,r=e?0:t.scrollHeight,i=t.animate([{maxHeight:n+`px`},{maxHeight:r+`px`}],{duration:350,easing:`ease`});i.onfinish=()=>{t.classList.remove(`overflow-hidden`),this.props.isCollapsed&&t.classList.add(`d-none`)}}},xE=class extends k{static template=`o-spreadsheet-SidePanelCollapsible`;static components={Collapse:bE};props=(0,t.props)({"title?":W.string(),"isInitiallyCollapsed?":W.boolean(),"class?":W.string()});state=(0,t.proxy)({isCollapsed:!!this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}},SE=class extends WT{static template=`o-spreadsheet-NumberInput`;static components={};props=(0,t.props)({...UT,"min?":W.number(),"max?":W.number()});debouncedOnChange=Ht(this.props.onChange.bind(this),100,!0);save(){let e=(this.genericInputRef()?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},CE=class extends SE{static template=`o-spreadsheet-DateInput`},wE=class extends k{static template=`o-spreadsheet.BadgeSelection`;props=(0,t.props)({choices:W.ArrayOf(),onChange:W.function([W.string()]),selectedValue:W.string()})},TE=class extends k{static template=`o-spreadsheet.ChartTitle`;static components={Section:Z,TextStyler:ZT,TextInput:GT};props=(0,t.props)({"title?":W.string(),"placeholder?":W.string(),updateTitle:W.function([W.string()]),"name?":W.string(),style:W.TitleDesign(),"defaultStyle?":W.object({}),updateStyle:W.function([W.object({})])},{title:``,placeholder:``});updateTitle(e){this.props.updateTitle(e)}},EE=class extends k{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:Z,ChartTitle:TE,BadgeSelection:wE,Checkbox:tE,NumberInput:SE,DateInput:CE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartWithAxisDefinition(),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),axesList:W.ArrayOf()});state=(0,t.proxy)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title?.text||``}updateAxisTitle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}get axisMin(){let e=this.currentAxisDesign?.min;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get axisMax(){let e=this.currentAxisDesign?.max;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get isMajorGridEnabled(){let e=this.currentAxisDesign?.gridLines;return e===void 0?this.getDefaultMajorGridValue(this.state.currentAxis):e===`major`||e===`both`}get isMinorGridEnabled(){return this.currentAxisDesign?.gridLines===`minor`||this.currentAxisDesign?.gridLines===`both`}get isValueAxis(){return`horizontal`in this.props.definition&&this.props.definition.horizontal?this.state.currentAxis===`x`:this.state.currentAxis!==`x`}get majorGridLabel(){return this.state.currentAxis===`x`?j(`Major vertical gridlines`):j(`Major horizontal gridlines`)}get minorGridLabel(){return this.state.currentAxis===`x`?j(`Minor vertical gridlines`):j(`Minor horizontal gridlines`)}updateAxisMin(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMin(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}updateAxisMax(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMax(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}toggleMajorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMinorGridEnabled?e?`both`:`minor`:e?`major`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}toggleMinorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMajorGridEnabled?e?`both`:`major`:e?`minor`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}get currentAxisDesign(){return this.props.definition.axesDesign?.[this.state.currentAxis]}getDefaultMajorGridValue(e){let{useLeftAxis:t,useRightAxis:n}=Dp(this.props.definition);if(e===`x`){if(`horizontal`in this.props.definition&&this.props.definition.horizontal||this.props.definition.type===`scatter`)return!0}else if(e===`y`)return!0;else if(e===`y1`)return!t&&n;return!1}get isCategoricalAxis(){if(this.isValueAxis)return!1;let e=this.getXAxisType();return e===void 0||e===`category`}get isTimeAxis(){return this.state.currentAxis===`x`&&this.getXAxisType()===`time`}get canChangeMinorGridVisibility(){if(this.isValueAxis)return!0;if(this.isCategoricalAxis)return!1;let e=this.props.definition.type;return e===`line`||e===`scatter`}parseTimeAxisBoundaryValue(e){let t=P(e,this.env.model.getters.getLocale());return Number.isNaN(t)?null:t}formatAxisBoundary(e){if(e!==void 0)return z(e,{format:`yyyy-mm-dd`,locale:this.env.model.getters.getLocale()})}getXAxisType(){return this.env.model.getters.getChartRuntime(this.props.chartId)?.chartJsConfig.options?.scales?.x?.type}},DE=class extends k{static template=`o-spreadsheet.RadioSelection`;props=(0,t.props)({choices:W.ArrayOf(),onChange:W.function([W.any()]),selectedValue:W.string(),name:W.string(),"direction?":W.or([W.literal(`horizontal`),W.literal(`vertical`)])},{direction:`horizontal`})},OE=class extends k{static template=`o-spreadsheet.RoundColorPicker`;static components={Section:Z,ColorPicker:qT};props=(0,t.props)({"currentColor?":W.string(),"title?":W.string(),onColorPicked:W.function([W.string()]),"disableNoColor?":W.boolean()});colorPickerButtonRef=(0,t.signal)(null);state;setup(){this.state=(0,t.proxy)({pickerOpened:!1}),mi(window,`click`,this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return y(this.colorPickerButtonRef())}get buttonStyle(){return H({background:this.props.currentColor})}},kE=class extends k{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:OE,ChartTitle:TE,Section:Z,SidePanelCollapsible:xE,RadioSelection:DE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinition(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),"defaultChartTitleFontSize?":W.number()},{defaultChartTitleFontSize:16});state;setup(){this.state=(0,t.proxy)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},AE=class extends k{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:tE};props=(0,t.props)(nE);get title(){let e=this.env.model.getters.getLocale();return j(`E.g. 1234567 -> %(value)s`,{value:z(1234567,{format:Hs({value:1234567},void 0,e),locale:e})})}},jE=class extends k{static template=`o-spreadsheet-ChartLegend`;static components={Section:Z,Select:t_};props=(0,t.props)({chartId:W.string(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function(),updateChart:W.function(),"isDisabled?":W.boolean()},{isDisabled:!1});updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:j(`None`)},{value:`top`,label:j(`Top`)},{value:`bottom`,label:j(`Bottom`)},{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}]}},ME=class extends k{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:xE,Section:Z,RoundColorPicker:OE,Select:t_};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())});state=(0,t.proxy)({dataSetId:this.getDataSeries()[0]?.dataSetId||``});getRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!e||!(`customizableSeries`in e))throw Error(`SeriesDesignEditor: chart runtime is not compatible with series customization.`);return e}getDataSeries(){return this.getRuntime().customizableSeries}updateEditedSeries(e){this.state.dataSetId=e}updateDataSeriesColor(e){let t={...this.props.definition.dataSetStyles};t[this.state.dataSetId]={...t[this.state.dataSetId],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSetStyles:t})}getDataSeriesColor(){let e=this.props.definition.dataSetStyles?.[this.state.dataSetId]?.backgroundColor,t=this.getDataSeries(),n=t.findIndex(e=>e.dataSetId===this.state.dataSetId);return e?uf(e):Hf(n,Uf(t.length))}updateDataSeriesLabel(e){let t=e.target.value,n={...this.props.definition.dataSetStyles};n[this.state.dataSetId]={...n[this.state.dataSetId],label:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesLabel(){return this.props.definition.dataSetStyles?.[this.state.dataSetId]?.label||this.getDataSeries().find(e=>e.dataSetId===this.state.dataSetId)?.label||``}get selectOptions(){return this.getDataSeries().map(({label:e,dataSetId:t})=>({value:t,label:e}))}},NE=class extends k{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:ME,Checkbox:tE,RadioSelection:DE,Section:Z,RoundColorPicker:OE,NumberInput:SE,Select:t_};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([W.UID(),W.object({})],W.DispatchResult()),updateChart:W.function([W.UID(),W.object({})],W.DispatchResult())});axisChoices=Ap;updateDataSeriesAxis(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSerieAxis(e){let t=this.props.definition.dataSetStyles;return t?.[e]&&t[e]?.yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e]?.trend,display:t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getTrendLineConfiguration(e){return this.props.definition.dataSetStyles?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n;switch(t){case`linear`:case`polynomial`:n={type:`polynomial`,order:t===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:n={type:t};break;default:return}this.updateTrendLineValue(e,n)}get trendOptions(){return[{value:`linear`,label:j(`Linear`)},{value:`polynomial`,label:j(`Polynomial`)},{value:`exponential`,label:j(`Exponential`)},{value:`logarithmic`,label:j(`Logarithmic`)},{value:`trailingMovingAverage`,label:j(`Trailing moving average`)}]}getPolynomialDegrees(e){return C(1,this.getMaxPolynomialDegree(e)+1).map(e=>({value:e.toString(),label:e.toString()}))}onChangePolynomialDegree(e,t){this.updateTrendLineValue(e,{order:parseInt(t)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId),n=t.customizableSeries.findIndex(t=>t.dataSetId===e);return Math.min(10,t.chartJsConfig.data.datasets[n].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSetStyles;if(!t?.[e])return``;let n=t[e]?.backgroundColor,r=this.env.model.getters.getChartRuntime(this.props.chartId),i=r.customizableSeries.findIndex(t=>t.dataSetId===e);return n?uf(n):Hf(i,Uf(r.customizableSeries.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Ef(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{...n[e]?.trend,...t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}},PE=class extends k{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:tE};props=(0,t.props)({chartId:W.UID(),definition:W.ChartDefinitionWithDataSource(),canUpdateChart:W.function([]),updateChart:W.function([]),"defaultValue?":W.boolean()})},FE=class extends k{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:kE,SidePanelCollapsible:xE,Section:Z,AxisDesignEditor:EE,SeriesWithAxisDesignEditor:NE,ChartLegend:jE,ChartShowValues:PE,ChartHumanizeNumbers:AE};props=(0,t.props)(nE);get axesList(){let{useLeftAxis:e,useRightAxis:t}=Dp(this.props.definition),n=[{id:`x`,name:j(`Horizontal axis`)}];return e&&n.push({id:`y`,name:j(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:j(e?`Right axis`:`Vertical axis`)}),n}},IE=class extends FE{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...FE.components,Checkbox:tE};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},LE=class extends IE{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}},RE=class extends k{static template=`o-spreadsheet-BubbleChartConfigPanel`;static components={ChartDataSeries:pE,ChartLabelRange:mE,ChartErrorSection:_E};props=(0,t.props)(nE);state=(0,t.proxy)({datasetDispatchResult:void 0,labelsDispatchResult:void 0,xRangeDispatchResult:void 0,sizeRangeDispatchResult:void 0});yRanges=[];labelRange;datasetOrientation;xRange;sizeRange;setup(){let e=this.props.definition;this.yRanges=e.yRanges||[],this.labelRange=e.labelRange,this.xRange=e.xRange,this.sizeRange=e.sizeRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.xRangeDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[],...this.state.sizeRangeDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>f_.Errors[e]||f_.Errors.Unexpected)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(`InvalidLabelRange`)}get isXDataInvalid(){return!!this.state.xRangeDispatchResult?.isCancelledBecause(`InvalidXRange`)}get isYDataInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(`InvalidYRange`)}get isBubbleSizeRangeInvalid(){return!!this.state.sizeRangeDispatchResult?.isCancelledBecause(`InvalidBubbleSizeRange`)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?j(`Use col %(column_name)s as headers`,{column_name:Cn(this.calculateHeaderPosition()||0)}):j(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getDataSeriesRanges(){return this.yRanges.map((e,t)=>({dataRange:e,dataSetId:`${t}`}))}onDataSeriesRangesChanged(e){this.yRanges=e,this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesConfirmed(){this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesReordered(e){this.yRanges=e.map(e=>this.yRanges[e]),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onDataSeriesRemoved(e){this.yRanges=this.yRanges.filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{yRanges:this.yRanges})}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}onXDataRangeChanged(e){this.xRange=e[0],this.state.xRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{xRange:this.xRange})}onXDataRangeConfirmed(){this.state.xRangeDispatchResult=this.props.updateChart(this.props.chartId,{xRange:this.xRange})}onBubbleSizeRangeChanged(e){this.sizeRange=e[0],this.state.sizeRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{sizeRange:this.sizeRange})}onBubbleSizeRangeConfirmed(){this.state.sizeRangeDispatchResult=this.props.updateChart(this.props.chartId,{sizeRange:this.sizeRange})}getLabelRangeOptions(){let e=this.props.definition;return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}calculateHeaderPosition(){if(this.isYDataInvalid)return;let e=this.yRanges[0]??this.xRange??``,t=this.env.model.getters,n=Bl(t,t.getActiveSheetId(),e||``)?.zone;if(n)return this.datasetOrientation===`rows`?n.left:n.top+1}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.yRanges){let r=this.env.model.getters,i=Bl(r,r.getActiveSheetId(),n)?.zone;if(!i)return;i.top===i.bottom&&(e=!0),i.left===i.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}},zE=class extends k{static template=`o-spreadsheet-BubbleChartDesignPanel`;static components={GeneralDesignEditor:kE,SidePanelCollapsible:xE,Section:Z,AxisDesignEditor:EE,ChartLegend:jE,ChartShowValues:PE,ChartHumanizeNumbers:AE,RadioSelection:DE,RoundColorPicker:OE,Checkbox:tE};props=(0,t.props)(nE);get axesList(){return[{id:`x`,name:j(`Horizontal axis`)},{id:this.verticalAxisPosition===`right`?`y1`:`y`,name:j(`Vertical axis`)}]}colorModeChoices=[{value:`single`,label:j(`Single color`)},{value:`multiple`,label:j(`Multiple colors`)}];axisChoices=Ap;get colorMode(){return this.props.definition.bubbleColor.color===`multiple`?`multiple`:`single`}onColorModeChange(e){this.updateBubbleColor(e===`multiple`?`multiple`:Pf)}get verticalAxisPosition(){return this.props.definition.verticalAxisPosition??`left`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}updateBubbleColor(e){let t=this.props.definition.bubbleColor;this.props.updateChart(this.props.chartId,{bubbleColor:{...t,color:e}})}get currentBubbleColor(){return this.colorMode===`multiple`?Pf:this.props.definition.bubbleColor.color}get areBubblesTransparent(){return this.props.definition.bubbleColor.transparent||!1}updateBubbleTransparency(e){let t=this.props.definition.bubbleColor;this.props.updateChart(this.props.chartId,{bubbleColor:{...t,transparent:e}})}};function BE(e){return e=uf(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let VE=Symbol(`NULL`);function HE(e,t,n){let r=e.granularity||`month`;if(!(r in UE))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:VE;if(!UE[r].set.has(t)){UE[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=co(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(P(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(P(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}UE[r].values[i]=HS(e,a)}return UE[r].values[i]}let UE={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function WE(){for(let e in UE)UE[e].set.clear(),UE[e].values={}}let GE=Object.freeze({value:null}),KE=Object.freeze({value:0});function qE(e,{labelValues:t,dataSetsValues:n},r){let i=r.getLocale(),a=t.map(({value:e,format:t})=>z(e,{format:t,locale:i}));({labels:a,dataSetsValues:n}=bD(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=wD(a,n));let o=ED(e.dataSetStyles,n,`left`),s=ED(e.dataSetStyles,n,`right`),c=e.horizontal?{x:o||s}:{y:o,y1:s},l=[];for(let t in n){let{data:r,dataSetId:i}=n[t],a=e.dataSetStyles?.[i]?.trend;if(!a?.display||e.horizontal){l.push(void 0);continue}let o=oD(a,r);l.push(o)}return{dataSetsValues:n,trendDataSetsValues:l,axisFormats:c,labels:a,locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function JE(e,t){switch(t){case`day_of_week`:return ps[e-1].toString();case`hour_number`:{let t=String(e%12).padStart(2,`0`);return j(e<12?`%(hour)s AM`:`%(hour)s PM`,{hour:t})}case`month_number`:return fs[e-1].toString();case`iso_week_number`:return j(`W%(weekNumber)s`,{weekNumber:String(e).padStart(2,`0`)});case`quarter_number`:return j(`Q%(value)s`,{value:e});default:return e.toString()}}function YE(e,t,n,r,i){let a={},o=[],s=[],c=[];for(let l=0;l<e?.length;l++){let u=P(HE({granularity:n,type:`date`,displayName:`date`},e[l].value,R),i);u in a||(o.push(u),a[u]={});let d=P(HE({granularity:r,type:`date`,displayName:`date`},e[l].value,R),i);c.includes(d)||(s.push(d),c.push(d)),d in a[u]||(a[u][d]={value:0});let f=t[l];V(f)&&(a[u][d].value+=f.value)}return o.sort((e,t)=>e-t),s.sort((e,t)=>t-e),{dataSetsValues:s.map(e=>({data:o.map(t=>a?.[t]?.[e]),label:JE(e,r),hidden:!1,dataSetId:`0`})),labels:o.map(e=>({value:JE(e,n)}))}}function XE(e,{labelValues:t,dataSetsValues:n},r){let i=t,a=r.getLocale();({labels:i,dataSetsValues:n}=xD(i,n));let o={y:ED(e.dataSetStyles,n,`left`)};return{labels:i,dataSetsValues:n}=YE(i,n[0]?.data??[],e.horizontalGroupBy??`day_of_week`,e.verticalGroupBy??`hour_number`,a),{dataSetsValues:n,axisFormats:o,labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function ZE(e,{labelValues:t,dataSetsValues:n},r){let i=qE(e,{labelValues:t,dataSetsValues:n.slice(0,2)},r),a=i.dataSetsValues.filter(e=>!e.hidden),o=[];if(a[0]){let e=a[0].data.map(e=>V(e)&&e.value>0?e:KE);o.push({...a[0],data:e})}if(a[1]){let e=a[1].data.map(e=>V(e)&&e.value>0?{value:-e.value}:KE);o.push({...a[1],data:e})}return{...i,dataSetsValues:o}}function QE(e,{labelValues:t,dataSetsValues:n},r){let i=uD(e,{labelValues:t,dataSetsValues:n}),a=i===`linear`?t.map(({value:e})=>String(e??``)):t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:a,dataSetsValues:n}=bD(a,n)),i===`time`&&({labels:a,dataSetsValues:n}=yD(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=wD(a,n)),e.cumulative&&(n=DD(n,`asc`));let o={y:ED(e.dataSetStyles,n,`left`),y1:ED(e.dataSetStyles,n,`right`),x:TD(t)},s=[];for(let t in n){let{data:o,dataSetId:c}=n[t],l=e.dataSetStyles?.[c]?.trend;if(!l?.display){s.push(void 0);continue}s.push(sD(l,o,a,i,r.getLocale()))}return{dataSetsValues:n,axisFormats:o,labels:a,locale:r.getLocale(),trendDataSetsValues:s,axisType:i,topPadding:OD(e,r),background:Pp(e,r)}}function $E(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n)),{dataSetsValues:n,labels:i}=vD(i,n);let a=ED(e.dataSetStyles,n,`left`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),topPadding:OD(e,r),background:Pp(e,r)}}function eD(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n));let a={r:ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`)};return{dataSetsValues:n,axisFormats:a,labels:i,locale:r.getLocale(),background:Pp(e,r)}}function tD(e,{labelValues:t,dataSetsValues:n},r){n=n.slice(0,1);let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=wD(i,n));let a=ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),availableRegions:r.getGeoChartAvailableRegions(),geoFeatureNameToId:r.geoFeatureNameToId,getGeoJsonFeatures:r.getGeoJsonFeatures,background:Pp(e,r)}}function nD(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>z(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=bD(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=wD(i,n)),e.cumulative&&(n=DD(n,`desc`));let a=ED(e.dataSetStyles,n,`left`)||ED(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{x:a},labels:i,locale:r.getLocale(),background:Pp(e,r)}}function rD(e,{labelValues:t,dataSetsValues:n},r){let i=t;return{labels:i,dataSetsValues:n}=CD(i,n),{labels:i,dataSetsValues:n}=SD(i,n),{dataSetsValues:n,axisFormats:{y:TD(i)},labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),background:Pp(e,r)}}function iD(e,t){let n=aD(e,t),r=QE(e,n,t),i=e.labelRange?t.getVisibleRangeValues(e.labelRange):[],a=e.sizeRange?t.getVisibleRangeValues(e.sizeRange):[];n.shouldRemoveFirstLabel&&(i=i.slice(1),a=a.slice(1));let o=[],s=[],c=TD(a);for(let e=0;e<r.dataSetsValues[0].data.length;e++){let t=a[e]?.value,n=i[e],c=n?z(n.value,{format:n.format,locale:r.locale}):``,l=t===null?void 0:eo(t,r.locale);l!==void 0&&l<0&&(l=void 0),o.push(c?String(c):``),s.push(l)}let l=C(0,s.length).sort((e,t)=>{let n=s[e],r=s[t];return n===void 0&&r===void 0?0:n===void 0?1:r===void 0?-1:r-n});return r.dataSetsValues[0]={...r.dataSetsValues[0],data:l.map(e=>r.dataSetsValues[0].data[e])},{...r,axisFormats:{...r.axisFormats||{},size:c},labels:l.map(e=>r.labels[e]),bubbleLabels:l.map(e=>o[e]),bubbleSizes:l.map(e=>s[e])}}function aD(e,t){let n=e.yRanges[0],r=e.xRange?t.getVisibleRangeValues(e.xRange):n?Array.from({length:t.getVisibleRangeValues(n).length},()=>GE):[],i=n?t.getVisibleRangeValues(n):[],a=Tp(r.length,i.length,e.dataSetsHaveTitle||!1);return{labelValues:a?r.slice(1):r,dataSetsValues:[{dataSetId:`0`,label:``,data:a?i.slice(1):i}],shouldRemoveFirstLabel:a}}function oD(e,t){let n=[],r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e];V(a)&&(n.push(a.value),r.push(e+1)),i.push(e+1)}let a=cD(e,n,r,C(.5,i.length+.55,.2));return a.length?a:void 0}function sD(e,t,n,r,i){let a=[],o=[],s=[],c=t.length;if(c<2)return;switch(r){case`category`:for(let e=0;e<c;e++){let n=t[e];V(n)&&(a.push(n.value),o.push(e+1)),s.push(e+1)}break;case`linear`:for(let e=0;e<t.length;e++){let r=Number(n[e]);if(isNaN(r))continue;let i=t[e];V(i)&&(a.push(i.value),o.push(r)),s.push(r)}break;case`time`:for(let e=0;e<t.length;e++){let r=P({value:n[e]},i),c=t[e];V(c)&&(a.push(c.value),o.push(r)),s.push(r)}break}let l=Math.min(...s),u=Math.max(...s);if(u===l)return;let d=5*s.length,f=(u-l)/d,p=cD(e,a,o,C(l,u+f/2,f));if(p.length)return p}function cD(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=lD(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return r.map(e=>({x:e,y:NaN}));if(n===1)return dS([t],[i],[a],!0)[0].map((e,t)=>({x:r[t],y:e}));let o=oS(t,i,n,!0).flat();return a.map((e,t)=>({x:r[t],y:cS(o,e,n)}))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?lS(dS([e],[n],[a],!0))[0].map((e,t)=>({x:r[t],y:e})):r.map(e=>({x:e,y:NaN}))}case`logarithmic`:return dS([t],uS([i]),uS([a]),!0)[0].map((e,t)=>({x:r[t],y:e}));case`trailingMovingAverage`:return fS(t,n,e.window);default:return r.map(e=>({x:e,y:NaN}))}}catch{return r.map(e=>({x:e,y:NaN}))}}function lD(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function uD(e,t){return dD(e,t)&&_D()?`time`:fD(e,t)?`linear`:`category`}function dD(e,t){return!e.labelsAsText&&mD(t)}function fD(e,t){return!e.labelsAsText&&hD(t)}function pD(e){return mD(e)||hD(e)}function mD(e){if(!hD(e))return!1;let t=TD(e.labelValues);return!!(t&&Kp.test(t))}function hD(e){let t=e.labelValues;return!(t.some(e=>!V(e)&&e.value)||t.every(e=>!e.value))}let gD=!1;function _D(){if(!window.Chart)return!1;let e=new window.Chart._adapters._date({})._id===`luxon`;return!e&&!gD&&(gD=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),e}function vD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(e=>t.some(t=>V(t.data[e])&&t.data[e].value>0));return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])&&e.data[t].value>0?e.data[t]:GE)}))}}function yD(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=x(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=qt(n,e);for(let t of r)t.data[e]=GE}return{labels:n,dataSetsValues:r}}function bD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return r||i.some(V)});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])?e.data[t]:GE)}))}}function xD(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return V(r)&&V(i[0])});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>V(e.data[t])?e.data[t]:GE)}))}}function SD(e,t){let n=Math.max(e.length,...t.map(e=>e.data?.length||0)),r=e=>e===null||e===``,i=C(0,n).filter(n=>{let i=t.map(e=>e.data?.[n]);if(r(i[0]?.value))return!1;let a=!1;for(let e of i)if(a||=r(e?.value),a&&!r(e?.value))return!1;return e[n]&&V(e[n])});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function CD(e,t){let n=[],r=[];for(let t=0;t<e.length;t++)Number(e[t].value)<=0?r.push(t):Number(e[t].value)>0&&n.push(t);let i=n.length?n:r;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function wD(e,t){let n=e=>typeof e==`number`?e:0,r=new Set(e),i={};r.forEach(e=>{i[e]=Array(t.length)});for(let r of C(0,e.length)){let a=e[r];for(let e of C(0,t.length)){let o=t[e].data[r];i[a][e]?i[a][e].value+=n(o?.value):i[a][e]={...o,value:n(o?.value)}}}return{labels:Array.from(r),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(r).map(e=>i[e][t])}))}}function TD(e){return e.find(({format:e})=>e!==void 0)?.format}function ED(e,t,n){let r=t.filter(t=>n===`right`==(e?.[t.dataSetId]?.yAxisId===`y1`));for(let e of r){let t=e.data.find(({format:e})=>e!==void 0&&!Os(e));if(t)return t.format}}function DD(e,t){return e.map(e=>{let n=[],r=0,i=t===`asc`?C(0,e.data.length):C(0,e.data.length).reverse();for(let t of i){let i=e.data[t];V(i)?(r+=i.value,n[t]={...i,value:r}):n[t]=GE}return{...e,data:n}})}function OD(e,t){let{title:n,legendPosition:r}=e,i=n&&n.text||r===`top`;return t.isDashboard()&&!i?30:0}function kD(e,t){return{padding:{left:20,right:20,top:Math.max(15,t.topPadding||0),bottom:10}}}function AD(e,t){let n=e.legendPosition;return{padding:{left:20+(n===`left`?70:0),right:20+(n===`right`?70:0),top:Math.max(15,t.topPadding||0),bottom:10}}}let jD=.2;function MD(e,t){let n=e.datasetIndex;for(let e=0;e<t.length;e++){if(e===n)continue;let r=t[e];for(let t of[`borderColor`,`backgroundColor`])t in r&&(r[t]=Ef(r[t],e===n?1:jD))}}function ND(e){for(let t of e)for(let e of[`borderColor`,`backgroundColor`])e in t&&(t[e]=Ef(t[e],1))}function PD(e,t){let n=e.datasetIndex;for(let e=0;e<t.length;e++){let r=t[e],i=Ef(r.borderColor,e===n?1:jD);r.borderColor=i,r.pointBackgroundColor=i,r.backgroundColor=Ef(r.backgroundColor,tt*(e===n?1:jD))}}function FD(e){for(let t of e){let e=Ef(t.borderColor,1);t.borderColor=e,t.pointBackgroundColor=e,t.backgroundColor=Ef(t.backgroundColor,tt)}}function ID(e,t){let n=t.datasetIndex;n!==void 0&&(e.isDatasetVisible(n)?e.hide(n):e.show(n))}function LD(e,t){for(let n of t){let t=n.backgroundColor;if(!t)return;t.forEach((t,n,r)=>{r[n]=Ef(t,n===e.index?1:jD)})}}function RD(e){for(let t of e){let e=t.backgroundColor;if(!e)return;e.forEach((e,t,n)=>{n[t]=Ef(e,1)})}}function zD(e,t){let n=t.index;n!==void 0&&e.toggleDataVisibility(n)}function BD({legendPosition:e}){return{display:e!==`none`,position:e===`none`?void 0:e}}function VD(e,t){return{...ZD({highlightItem:MD,unHighlightItems:ND,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{lineWidth:3})}}function HD(e,t){return{...BD(e),...$D(xp(e.background),{pointStyle:`rect`,lineWidth:3})}}function UD(e,t){let n=e.fillArea,r=n?`rect`:`line`,i=n?2:3;return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{pointStyle:r,lineWidth:i})}}function WD(e,t){let{dataSetsValues:n}=t,r=jp(new Gf(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n),i=xp(e.background);return{...ZD({highlightItem:LD,unHighlightItems:RD,toggleDataVisibility:zD}),...BD(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((t,n)=>({text:Mp(String(t)),strokeStyle:r[n],fillStyle:r[n],pointStyle:`rect`,lineWidth:2,fontColor:i,index:n,hidden:!e.getDataVisibility?.(n)}))||[]).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function GD(e,t){return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...tO(xp(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8})}}function KD(e,t){return e.bubbleColor.color===`multiple`?{...QD,...BD(e),...eO(xp(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8},t.bubbleLabels)}:{display:!1}}function qD(e,t){return{...ZD({highlightItem:MD,unHighlightItems:ND,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{lineWidth:3})}}function JD(e,t){let n=xp(e.background),r=e.negativeValuesColor||`#EA6175`,i=e.positiveValuesColor||`#4EA7F2`,a=e.subTotalValuesColor||`#AAAAAA`;return{...BD(e),labels:{usePointStyle:!0,generateLabels:()=>{let t=[{text:j(`Positive values`),fontColor:n,fillStyle:i,strokeStyle:i,pointStyle:`rect`},{text:j(`Negative values`),fontColor:n,fillStyle:r,strokeStyle:r,pointStyle:`rect`}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:j(`Subtotals`),fontColor:n,fillStyle:a,strokeStyle:a,pointStyle:`rect`}),t},filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0},onClick:()=>{}}}function YD(e,t){let n=e.fillArea??!1,r=n?`rect`:`line`,i=n?2:3;return{...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),...BD(e),...$D(xp(e.background),{pointStyle:r,lineWidth:i})}}function XD(e,t){let n=xp(e.background);return{...BD(e),labels:{usePointStyle:!0,generateLabels:e=>{let t=e.data.datasets.at(-1);return t?t.groupColors.map(({color:e,label:t})=>({text:Mp(t),fontColor:n,fillStyle:e,strokeStyle:e,pointStyle:`rect`})):[]}}}}function ZD({highlightItem:e,unHighlightItems:t,toggleDataVisibility:n}){return{onHover:(t,n,r)=>{if(!n.hidden){let t=r.chart.data.datasets;e(n,t),r.chart.update()}let i=t.native?.target;i&&i instanceof HTMLElement&&(i.style.cursor=`pointer`)},onLeave:(e,n,r)=>{if(!n.hidden){let e=r.chart.data.datasets;t(e),r.chart.update()}let i=e.native?.target;i&&i instanceof HTMLElement&&(i.style.cursor=`default`)},onClick:(r,i,a)=>{r.type!==`click`||!a.legendItems||(a.chart.options.animation&&(a.chart.options.animation=!1),n(a.chart,i),i.hidden?e(i,a.chart.data.datasets):t(a.chart.data.datasets),a.chart.update(),r.native.preventDefault(),r.native.stopPropagation())}}}let QD={...ZD({highlightItem:PD,unHighlightItems:FD,toggleDataVisibility:ID}),onClick:(e,t,n)=>{if(e.type!==`click`)return;let r=t.datasetIndex;if(r===void 0)return;let i=n.chart.getDatasetMeta(0),a=i.data[r].hidden;i.data[r].hidden=!a,n.chart.update(),e.native.preventDefault(),e.native.stopPropagation()}};function $D(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>Np(r.xAxisID)?{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.backgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:r.type===`line`?`line`:`rect`,datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function eO(e,t,n){return{labels:{color:e,usePointStyle:!0,generateLabels:r=>{if(!r.data.datasets[0])return[];let i=r.data.datasets[0].backgroundColor,a=typeof i==`string`?r.data.datasets[0].data.map(()=>i):i;return r.data.datasets[0].data.map((i,o)=>({text:n[o],fontColor:e,strokeStyle:a?.[o],fillStyle:a?.[o],hidden:r.getDatasetMeta(0).data[o].hidden,pointStyle:`rect`,datasetIndex:o,...t})).filter(e=>e.text)},filter:(e,t)=>!0}}}function tO(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>Np(r.xAxisID)?{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Mp(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.pointBackgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:`circle`,datasetIndex:i,lineWidth:8,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}let nO={showValues:!1,showLabels:!0,valuesDesign:{align:`center`,fontSize:13}};function rO(e,t){let{axisFormats:n,locale:r}=t;return{type:e.type,horizontal:`horizontal`in e&&e.horizontal,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i)=>{let a=cO(e,i);return Op(n,r,e.humanize)(t,a)}}}function iO(e,t){let{locale:n,axisFormats:r}=t,i=(t,n,r)=>e.background,a=t.dataSetsValues.flat().flatMap(e=>e?.data.filter(V)).map(e=>e.value);if(a.length){let t=Math.min(...a),n=Math.max(...a),r=pm(e.colorScale??cC(`oranges`),t,n);i=(t,n,i)=>{let a=n._dataset.values[i];return a===void 0?e.background:xp(r(a))}}return{type:`calendar`,horizontal:!1,showValues:`showValues`in e?!!e.showValues:!1,background:i,callback:(e,t,i)=>{let a=t._dataset.values[i];return a===void 0?``:Vs({value:a,format:r?.y},n)}}}function aO(e,t){let{axisFormats:n,locale:r}=t;return{callback:Op(n,r,e.humanize),showLabels:e.showLabels??nO.showLabels,showValues:e.showValues??nO.showValues,style:{fontSize:Rd(e.valuesDesign?.fontSize??nO.valuesDesign.fontSize),align:e.valuesDesign?.align??nO.valuesDesign.align,bold:e.valuesDesign?.bold??nO.valuesDesign.bold,italic:e.valuesDesign?.italic??nO.valuesDesign.italic,textColor:e.valuesDesign?.color??nO.valuesDesign.color}}}function oO(e,t){let{axisFormats:n,locale:r}=t;return{type:`pyramid`,horizontal:!0,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(e,t)=>(e=Math.abs(Number(e)),e===0?``:Op(n,r)(e,t.xAxisID||`x`))}}function sO(e,t){let{axisFormats:n,locale:r,dataSetsValues:i}=t,a=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:`waterfall`,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i,o)=>{let s=i._dataset.data[o],c=s[1]-s[0],l=c>=0?`+`:``;return e.showSubTotals&&a.includes(o)&&l===`+`&&(l=``),`${l}${Op(n,r,e.humanize)(c,i.yAxisID)}`}}}function cO(e,t){return t.rAxisID?t.rAxisID:(`horizontal`in e&&e.horizontal?t.xAxisID:t.yAxisID)||`y`}function lO({title:e,legendPosition:t,background:n},r){let i=Sp(n);return{display:!!e.text,text:e.text?r.dynamicTranslate(e.text):``,color:e?.color??i,align:e.align===`center`?`center`:e.align===`right`?`end`:`start`,font:{size:Rd(e.fontSize??16),weight:e.bold?`bold`:`normal`,style:e.italic?`italic`:`normal`},padding:{bottom:t===`top`?0:20}}}let uO;function dO(e,t={}){return fO(e,t).innerHTML}function fO(e,n={}){uO||=new t.App({templates:`
39
39
  <templates>
40
40
  <t t-name="o-spreadsheet-CustomTooltip">
41
41
  <div
@@ -115,7 +115,7 @@ stores.inject(MyMetaStore, storeInstance);
115
115
  />`;props=(0,t.props)({"topOffset?":W.number()},{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:fe()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},ZL=class extends k{static template=`o-spreadsheet-Selection`;static components={Highlight:KL};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:Oe}}},QL=class extends k{static template=`o-spreadsheet-TableResizer`;props=(0,t.props)({table:W.Table()});state=(0,t.proxy)({highlightZone:void 0});dragNDropGrid=FI(this.env);setup(){dA(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 H({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?H({display:`none`}):H({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=hh(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 $L={ROW:jI,COL:wI,CELL:lI,GROUP_HEADERS:kI,UNGROUP_HEADERS:AI};var eR=class extends k{static template=`o-spreadsheet-Grid`;static components={GridComposer:uL,GridOverlay:OL,GridPopover:kL,HeadersOverlay:IL,MenuPopover:e_,Autofill:LI,ClientTag:zI,Highlight:KL,Popover:Xg,VerticalScrollBar:XL,HorizontalScrollBar:YL,TableResizer:QL,Selection:ZL};props=(0,t.props)({exposeFocus:W.function([W.function([])]),getGridSize:W.function([],W.DOMDimension())});HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef=(0,t.signal)(null);canvasRef=(0,t.signal)(null);highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=FI(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=A(lE),this.menuState=(0,t.proxy)({isOpen:!1,anchorRect:null,menuItems:[]}),this.hoveredCell=A(c_),this.composerFocusStore=A(Ur),this.DOMFocusableElementStore=A(Cg),this.sidePanel=A(jP),this.paintFormatStore=A(wL),this.clientFocusStore=A(NI),A(MI),bi({getPopoverContainerRect:()=>this.getGridRect()}),mi(document.body,`cut`,this.copy.bind(this,!0)),mi(document.body,`copy`,this.copy.bind(this,!1)),mi(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),RL({canvasRef:this.canvasRef,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=HL((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=A(BC),hi((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),BL(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 H({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":()=>zw(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&&sd(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":()=>{PC(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{PC(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{PC(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":()=>mw(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?Aw(this.env):i&&!r&&Ow(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":()=>{MT.execute?.(this.env)},"Alt+T":()=>{yT.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+Shift+K":()=>{this.closeMenu(),Hw(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}aE(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}aE(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.getSelectedFigureIds().length&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){let e=this.gridRef();if(!e)throw Error(`Grid el is not defined.`);return e}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{...y(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(),iE(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=se(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`;or(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=$L[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?pF(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=>HC.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()===qC(r.content[`text/html`]))LC(this.env,i);else{let e=KC(r.content);await RC(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(!dF(this.env,`COL`)&&!dF(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(iP)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let tR=new O;tR.add(`SPREADSHEET`,!1);var nR=class extends k{static template=`o-spreadsheet-ClickableCellSortIcon`;props=(0,t.props)({position:W.CellPosition(),sortDirection:W.or([W.SortDirection,W.literal(`none`)])});hoveredTableStore;setup(){this.hoveredTableStore=A(TL)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=Bd(e);return H({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?Cf(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},rR=class extends k{static template=`o-spreadsheet-FullScreenFigure`;static components={ChartFigure:i_};fullScreenFigureStore;fullScreenFigureRef=(0,t.signal)(null);spreadsheetRect=Jg();figureRegistry=o_;setup(){this.fullScreenFigureStore=A(vg);let e=A(Ai),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(()=>this.fullScreenFigureRef()?.focus())}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 o_.get(this.figureUI.tag).Component}},iR=class extends k{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:tE};props=(0,t.props)({pivotId:W.UID(),onCellClicked:W.function([W.string()])});pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.proxy)({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(F(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${zS(e,i).join(`,`)})`,value:z(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(${zS(e,i).join(`,`)})`,value:z(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(${zS(e,i).join(`,`)})`,value:z(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=F(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(${zS(e,o,a).join(`,`)})`,value:z(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},aR=l({GHOST_SUNBURST_VALUE:()=>gm,canChartParseLabels:()=>pD,getBarChartData:()=>qE,getBarChartDatasets:()=>_m,getBarChartLegend:()=>VD,getBarChartScales:()=>Zp,getBarChartTooltip:()=>pO,getBubbleChartData:()=>iD,getBubbleChartDatasets:()=>Cm,getBubbleChartLegend:()=>KD,getBubbleChartScales:()=>im,getBubbleChartTooltip:()=>gO,getCalendarChartData:()=>XE,getCalendarChartDatasetAndLabels:()=>ym,getCalendarChartLayout:()=>AD,getCalendarChartScales:()=>Qp,getCalendarChartShowValues:()=>iO,getCalendarChartTooltip:()=>mO,getCalendarColorScale:()=>$p,getChartColorsGenerator:()=>Bm,getChartLabelFormat:()=>TD,getChartLayout:()=>kD,getChartShowValues:()=>rO,getChartTitle:()=>lO,getComboChartDatasets:()=>Em,getComboChartLegend:()=>qD,getFunnelChartData:()=>nD,getFunnelChartDatasets:()=>km,getFunnelChartScales:()=>lm,getFunnelChartTooltip:()=>SO,getFunnelLabelColors:()=>Am,getGeoChartData:()=>tD,getGeoChartDatasets:()=>Om,getGeoChartScales:()=>cm,getGeoChartTooltip:()=>xO,getHierarchalChartData:()=>rD,getLineChartData:()=>QE,getLineChartDatasets:()=>xm,getLineChartLegend:()=>UD,getLineChartScales:()=>em,getLineChartTooltip:()=>hO,getPieChartData:()=>$E,getPieChartDatasets:()=>Tm,getPieChartLegend:()=>WD,getPieChartTooltip:()=>_O,getPyramidChartData:()=>ZE,getPyramidChartLegend:()=>HD,getPyramidChartScales:()=>om,getPyramidChartShowValues:()=>oO,getPyramidChartTooltip:()=>yO,getRadarChartData:()=>eD,getRadarChartDatasets:()=>Dm,getRadarChartLegend:()=>YD,getRadarChartScales:()=>sm,getRadarChartTooltip:()=>bO,getRuntimeColorScale:()=>pm,getScatterChartDatasets:()=>Sm,getScatterChartLegend:()=>GD,getScatterChartScales:()=>rm,getSunburstChartDatasets:()=>jm,getSunburstChartLegend:()=>XD,getSunburstChartTooltip:()=>CO,getSunburstShowValues:()=>aO,getTopPaddingForDashboard:()=>OD,getTreeMapChartDatasets:()=>Im,getTreeMapChartTooltip:()=>wO,getTrendDatasetForBarChart:()=>oD,getTrendDatasetForLineChart:()=>sD,getWaterfallChartLegend:()=>JD,getWaterfallChartScales:()=>am,getWaterfallChartShowValues:()=>sO,getWaterfallChartTooltip:()=>vO,getWaterfallDatasetAndLabels:()=>bm,makeDatasetsCumulative:()=>DD}),oR=class extends U_{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||Xe.style,color:e.border.color||Xe.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 Ot(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 Nn(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 Nn(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 Z_(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,Wn(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=Y_(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=X_(e)}e.borders=t}exportForExcel(e){this.export(e)}},sR=class extends U_{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`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}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]})}}},cR=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;baseNumber=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=Du.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)}squish(e,t){if(e.isFormula){let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters):(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)return this.baseNumber=t,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.baseNumber=void 0,e.content}squishCommand(e){if(e.content){let t=ud(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 e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=Mn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=Mn(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.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),Rl(e,r,this.getters.getSheetName);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),Rl(e,r,this.getters.getSheetName);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),Rl(e,r,this.getters.getSheetName);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)}`:Rl(e,r,this.getters.getSheetName)}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 lR(e){return[Mn(e)]}function*uR(e,t){let n=Mn(e),r=Mn(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 dR=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;n=e==null||e===``?`NOT_A_FORMULA`: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=uR(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:Mn(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===``)continue;i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?lR(a):uR(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=Du.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}}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)yield{position:n,compiled:this.unsquishFormula(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)yield{position:e,compiled:this.unsquishFormula(this.previousOffset,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:z(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=dd(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 Du.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}}}},fR=class extends U_{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 Nn(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 Nn(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 NP,i=new dR;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 Z_(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 cR(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=Y_(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=Y_(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=X_(a),i.formats=X_(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?pd(a,i,r,n):ud(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])Ys(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&&Ta(e.content,R)?Ge:Ue;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 Du.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Du||(r=Du.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 Du.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 Nn(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?rn(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=ud(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)?or(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 Nn(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`}},pR=class extends U_{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=WO.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=WO.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=WO.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=WO.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 WO.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 mR(e){return e===``?NaN:Number(e)}var hR=class extends U_{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)or(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(Un));let s=Nn(o,r);return Nn([...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 LA.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=Q.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(Du.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&&mR(t)>=mR(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&&mR(t)>=mR(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&&mR(t)>=mR(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Du.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)}},gR=class extends U_{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=>zl(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=Nn(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(or(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 Vl(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 Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Du.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`}},_R=class extends U_{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)}},vR=class extends U_{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=Jt(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&&an([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]=eu(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=tu(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=Sy(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Sy(t,e,n.end+1);r.collapsed=!0}}}}}},yR=class extends U_{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=sn(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=Jt(e.position,e.base),r=t[e.base],i=cn(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)})}}},bR=class extends U_{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`:mn(e.elements)<0||pn(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=Jt(e.position,e.base),n=cn([...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 Zt(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])}}},xR=class extends U_{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]}}},SR=class extends U_{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(ir(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&&ir(n,o)&&(o=er(n,o))}return rr(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:rr(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 rr(t,n);let{numberOfCols:r,numberOfRows:i}=cr(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:wR(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&&ir(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 Cr(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||!rr(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,Yn({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||!rr(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}=cr(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 dr(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,Wn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...CR(e))}}exportForExcel(e){this.export(e)}};function CR(e){return Object.entries(e).map(([e,t])=>t?wR(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function wR(e,t){return{...t.zone,id:e}}var TR=class extends U_{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 lN(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=xN.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=Du.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=>Et(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:VS(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||PS(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}},ER=class extends U_{static getters=[`getLocale`];locale=R;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return S_(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===z_(e)&&(n=z_(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??R}export(e){e.settings={locale:this.locale}}},DR=class extends U_{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||df(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=mn(e.elements),n=pn(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`,iu(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[iu(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:$l(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[iu(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 nu(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?Zt(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(qn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>sr(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:$l(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=>au(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:rt.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[iu(n)],r[iu(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[iu(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return ru(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[iu(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 Ot(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(Wn),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 Ru(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:Lu(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},OR=class extends U_{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||!qn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},kR=class extends U_{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(!Jb[e.templateName])return`InvalidTableStyle`;try{uf(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=Yb(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:Mb.styleId}});break}}getTableStyle(e){if(YN[e])return YN[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return vn(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!qb[e]&&!YN[e]}import(e){for(let e in qb)this.styles[e]=qb[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=Yb(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)qb[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},AR=class extends U_{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 Tr(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(ir(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||Mb,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=>!nr(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=>sr(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>ir(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(`=`)?EN(Du.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=vr(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,vr(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 rP(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 rP(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=rP(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<cr(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||Mb,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:Yn(e.range.zone),type:e.type};T(e.config,Mb)||(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=Yn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}};let jR=bc.mapping;function MR(e,t,n){return new NR(e,t,n).getParameters()}var NR=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(jR),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=nr(r,this.getters.getSheetZone(n));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(!qn(e.zone))return new Ba;if(e.invalidSheetName)return new Ba(j(`Invalid sheet name: %s`,e.invalidSheetName))}},PR=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},FR=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(IR),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;)IR(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 PR(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 IR(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 LR=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){Pn(this.profilesStartingPosition,this.profiles,[e])}delete(e){Pn(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return Fn(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 zn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},RR=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new LR),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(Ul(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(Ul(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(Ul(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]()}},zR=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 RR){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new RR;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new FR,this.forest[e][t]=n),n}},BR=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=VR(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 VR(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var HR=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]=BR.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)}},UR=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),WR=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 GR,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new GR),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)}},GR=class extends UR.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}},KR=class{resultsToArrayFormulas=new WR;arrayFormulasToResults=new NP;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||qR}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 qR=[],JR=new O;JR.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let YR=Object.freeze(hd({value:null})),XR={};for(let[e,t]of Object.entries(Cu))XR[t]=e;for(let[e,t]of Object.entries(wu))XR[t]=e;var ZR=class{context;getters;compilationParams;evaluatedCells=new NP;formulaDependencies=Kt(new zR);blockedArrayFormulas=new HR({});spreadingRelations=new KR;perfProfile;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=MR(this.context,this.getters,this.computeAndSave.bind(this))}getPerfProfile(){return this.perfProfile}getEvaluatedCell(e){return this.evaluatedCells.get(e)||YR}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):er(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,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=MR(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(e){this.compilationParams=MR(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.__timingEntries=e,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 HR(e)}evaluateCells(e){let t=performance.now(),n=new RR;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 RR;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 KR,this.formulaDependencies=Kt(()=>{let e=new zR;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);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(e){let t=performance.now();this.evaluatedCells=new NP;let n=[];for(let e of this.getters.getSheetIds()){let t=this.getters.getSheetZone(e);n.push({sheetId:e,zone:t})}this.evaluate(n,e),console.debug(`evaluate all cells`,performance.now()-t,`ms`)}evaluateFormulaResult(e,t,n){let r=Du.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=tz(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return gt(r)?yo(r,$R):$R(r)}catch(e){return mc(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new RR,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 RR;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e,t){t&&(this.perfProfile=void 0),this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new RR(e);let n=0,r=t?[]:void 0;for(;!this.nextRangesToUpdate.isEmpty()&&n++<30;){this.updateCompilationParameters(r);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)}}JR.getAll().forEach(e=>e(this.getters))}n>=30&&console.warn(`Maximum iteration reached while evaluating cells`),t&&this.processPerfProfile()}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{...YR,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?nz(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):ld(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||_c,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,hd(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=tz(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e),r=this.compilationParams.evalContext.__timingEntries,i=r&&gt(n)?performance.now():0,a=this.postProcessFormulaReturn(e,t,n);if(i){let t=r?.at(-1);t&&t.position.sheetId===e.sheetId&&t.position.col===e.col&&t.position.row===e.row&&(t.time+=performance.now()-i)}return a}postProcessFormulaReturn(e,t,n){if(!gt(n)){let r=hd(ez(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 hd({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return hd(ez(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),QR(r,i,this.checkCollision(e)),QR(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),hd(ez(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(ur(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 Ua(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 Ua(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 Ua(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=hd(ez(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 nz(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]),xr(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Ra(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}processPerfProfile(){let e=this.compilationParams.evalContext.__timingEntries??[],t=Object.groupBy(e,e=>e.functionName),n=0,r=[];for(let e in t){let i=XR[e]??e,a=Object.groupBy(t[e],({position:e})=>{let t=this.getters.getCell(e);return(t?this.getters.getCellFingerprint(t):void 0)??``});for(let e in a)for(let t of this.mergeIntoRangeTimings(i,a[e]))n+=t.time,r.push(t)}r.sort((e,t)=>t.time-e.time),this.perfProfile={totalTime:n,totalCells:this.evaluatedCells.keys().length,totalFunctionCalls:e.length,entries:r}}mergeIntoRangeTimings(e,t){let n=new NP,r=new RR;for(let{position:e,time:i}of t)n.set(e,(n.get(e)??0)+i),r.addPosition(e);let i=[];for(let{sheetId:t,zone:a}of r){let r=0;for(let e=a.left;e<=a.right;e++)for(let i=a.top;i<=a.bottom;i++)r+=n.get({sheetId:t,col:e,row:i})??0;i.push({functionName:e,range:this.getters.getRangeFromZone(t,a),time:r})}return i}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function QR(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 $R(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function ez(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Ga:$R(e)}function tz(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 nz(e){return hd({...new za,origin:void 0},void 0,e)}var rz=class extends PP{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`,`getPerfProfile`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new ZR(e.custom,this.getters)}beforeHandle(e){(Vu.has(e.type)||Uu.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(e.profiling);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 gt(r)?yo(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 dr(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 dr(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}getPerfProfile(){return this.evaluator.getPerfProfile()}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return dr(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=Y_(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 iz=new O;iz.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value,r=e.isDarkMode(),i,a;return n?(i=fy(r),a=fy(r)):(i=uy(r),a=dy(r)),{svg:i,hoverSvg:a,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})}}}}),iz.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:sy(i),hoverSvg:ly(i),priority:2,horizontalAlign:`right`,size:Bd(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`}}),iz.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:hy[n].svg,priority:1,horizontalAlign:`left`,size:Bd(r),margin:4,position:t}}}),iz.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??OS.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&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?py(s,!1):void 0,hoverSvg:o?py(s,!0):void 0,position:t,onClick:rC}}}),iz.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:Bd(r),margin:0,svg:n===`asc`?cy(r):sy(r),position:t,onClick:void 0}});var az=class extends PP{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=iz.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 oz=/"(#[0-9a-fA-F]{6})"/g;function sz(e){let t=[{leadColor:mf(255,0,0),colors:[]},{leadColor:mf(255,128,0),colors:[]},{leadColor:mf(128,128,0),colors:[]},{leadColor:mf(128,255,0),colors:[]},{leadColor:mf(0,255,0),colors:[]},{leadColor:mf(0,255,128),colors:[]},{leadColor:mf(0,255,255),colors:[]},{leadColor:mf(0,127,255),colors:[]},{leadColor:mf(0,0,255),colors:[]},{leadColor:mf(127,0,255),colors:[]},{leadColor:mf(128,0,128),colors:[]},{leadColor:mf(255,0,128),colors:[]}];for(let n of e.map(vf)){let e=500,r=0;t.forEach((t,i)=>{let a=cz(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>bf(e).s-bf(t).s)).flat().map(_f)}function cz(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var lz=class extends PP{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));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));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 sz(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}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(cf(t.minimum.color)),n.push(t.midpoint?cf(t.midpoint.color):void 0),n.push(cf(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(oz)].map(e=>e[1])}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(!df(t))continue;let e=uf(t);t&&!Ve.includes(e)&&this.history.update(`customColors`,e,!0)}}},uz=class extends PP{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Vu.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=>or(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;ir(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>ir(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(!Tr(t))return!1;let n=er(...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)&&xr(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=rP(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:!dr(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=Wn(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 dr(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(!Vt(i)){let n=Y_(i,e.styles);t.styles[o]=n}if(a){let n=Y_(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function dz(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!Np(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 Mp(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var fz=class extends PP{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(Vu.has(e.type)||Wu.has(e.type)||Hu.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){let n=this.getters.getSpreadsheetTheme().backgroundColor;if(e)return{background:e,fontColor:xp(e)};if(!t)return{background:n,fontColor:xp(n)};let r=t.zone.left,i=t.zone.top,a=t.sheetId,o=this.getters.getCellComputedStyle({sheetId:a,col:r,row:i}),s=o.fillColor||n;return{background:s,fontColor:o.textColor||xp(s)}}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 Rh(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=dz(e)}return r}},pz=class extends PP{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Vu.has(e.type)||Wu.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]=Kt(()=>this.getComputedStyles(e)),this.computedIcons[e]=Kt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Kt(()=>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 Du.Compile(t,e,this.getters)}),i=Q.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`?pn(a):mn(a);case`number`:return Number(n.value);case`percentage`:let t=mn(a);return t+(pn(a)-t)*Number(n.value)/100;case`percentile`:return Oa(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=pn(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});!or(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:cf(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&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=Xf(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=Q.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:md(t,R));if(o.some(Xx))return!1;let s={...t,type:t.operator,values:o.map(Jx),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let mz={isValid:!0};var hz=class extends PP{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(Vu.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=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:v_.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 dr(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 mz;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:mz}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:Nf(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!Du.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]?.()||mz}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Vl(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Kt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?mz:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Xx))return;let c={...i,values:s.map(Jx)};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=>or(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 md(r,R);let i=Du.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let gz=[`SUBTOTAL`,`PIVOT`];var _z=class extends PP{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of gz)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of gz)xn(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 gz)xn(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))}},vz=class extends PP{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=Od();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Jt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=cn(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=sn(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 dr(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 kd(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 yz=`0.00%`;function bz(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=NS[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return mc(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}=KM(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Va:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=KM(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Va:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return gt(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=KM(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=HS(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 mc(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:yz}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:yz}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:yz}}asPercentOfParentRowTotal(e,t,n){let r=WM(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:yz}}asPercentOfParentColumnTotal(e,t,n){let r=GM(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:yz}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!eN(i,n))return{value:``};let a=QM(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:yz}}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}=KM(this,n),u=rN(l),d=rN(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:yz}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!eN(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:yz}:s===void 0?{value:M.NullError}:{value:s/o,format:yz}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!eN(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(!eN(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:yz}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!eN(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}=KM(this,n),u=rN(l),d=rN(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=tN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=xo(o));for(let s of o){let o=rN(qM(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:qM(this,i,t.domain)})).filter(e=>eN(t,e.rowDomain)),l=Object.groupBy(c,e=>aN(e.rowDomain,t));for(let e in l)l[e]=gn(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=rN(qM(this,i,e.domain)),a=l[aN(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:_n(r)}computeRunningTotal(e,t,n){let r={},i=tN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=xo(o));for(let s of o){let o=rN(qM(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:qM(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>eN(t,e.rowDomain));for(let e of l){let n=rN(e.rowDomain),i=oN(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=rN(n),a=oN(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:_n(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=tN(this,e),{rowDomain:a,colDomain:o}=KM(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=rN(c),d=oN(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=oN(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=rN(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&&mS.contains(n)){let t=hS(n).toComparableValue?.(e);if(t!==void 0)return t}return P(e,R)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=KM(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=KM(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)`?nN(this,t,n,r):$M(t,n,r);if(T(i,t))return`sameValue`;if(!i||!YM(this,i))throw new Va;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;XS(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let xz=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function Sz(e){return xz.includes(e.type)}var Cz=class extends PP{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;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(Vu.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(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(Sz);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:WE();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}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=DN(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=iL(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||ON(t.compiledFormula,this.getters)===0)return uN;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return uN;let{functionName:i,args:a}=r,o=a[0];if(!o)return uN;let s=this.getters.getPivotId(o.toString());if(!s)return uN;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return uN;try{if(i===`PIVOT`){let t=iC(this.getters.getPivotCoreDefinition(s),Jx(a[1]),Jx(a[2]),Jx(a[3]),Jx(a[4]),Jx(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=>gt(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:KM(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 uN}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return vn(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)&&xN.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=KM(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=bz(xN.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:iC(this.getters.getPivotCoreDefinition(i),Jx(n.args[1]),Jx(n.args[2]),Jx(n.args[3]),Jx(n.args[4]),Jx(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}};let wz=new O;wz.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=z(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=co(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=sa(r);e.current=i;let a=n.getLocale(),o=z(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?ld(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 Tz=new O,Ez=/(\d+)$/,Dz=/^(.*\D+)/,Oz=/^(.*\D+)(\d+)$/,kz=/^0*/;function Az(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:ld(a,{locale:R,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function jz(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 Mz(e){let t=1;return e.length>=2&&(t=jz(e)*e.length),t}function Nz(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 Pz(e){if(e.length<2)return 1;let t=e.map(e=>co(e,R)),n=Nz(Fz(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}}Tz.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Os(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&ld(e,{locale:R}).type===`text`&&Oz.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(Ez)[0]),i=e.content.match(Dz)[0],a=Az(e,t,e=>e.type===`text`&&Oz.test(e.value)).filter(e=>i===(e.value??``).toString().match(Dz)[0]).map(e=>(e.value??``).toString().match(Ez)[0]),o=a.reduce((e,t)=>{let n=t.match(kz)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=Mz(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&&ld(e,{locale:R}).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&&ld(e,{locale:R}).type===`number`&&!!e.format&&Os(e.format),generateRule:(e,t)=>{let n=Pz(Az(e,t,e=>e.type===`number`&&!!e.format&&Os(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=ld(e,{locale:R});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&&ld(e,{locale:R}).type===`number`,generateRule:(e,t,n)=>{let r=Az(e,t,e=>e.type===`number`&&!Os(e.format||``)).map(e=>Number(e.value)),i=Mz(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=ld(e,{locale:R});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function Fz(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=Ni.fromTimestamp(e[n-1].getTime()),i=ha(r,t),a=pa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:ma(r,t)}}).slice(1)}var Iz=class extends H_{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){}},Lz=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}=wz.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}}}},Rz=class extends Iz{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:Nn(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(Wn),[]);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=Nn(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(or(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=Tz.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}=Mn(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 Lz(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([]))}},zz=class extends Iz{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}=or(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)||lr(er(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,er(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=pn(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=Ot(i.filter(e=>this.isNumber(r[e])))[0]||[];return pn(o)<a?1/0:mn(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Os(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 lr(t)?(n.add(cr(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)},dr(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)},dr(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`))}},Bz=class extends Iz{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(Vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(Hz(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)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Kt(()=>{let n=this.getters.getTableStyle(t.config.styleId),{tableMetaData:r,config:i}=this.getTableMetaData(e,t),a=aP(i,n,r),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r.numberOfCols;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<r.numberOfRows;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}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),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 Vz=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 Hz(e){return Vz.has(e.type)}var Uz=class extends Iz{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new NP;borders=new NP;handle(e){if(Vu.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 NP,this.borders=new NP;return}if(Hz(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new NP,this.borders=new NP);return}if(Wu.has(e.type)){this.styles=new NP;return}if(Gu.has(e.type)){this.borders=new NP;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=Ae),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{...Qt(r),...Qt(i),...Qt(t?.style),...Qt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...Mn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>sr(Wn(e),Wn(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(Wn),s=Nn([Wn(r)],o);delete t.styles[r];for(let e of s)t.styles[Yn(e)]=n;let c=Y_({...a,textColor:Ae},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...Mn(n)});t.styles[n]=Y_({...r?.style,textColor:Ae},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Qt(this.getters.getCellTableBorder(e)||{}),...Qt(t)};return Vt(n)?null:n}},Wz=class extends Iz{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 Gz(e){let t=Gl.get(e.type)?.(e),n=Jz(e);if(!t&&!n)return;let r=t||qz(),i=n||(e=>e),a=Kz(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>cu(e,t,r),adaptFormulaString:(e,t)=>ou(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function Kz(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!qn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function qz(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function Jz(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let Yz=new class extends O{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)}},Xz=new class extends O{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};Yz.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],lB),Yz.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],lB),Yz.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],eB),Yz.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],tB),Yz.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],nB),Yz.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],rB),Yz.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],iB),Yz.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],aB),Yz.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],oB),Yz.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],oB),Yz.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],sB),Yz.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],sB),Yz.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],cB),Yz.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],uB),Yz.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],uB),Yz.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],$z),Yz.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],Qz),Yz.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],Zz),Yz.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],Zz),Yz.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],dB);function Zz(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Mr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function Qz(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function $z(e,t){if(e.pivotId!==t.pivotId)return e}function eB(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function tB(e,t){if(e.figureId!==t.figureId)return e}function nB(e,t){if(e.chartId!==t.chartId)return e}function rB(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function iB(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 aB(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!ir(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function oB(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 sB(e,t){if(e.sheetId!==t.sheetId)return e;let n=Mr(e.zone,t);if(!n)return;let r=e.newTableRange?Nr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function cB(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:Mb.styleId}}:e}function lB(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=tu(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=eu(Jt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function uB(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=tu(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=eu(Jt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function dB(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 fB(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}Xz.add(`UPDATE_CELL`,fB);function pB(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}Xz.add(`ADD_CONDITIONAL_FORMAT`,pB);function mB(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}Xz.add(`ADD_DATA_VALIDATION_RULE`,mB);function hB(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}Xz.add(`ADD_PIVOT`,hB),Xz.add(`UPDATE_PIVOT`,hB),Xz.add(`CREATE_CHART`,gB),Xz.add(`UPDATE_CHART`,gB);function gB(e,t){return{...e,definition:WO.transformDefinition(e.sheetId,e.definition,t)}}let _B=[{match:Fu,fn:SB},{match:Lu,fn:CB},{match:Bu,fn:wB},{match:zu,fn:DB},{match:Iu,fn:EB},{match:Ru,fn:TB}];function vB(e,t){let n=Yz.getTransformation(e.type,t.type),r=n?n(e,t):xB(e,t);return r&&yB(r,t)}function yB(e,t){let n=Xz.get(e.type);if(!n)return e;let r=Gz(t);return r?n(e,r):e}function bB(e,t){let n=[...e],r=new Set(Yz.getKeys());for(let e of t)(r.has(e.type)||Gl.contains(e.type))&&(n=n.reduce((t,n)=>{let r=vB(n,e);return r&&t.push(r),t},[]));return n}function xB(e,t){for(let{match:n,fn:r}of _B)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function SB(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 CB(e,t){let n=SB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Mr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function wB(e,t){let n=SB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Mr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function TB(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>Nr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function EB(e,t){let n=SB(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=tu(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=eu(Jt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function DB(e,t){let n=SB(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?OB(e,t):t.type===`ADD_MERGE`?kB(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function OB(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 kB(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&or(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var AB=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}},jB=class extends Error{},MB=class extends Si{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;lastLocalOperation;constructor(e,t,n=Ze,r){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new AB(G.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:G.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:G.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=G.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 jB(`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 AB(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:bB(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new AB(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)),e={...e,commands:this.commandSquisher.squish(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.
116
116
  ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof jB))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`)}},NB=class extends Iz{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new qf(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(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof jB)return[];throw e}let e=this.getters.getActiveSheetId(),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()){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 ${Je+1}px ${Ye}`}}};let PB={light:{backgroundColor:`#FFFFFF`,gridBorderColor:`#E2E3E3`,headerBackgroundColor:`#F8F9FA`,headerActiveBackgroundColor:`#595959`,headerSelectedBackgroundColor:`#E8EAED`,headerTextColor:`#666666`,headerBorderColor:`#C0C0C0`,frozenPaneBorderColor:`#DADFE8`,frozenPaneHeaderBorderColor:`#BCBCBC`,singleCellSelectionBackgroundColor:`#F3F7FE`,multipleCellsSelectionBackgroundColor:`#E9F0FF`},dark:{backgroundColor:jf(`#1A1C2E`),gridBorderColor:jf(`#4A4E55`),headerBackgroundColor:jf(`#262A36`),headerActiveBackgroundColor:jf(`#3A4052`),headerSelectedBackgroundColor:jf(`#4E566E`),headerTextColor:jf(`#A1A6B3`),headerBorderColor:jf(`#7A7F91`),frozenPaneBorderColor:jf(`#7A7F91`),frozenPaneHeaderBorderColor:jf(`#9FA5BD`),singleCellSelectionBackgroundColor:jf(`#696E8044`),multipleCellsSelectionBackgroundColor:jf(`#828AA044`)}};var FB=class extends Iz{static getters=[`isDarkMode`,`getSpreadsheetTheme`];colorScheme;constructor(e){super(e),this.colorScheme=e.colorScheme}handle(e){e.type===`UPDATE_COLOR_SCHEME`&&(this.colorScheme=e.colorScheme)}isDarkMode(){return this.colorScheme===`dark`}getSpreadsheetTheme(){switch(this.colorScheme){case`dark`:return PB.dark;default:return PB.light}}},IB=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){}},LB=class extends IB{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of GC(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of Nn(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){}},RB=class extends LB{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=>sr(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=VS(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)?``:z(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 GC(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:GC(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(`
117
117
  `).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=E_(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},zB=class extends Iz{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===cr(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new RB(this.getters,this.dispatch),c=s.copy(UC(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.
118
- %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=Nn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(dr).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=un(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})}},BB=class extends Iz{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 Vl(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=(gt(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`})}}}}},VB=class extends Iz{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},HB=class extends Iz{allowDispatch(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures){let e=this.canDispatch(`UPDATE_FIGURE`,t);if(!e.isSuccessful)return e.reasons}break;case`DELETE_FIGURES`:for(let t of e.figureIds)if(!this.getters.getFigure(e.sheetId,t))return`FigureDoesNotExist`;break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=e.chartFigureIds.map(t=>this.getters.getFigure(e.sheetId,t)),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(t.some(e=>e===void 0||e.tag!==`chart`)||!n||n.tag!==`chart`)return`FigureDoesNotExist`}return`Success`}handle(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures)this.dispatch(`UPDATE_FIGURE`,t);break;case`DELETE_FIGURES`:for(let t of e.figureIds)this.dispatch(`DELETE_FIGURE`,{figureId:t,sheetId:e.sheetId});break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=G.smallUuid(),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(!n)throw Error(`Figure ${e.baseFigureId} does not exists.`);this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetId,figureId:t,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:{items:[]}}),this.dispatch(`ADD_FIGURES_CHART_TO_CAROUSEL`,{sheetId:e.sheetId,carouselFigureId:t,chartFigureIds:e.chartFigureIds})}}},UB=class extends Iz{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 Nn(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=Nn(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:Nn(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 Nn(t))for(let t of dr(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Gs(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=Nn(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&&Os(e.format)))return e.format||Ms(e.value)}}},WB=class extends Iz{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];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)}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`)}},GB=class extends Iz{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),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}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))}},KB=class extends Iz{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){xr(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:[],filters:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:lt}}});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 vn(Dt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new lN(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:{...ct,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:VS(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:$N(o.config.styleId)}})}}}};let qB=new O,JB=new O;function YB(e,t){if(t&&qB.contains(t.type))return qB.get(t.type)(e,t)}function XB(e,t,n){if(JB.contains(t.type))return JB.get(t.type)(e,t,n)}function ZB(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Xu(e.rootCommand)?qB.contains(e.rootCommand.type):JB.contains(e.rootCommand.type)}function QB(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Xu(e.rootCommand)?YB(t,e.rootCommand):XB(t,e.rootCommand,e.commands)}var $B=class extends Iz{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=QB(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:ZB(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},eV=class extends Iz{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Ju.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Xu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},tV=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,F(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)}},nV=class extends Iz{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new tV,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 rV=[`number`,`error`,`text`,`boolean`];function iV(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=rV.indexOf(e.type)-rV.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 aV(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(iV(t))}var oV=class extends Iz{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return or(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)&&dr(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=>ir(e,t)),r=cr(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 dr(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=aV(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}},sV=class extends Iz{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[`
118
+ %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=Nn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(dr).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=un(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})}},BB=class extends Iz{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 Vl(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=(gt(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`})}}}}},VB=class extends Iz{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},HB=class extends Iz{allowDispatch(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures){let e=this.canDispatch(`UPDATE_FIGURE`,t);if(!e.isSuccessful)return e.reasons}break;case`DELETE_FIGURES`:for(let t of e.figureIds)if(!this.getters.getFigure(e.sheetId,t))return`FigureDoesNotExist`;break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=e.chartFigureIds.map(t=>this.getters.getFigure(e.sheetId,t)),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(t.some(e=>e===void 0||e.tag!==`chart`)||!n||n.tag!==`chart`)return`FigureDoesNotExist`}return`Success`}handle(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures)this.dispatch(`UPDATE_FIGURE`,t);break;case`DELETE_FIGURES`:for(let t of e.figureIds)this.dispatch(`DELETE_FIGURE`,{figureId:t,sheetId:e.sheetId});break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=G.smallUuid(),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(!n)throw Error(`Figure ${e.baseFigureId} does not exists.`);this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetId,figureId:t,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:{items:[]}}),this.dispatch(`ADD_FIGURES_CHART_TO_CAROUSEL`,{sheetId:e.sheetId,carouselFigureId:t,chartFigureIds:e.chartFigureIds})}}},UB=class extends Iz{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 Nn(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=Nn(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:Nn(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 Nn(t))for(let t of dr(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Gs(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=Nn(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&&Os(e.format)))return e.format||Ms(e.value)}}},WB=class extends Iz{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];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)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){if(!globalThis.ChartGeo)return null;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`)}},GB=class extends Iz{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),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}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))}},KB=class extends Iz{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){xr(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:[],filters:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:lt}}});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 vn(Dt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new lN(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:{...ct,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:VS(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:$N(o.config.styleId)}})}}}};let qB=new O,JB=new O;function YB(e,t){if(t&&qB.contains(t.type))return qB.get(t.type)(e,t)}function XB(e,t,n){if(JB.contains(t.type))return JB.get(t.type)(e,t,n)}function ZB(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Xu(e.rootCommand)?qB.contains(e.rootCommand.type):JB.contains(e.rootCommand.type)}function QB(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Xu(e.rootCommand)?YB(t,e.rootCommand):XB(t,e.rootCommand,e.commands)}var $B=class extends Iz{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=QB(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:ZB(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},eV=class extends Iz{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Ju.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Xu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},tV=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,F(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)}},nV=class extends Iz{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new tV,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 rV=[`number`,`error`,`text`,`boolean`];function iV(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=rV.indexOf(e.type)-rV.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 aV(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(iV(t))}var oV=class extends Iz{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return or(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)&&dr(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=>ir(e,t)),r=cr(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 dr(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=aV(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}},sV=class extends Iz{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[`
119
119
  `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&!s?.isFormula&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:C_(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of C(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of C(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i?.isFormula||i?.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of C(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i?.isFormula||i?.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},cV=class extends Iz{handle(e){Ku.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:this.getters.getCellsWithTrackedFormula(`SUBTOTAL`)})}},lV=class extends Iz{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=tP(t.range.zone,t.config);if(a&&or(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},uV=class extends Iz{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.isFormula&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},dV=class extends Iz{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},fV=class extends Iz{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=Od();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=Ot(C(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=Hd(this.ctx,r,t,void 0);n+=Md(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Nd(this.ctx,e,t)}getMultilineTextSize(e,t){return Md(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula){if(n?.isFormula)return O_(n.compiledFormula.toFormulaString(this.getters),r);if(!n?.content)return``}let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Nd(this.ctx,e,n?.style||{})}:void 0;return z(i.value,{format:i.format,locale:r,formatWidth:a})}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return Hd(this.ctx,r,n,t.wrapWidth)}computeTextYCoordinate(e,t,n=Ke,r=1){let i=e.y+1,a=Dd(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of C(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of C(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);rr(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=dr(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,pn(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0&&e.type!==`CREATE_SHEET`?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCellIds(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=Ad(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=Ad(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},pV=class extends Iz{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURES_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||e.chartFigureIds.some(t=>this.getters.getFigure(e.sheetId,t)?.tag!==`chart`)?`InvalidFigureId`:`Success`;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?`InvalidFigureId`:`Success`;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?`Success`:`InvalidFigureId`;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>T(t,e.item))?`Success`:`InvalidCarouselItem`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURES_CHART_TO_CAROUSEL`:e.chartFigureIds.forEach(t=>{this.addFigureChartToCarousel(e.carouselFigureId,t,e.sheetId)});break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=G.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:G.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=G.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:rg});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={type:`chart`,chartId:r},o={...i,items:[...i.items,a]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:o}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t}),this.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:e,sheetId:n,item:a})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=cn(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function mV(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var hV=class extends Iz{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=G.uuidv4();fileStore;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataAbove(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZones();if(e.length>1)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==pC()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=G.uuidv4(),i=t.imageData,a=Gh(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAbove(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAboveOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!qn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Xu(e)&&(this.status=`invisible`)}}getCopiedDataAbove(e){let t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};return this.copy([n])}getCopiedDataOnLeft(e){let t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};return this.copy([n])}getCopiedDataAboveOnLeft(e){let t={...e,right:e.left,bottom:e.top};return this.copy([t])}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureIds`in e?SL.figureHandlers:SL.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureIds`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=XC(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),t.figureIds&&this.dispatch(`SELECT_FIGURE`,{figureId:null}),YC(i,t,a,n),n?.selectTarget&&ZC(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":``,"text/html":``};try{n[`text/plain`]=this.getPlainTextContent(),n[`text/html`]=await this.getHTMLContent()}catch{this.ui.notifyUI({type:`danger`,text:`Your selection was too large for the browser to copy it.
120
120
  Please select a smaller zone.`,sticky:!0})}return t&&e&&(n[t]=e),n}getSheetData(){let e={version:pC()};return this.copiedData&&`figureIds`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.compiledFormula?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
121
121
  `)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureIds&&this.copiedData.figureIds.length){let t=this.copiedData.figureIds[0],n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=ox(`${this.getters.getCellText(t[0][0].position)}`);else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=H(bg(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+ox(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;let n=JSON.stringify(this.getSheetData());return`<div data-osheet-clipboard-id='${this.clipboardId}' data-osheet-clipboard='${ox(n)}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${ox(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureIds&&this.copiedData.figureIds[0];if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:j(`The file you are trying to copy is too large (>%sMB).
@@ -960,4 +960,4 @@ If you meant to create a named range, named range cannot have the same name as a
960
960
  <Relationships xmlns="${tp.Relationships}">
961
961
  <Relationship ${J(e)} />
962
962
  </Relationships>
963
- `),`_rels/.rels`)}function TG(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=vn(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(`'?${St(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function EG(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>cr(Wn(e.range)).numberOfRows>1);return e}var DG=class e extends Si{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=!1){let i=performance.now();console.debug(`##### Model creation #####`),super(),Fa(),n=wC(e,n);let a=gC(e,r);this.state=new zU,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(a.revisionId),this.coreGetters={},this.range=new FU(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.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 LU(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 CV.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of EV.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of TV.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of wV.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()-i,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession({shouldSnapshot:e}={shouldSnapshot:!0}){let t=e&&!this.getters.isReadonly()?Kt(()=>this.exportData()):void 0;await this.session.leave(t)}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 MB(MU({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 CU(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:G.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new vH,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 wU(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(Lo));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,colorScheme:this.config.colorScheme}}checkDispatchAllowed(e){let t=Xu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Qu(e.flat()):Qu.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(OG(e,t));dispatch=(e,t)=>{let n=OG(e,t),r=this.status;if(this.getters.isReadonly()&&!Zu(n))return new Qu(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Qu(`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();Xu(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(Xu(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(Xu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Qu.Success};dispatchFromCorePlugin=(e,t)=>{let n=OG(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Qu.Success};dispatchToHandlers(e,t){let n=Xu(t);for(let r of e)!n&&r instanceof U_||r.beforeHandle(t);for(let r of e)!n&&r instanceof U_||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 vH};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=jC();for(let n of this.handlers)n instanceof U_&&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=NC();for(let t of this.handlers)t instanceof H_&&await t.exportForExcel(e);return e=x(e),gG(e)}};function OG(e,t={}){let n=x(t);return n.type=e,n}var kG=class extends LB{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=Nn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},AG=class extends IB{copy(e){}getCopyRect(e){return Wg(...e.figureIds.map(t=>this.getters.getFigure(e.sheetId,t)).filter(w).map(t=>this.getters.getFigureUI(e.sheetId,t)))}},jG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`carousel`)continue;let a={...e},o=this.getters.getCarousel(i),{x:s,y:c}=this.getters.getFigureUI(t,e),l={};for(let e of o.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);l[e.chartId]=t}n.push({figureId:i,copiedFigure:a,copiedCarousel:o,copiedCharts:l,copiedSheetId:t,offset:{x:s-r.x,y:c-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,{col:l,row:u,offset:d}=Kh(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CAROUSEL`,{figureId:o,sheetId:i,definition:{items:[]},col:l,row:u,offset:d,size:{height:c,width:s}});let f=x(a.copiedCarousel.items);for(let e of f){if(e.type!==`chart`)continue;let t=a.copiedCharts[e.chartId],n=G.smallUuid(),r=WO.fromDefinition(this.getters,i,t.copyInSheetId(i)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:o,chartId:n,sheetId:i,definition:r}),e.chartId=n}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:i,figureId:o,definition:{...a.copiedCarousel,items:f}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedSheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},MG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`chart`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=this.getters.getChartFromFigureId(i);if(!c)throw Error(`No chart for the given id: ${i}`);n.push({figureId:i,copiedFigure:a,copiedChart:c,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,l=a.copiedChart,u=WO.fromDefinition(this.getters,i,l.copyInSheetId(i)).getDefinition();u=WO.fromStrDefinition(this.getters,i,u).getDefinition();let{col:d,row:f,offset:p}=Kh(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CHART`,{figureId:o,chartId:G.smallUuid(),sheetId:i,definition:u,col:d,row:f,offset:p,size:{height:c,width:s}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedChart.sheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},NG=class extends LB{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:G.smallUuid(),ranges:[]}}},PG=class extends LB{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?G.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=Nn([...Nn(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})}}},FG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`image`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=x(this.getters.getImage(i));n.push({figureId:i,copiedFigure:a,copiedImage:c,sheetId:t,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{sheetId:e,zones:[],figureIds:i}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e;for(let i of t.figures){let a=e.figureIds[i.figureId],o=this.getters.getActiveSheetId(),{width:s,height:c}=i.copiedFigure,l=x(i.copiedImage),{col:u,row:d,offset:f}=Kh(this.getters,o,{col:r[0].left,row:r[0].top},{...i.copiedFigure,offset:i.offset});this.dispatch(`CREATE_IMAGE`,{figureId:a,sheetId:o,col:u,row:d,offset:f,size:{height:c,width:s},definition:l}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:i.sheetId,figureId:i.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:a,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},IG=class extends LB{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}]})}},LG=class extends LB{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})}}},RG=class extends LB{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Cr(GC(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},zG=class extends LB{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=>sr(f,e))){s.add(u.id);let{numberOfRows:e}=cr(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=>sr(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=Qt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Qt(n)},border:{...r,...Qt(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=cr(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}))}};SL.figureHandlers.add(`chart`,MG).add(`image`,FG).add(`carousel`,jG),SL.cellHandlers.add(`dataValidation`,PG).add(`cell`,RB).add(`sheet`,RG).add(`merge`,IG).add(`border`,kG).add(`table`,zG).add(`conditionalFormat`,NG).add(`references`,LG);var BG=class extends k{static maxSize={maxHeight:80};static template=`o-spreadsheet-ErrorToolTip`;props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){let e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return``;let e=this.evaluationError?.errorOriginPosition;if(!e||T(e,this.props.cellPosition))return``;let t=e.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(t,D(e)),this.env.model.getters.getActiveSheetId())}selectCell(){let e=this.evaluationError?.errorOriginPosition;if(!e)return;let t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}get isSpillErrorBecauseOfMissingHeaders(){let e=this.evaluationError;return e?.value===M.SpilledBlocked&&!e.errorOriginPosition&&!this.env.model.getters.getSpreadZone(this.props.cellPosition,{ignoreSpillError:!0})}getMissingHeadersForSpread(){if(!this.isSpillErrorBecauseOfMissingHeaders)return;let e=this.env.model.getters.getCell(this.props.cellPosition);if(!e||!e.isFormula)return;let t=e.compiledFormula.toFormulaString(this.env.model.getters);return Sn(this.env.model.getters,this.props.cellPosition,t)}addMissingHeaders({missingCols:e,missingRows:t}){let n=this.props.cellPosition.sheetId;e>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`COL`,base:this.env.model.getters.getNumberCols(n)-1,position:`after`,quantity:e+20}),t>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`ROW`,base:this.env.model.getters.getNumberRows(n)-1,position:`after`,quantity:t+50})}getAddMissingHeadersButtonText(e){return e.missingCols>0&&e.missingRows>0?j(`Add missing columns and rows`):e.missingCols>0?j(`Add missing columns`):j(`Add missing rows`)}};let VG={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return n.type===`error`&&n.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:BG,cellCorner:`top-right`}:{isOpen:!1}}};var HG=class extends k{static template=`o-spreadsheet-FilterMenu`;static components={FilterMenuValueList:kM,SidePanelCollapsible:xE,FilterMenuCriterion:DM};props=(0,t.props)({filterPosition:W.Position(),"onClosed?":W.function([])});state;criterionCategory=`text`;updatedCriterionValue;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition),this.state.values=this.getFilterHiddenValues(e.filterPosition))}),this.state=(0,t.proxy)({values:this.getFilterHiddenValues(this.props.filterPosition)}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;let e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&e?.type!==`dynamic`}get table(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterValue({sheetId:e,...t})?.filterType}getCriterionCategory(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n||!n.filteredRange)return`text`;let r={text:0,number:0,date:0},i=n.filteredRange.zone;for(let n=i.top;n<=i.bottom&&!(n>100);n++){let i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:n,col:e.col});i.type===`text`||i.type===`boolean`?r.text++:i.type===`number`&&(i.format&&Os(i.format)?r.date++:r.number++)}let a=Math.max(r.text,r.number,r.date);return Object.keys(r).find(e=>r[e]===a)||`text`}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:`values`,hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue){this.props.onClosed?.();return}let e=this.props.filterPosition;this.env.model.dispatch(`UPDATE_FILTER`,{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return this.criterionCategory===`date`?EM:this.criterionCategory===`number`?TM:wM}cancel(){this.props.onClosed?.()}sortFilterZone(e){let t=this.props.filterPosition,n=this.table?.range.zone;if(!t||!n||n.top===n.bottom)return;let r=this.env.model.getters.getActiveSheetId(),i={...n,top:n.top+1},a={col:t.col,row:i.top};dI(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n?.filteredRange)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=dr(n.filteredRange.zone);r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.row)));let a=i.map(e=>this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(Wd)),c=new Set,l=[],u=e=>{let t=Wd(e);c.has(t)||(l.push({string:e||``,checked:r?.filterType===`criterion`?!1:!s.has(t),normalizedValue:t}),c.add(t))};return a.forEach(u),o.forEach(u),l.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:`base`}))}getFilterCriterionValue(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return n?.filterType===`criterion`?x(n):{filterType:`criterion`,type:`none`,values:[]}}};let UG={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:HG,cellCorner:`bottom-left`})};var WG=class extends k{static template=`o-spreadsheet-LinkDisplay`;props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});cellPopovers;setup(){this.cellPopovers=A(BC)}get cell(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;let{col:e,row:t}=this.props.cellPosition;throw Error(`LinkDisplay Component can only be used with link cells. ${E(e,t)} is not a link.`)}getUrlRepresentation(e){return od(e,this.env.model.getters)}openLink(e){sd(this.link,this.env,ue(e))}edit(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},`LinkEditor`)}unlink(){let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.props.cellPosition,r=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:n}),i=r?.textColor===`#017E84`?void 0:r?.textColor;this.env.model.dispatch(`UPDATE_CELL`,{col:t,row:n,sheetId:e,content:this.link.label,style:{...r,textColor:i,underline:void 0}})}};let GG={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:WG,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var KG=class extends k{static template=`o-spreadsheet-LinkEditor`;static components={MenuPopover:e_};props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});static size={maxHeight:500};urlInput=(0,t.signal)(null);suggestionListRef=(0,t.signal)(null);urlInputContainer=(0,t.signal)(null);state=(0,t.proxy)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput()?.focus())}computeLinks(){this.state.selectedIndex=null,this.state.linksByCategory=this.linkProposalByCategory,this.state.linksList=Object.values(this.state.linksByCategory).flat()}get linkProposalByCategory(){let e={},t=-1,n=this.state.url;for(let r of nd.getKeys()){let i=nd.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?jk(n,a,e=>i.urlRepresentation(e.url,this.env.model.getters)):a;o.length!==0&&(e[i.title]=o.map(e=>{t++;let n=i.urlRepresentation(e.url,this.env.model.getters),r=t;return{text:n,icon:e.icon,index:r,onSelect:()=>{this.state.url=e.url,this.state.label=e.label,this.state.isUrlEditable=e.isUrlEditable,this.state.selectedIndex=r,this.urlInputContainer()?.focus()}}}))}return e}get defaultState(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t});return r.link?{url:r.link.url,label:r.formattedValue,isUrlEditable:r.link.isUrlEditable,selectedIndex:null,linksByCategory:{},linksList:[]}:{label:r.formattedValue,url:``,isUrlEditable:!0,selectedIndex:null,linksByCategory:{},linksList:[]}}getUrlRepresentation(e){return od(e,this.env.model.getters)}removeLink(){this.state.url=``,this.state.isUrlEditable=!0,this.computeLinks()}save(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getLocale(),r=this.state.label?C_(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Ft(r,this.state.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case`Enter`:this.state.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case`Escape`:this.cancel(),e.stopPropagation();break}}onInputKeyDown(e){switch(e.key){case`Enter`:if(this.state.selectedIndex!==null){let t=this.state.linksList[this.state.selectedIndex];if(t){let n=this.state.url;t.onSelect(),this.state.url!==n&&(e.stopPropagation(),e.preventDefault())}}break;case`ArrowDown`:this.state.selectedIndex=this.state.selectedIndex===null||this.state.selectedIndex===this.state.linksList.length-1?0:(this.state.selectedIndex+1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault();break;case`ArrowUp`:this.state.selectedIndex!==null&&(this.state.selectedIndex=this.state.selectedIndex===0?this.state.linksList.length-1:(this.state.selectedIndex-1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault());break}}showSelectedProposal(){this.suggestionListRef()?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};zC.add(`ErrorToolTip`,VG).add(`LinkCell`,GG).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:KG,cellCorner:`bottom-left`})}).add(`FilterMenu`,UG),Mk.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(yn(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:Nf(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t.text),this.composer.stopEdition()}}),Mk.add(`functions_and_named_ranges`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;if(!yn(this.composer.currentContent))return[];let n=Object.entries(bc.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({type:`function`,text:e,icon:`o-spreadsheet-Icon.FX_SVG`,description:n,htmlContent:NM(t,e,Me,`o-semi-bold`)}));return n.push(...this.getters.getNamedRanges().map(e=>({type:`named_range`,text:e.name,description:this.getters.getRangeString(e.range),icon:`o-spreadsheet-Icon.NAMED_RANGE`,htmlContent:NM(t,e.name,Me,`o-semi-bold`)}))),n.sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)),n},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens,a=t.text;if(t.type===`function`){a+=`(`;let t=i.map(e=>e.start).indexOf(e.start);t+1<i.length&&i[t+1]?.type===`LEFT_PAREN`&&r++}this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(a)}});function qG(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||Mk.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:JG,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?mt.STRING:mt.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function JG(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}bc.getAll().forEach(e=>qG(e.name,e.args)),Mk.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:mt.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(w)},selectProposal:JG}),Mk.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:j(`Count`),htmlContent:[{value:e,color:mt.STRING}],fuzzySearchKey:j(`Count`)+e}}return AN(e)}).filter(w):[]},selectProposal:JG}),Mk.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!YG(e)&&!XG(e))return;let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(w),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=tR.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(w);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?kN(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:j(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:mt.STRING}],fuzzySearchKey:t.string+n}})).filter(w)},selectProposal:JG});function YG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function XG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}Mk.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!ZG(e)&&!QG(e))return;let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(fs).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:mt.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:j(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`day_of_month`?C(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`iso_week_number`?C(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`day_of_week`?C(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`hour_number`?C(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`minute_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`second_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?mt.STRING:mt.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:JG});function ZG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function QG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}Mk.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Et(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text+`!`)}});function $G(e){return e.yRanges.length&&!Dc.test(e.yRanges[0])?`InvalidYRange`:e.xRange&&!Dc.test(e.xRange)?`InvalidXRange`:e.labelRange&&!Dc.test(e.labelRange)?`InvalidLabelRange`:e.sizeRange&&!Dc.test(e.sizeRange)?`InvalidBubbleSizeRange`:`Success`}let eK={sequence:40,allowedDefinitionKeys:[...$m.commonKeys,`yRanges`,`xRange`,`labelRange`,`sizeRange`,`dataSetsHaveTitle`,`verticalAxisPosition`,`labelsAsText`,`bubbleColor`,`legendPosition`,`axesDesign`,`showValues`],fromStrDefinition(e,t,n){let r=e.yRanges.map(e=>Bl(n,t,e)).filter(w),i=Bl(n,t,e.xRange),a=Bl(n,t,e.labelRange),o=Bl(n,t,e.sizeRange);return{...e,yRanges:r,xRange:i,labelRange:a,sizeRange:o}},toStrDefinition(e,t,n){return{...e,yRanges:e.yRanges.map(e=>n.getRangeString(e,t)),xRange:e.xRange?n.getRangeString(e.xRange,t):void 0,labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,sizeRange:e.sizeRange?n.getRangeString(e.sizeRange,t):void 0}},validateDefinition(e,t){return e.checkValidations(t,$G)},transformDefinition(e,t,{adaptRangeString:n}){let r=e=>{if(!e)return;let{changeType:r,range:i}=n(t,e);return r===`REMOVE`?void 0:i};return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),sizeRange:r(e.sizeRange),labelRange:r(e.labelRange)}},getDefinitionFromContextCreation(e,t){let n=e.dataSource?.type===`range`;return{background:e.background,yRanges:n?e.dataSource.dataSets?.map(e=>e.dataRange)??[]:[],verticalAxisPosition:e.dataSetStyles?.[0]?.verticalAxisPosition,dataSetsHaveTitle:n?e.dataSource.dataSetsHaveTitle??!1:!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bubble`,labelRange:e.bubbleLabelRange||void 0,labelsAsText:e.labelsAsText??!1,xRange:e.auxiliaryRange||void 0,sizeRange:e.bubbleSizeRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize,bubbleColor:e.bubbleColorMode||{color:`multiple`}}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.yRanges.map((e,t)=>({dataSetId:`${t}`,dataRange:e}))},bubbleLabelRange:e.labelRange,auxiliaryRange:e.xRange,bubbleSizeRange:e.sizeRange,bubbleColorMode:e.bubbleColor}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=e.yRanges.map(e=>gp(e,t)).filter(w),r=gp(e.xRange,t),i=gp(e.labelRange,t),a=gp(e.sizeRange,t);return{...e,yRanges:n,xRange:r,labelRange:i,sizeRange:a}},duplicateInDuplicatedSheet(e,t,n){let r=e=>hp(t,n,e);return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),labelRange:r(e.labelRange),sizeRange:r(e.sizeRange)}},copyInSheetId:e=>e,getRuntime(e,t){let n=iD(t,e);return{chartJsConfig:{type:`line`,data:{datasets:Cm(t,n),labels:n.labels},options:{...Lh,layout:kD(t,n),scales:im(t,n),plugins:{title:lO(t,e),legend:KD(t,n),tooltip:gO(t,n),chartShowValuesPlugin:rO(t,n),background:{color:t.background}}}}}}};function tK(e){return!$O.includes(e.horizontalGroupBy)||!$O.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let nK={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,tK)},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=XE(t,n(),e),{labels:i,datasets:a}=ym(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Lh,indexAxis:`x`,layout:AD(t,r),scales:Qp(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:mO(t,r),chartShowValuesPlugin:iO(t,r),chartColorScalePlugin:$p(t,r),background:{color:r.background}}}}}}},rK={sequence:15,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r,verticalAxis:Dp(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=qE(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:Em(t,a)},options:{...Lh,layout:kD(t,a),scales:Zp(t,a),plugins:{title:lO(t,e),legend:qD(t,a),tooltip:pO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},iK={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.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=nD(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:km(t,a)},options:{...Lh,indexAxis:`y`,layout:kD(t,a),scales:lm(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:SO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}}}}},aK={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.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=tD(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Om(t,a)},options:{...Lh,layout:kD(t,a),scales:cm(t,a),plugins:{title:lO(t,e),tooltip:xO(t,a),legend:{display:!1},background:{color:a.background}},...i}}}}},oK={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...$m.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 i=ZE(t,JO(e,t.dataSource),e),{dataSetsValues:a}=i,o=Math.max(...a.map(e=>Math.max(...e.data.map(e=>V(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:BE(i.background||`#FFFFFF`),fontColor:BE(xp(i.background)),dataSets:n,labelRange:r,verticalAxis:Dp(t),maxValue:o}},getRuntime(e,t,{extractData:n},r,i){let a=ZE(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:_m(t,a)},options:{...Lh,indexAxis:`y`,layout:kD(t,a),scales:om(t,a),plugins:{title:lO(t,e),legend:HD(t,a),tooltip:yO(t,a),chartShowValuesPlugin:oO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sK={sequence:80,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=eD(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Dm(t,a)},options:{...Lh,layout:kD(t,a),scales:sm(t,a),plugins:{title:lO(t,e),legend:YD(t,a),tooltip:bO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cK={sequence:60,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r,verticalAxis:Dp(t)}},getRuntime(e,t,{extractData:n},r,i){let a=QE(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:Sm(t,a)},options:{...Lh,layout:kD(t,a),scales:rm(t,a),plugins:{title:lO(t,e),legend:GD(t,a),tooltip:hO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},lK={sequence:30,allowedDefinitionKeys:[...$m.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=rD(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:jm(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...Lh,layout:kD(t,a),plugins:{title:lO(t,e),legend:XD(t,a),tooltip:CO(t,a),sunburstLabelsPlugin:aO(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:a.background}},...i}}}}},uK={sequence:100,allowedDefinitionKeys:[...$m.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=rD(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:Im(t,a)},options:{...Lh,layout:kD(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:wO(t,a),background:{color:a.background}},...i}}}}};ib.add(`bar`,OO),ib.add(`combo`,rK),ib.add(`line`,zO),ib.add(`pie`,BO),ib.add(`scorecard`,lh),ib.add(`gauge`,PO),ib.add(`scatter`,cK),ib.add(`waterfall`,VO),ib.add(`pyramid`,oK),ib.add(`radar`,sK),ib.add(`geo`,aK),ib.add(`funnel`,iK),ib.add(`sunburst`,lK),ib.add(`treemap`,uK),ib.add(`calendar`,nK),ib.add(`bubble`,eK),ng.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(`bubble`,{displayName:j(`Bubble`),chartType:`bubble`,chartSubtype:`bubble`,category:`misc`,preview:`o-spreadsheet-ChartPreview.BUBBLE_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`}),iz.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=hf(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:my(n,r,!1),hoverSvg:my(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(BC),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});var dK=l({ARRAYTOTEXT:()=>BK,ARRAY_CONSTRAIN:()=>mK,ARRAY_LITERAL:()=>hK,ARRAY_ROW:()=>gK,CHOOSECOLS:()=>_K,CHOOSEROWS:()=>vK,EXPAND:()=>yK,FLATTEN:()=>bK,FREQUENCY:()=>xK,HSTACK:()=>SK,MDETERM:()=>CK,MINVERSE:()=>wK,MMULT:()=>TK,SUMPRODUCT:()=>EK,SUMX2MY2:()=>OK,SUMX2PY2:()=>kK,SUMXMY2:()=>AK,TOCOL:()=>NK,TOROW:()=>PK,TRANSPOSE:()=>FK,VSTACK:()=>IK,WRAPCOLS:()=>LK,WRAPROWS:()=>RK});function fK(e,t){let n=e.map(L),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 pK(e,t){let n=e.map(L),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=vo(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 mK={description:j(`Returns a result array constrained to a specific width and height.`),args:[B(`input_range (any, range<any>)`,j(`The range to constrain.`)),B(`rows (number)`,j(`The number of rows in the constrained array.`)),B(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=L(e),i=ro(t?.value,this.locale),a=ro(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 vo(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},hK={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return pK(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},gK={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return fK(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},_K={description:j(`Creates a new array from the selected columns in the existing range.`),args:[B(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),B(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=L(e),r=No(t,e=>ro(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},vK={description:j(`Creates a new array from the selected rows in the existing range.`),args:[B(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),B(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=L(e),r=No(t,e=>ro(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?vo(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},yK={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[B(`array (any, range<any>)`,j(`The array to expand.`)),B(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),B(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),B(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=L(e),a=ro(t?.value,this.locale),o=n===void 0?i.length:ro(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())):vo(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},bK={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[No(e,e=>e===void 0?{value:``}:e)]},isExported:!1},xK={description:j(`Calculates the frequency distribution of a range.`),args:[B(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),B(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=No([e],e=>e.value).filter(e=>typeof e==`number`),r=No([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},SK={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return fK(e)},isExported:!0},CK={description:j(`Returns the matrix determinant of a square matrix.`),args:[B(`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=to(e,`square_matrix`);return Hx(t)?Gx(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},wK={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[B(`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=to(e,`square_matrix`);if(!Hx(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=Gx(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},TK={description:j(`Calculates the matrix product of two matrices.`),args:[B(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),B(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=to(e,`matrix1`),r=to(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?qx(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},EK={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[B(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!Vx(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(L),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*=P(n[e][r],this.locale);n+=i}return n},isExported:!0};function DK(e,t,n){if(!Vx(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=L(e),i=L(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 OK={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>e**2-t**2)},isExported:!0},kK={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>e**2+t**2)},isExported:!0},AK={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>(e-t)**2)},isExported:!0},jK=[B(`array (any, range<any>)`,j(`The array which will be transformed.`)),B(`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`)}]),B(`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 MK(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!Ja(e.value);if(t===3)return e=>e.value!==null&&!Ja(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let NK={description:j(`Transforms a range of cells into a single column.`),args:jK,compute:function(e,t={value:0},n={value:!1}){let r=L(e),i=P(t.value,this.locale),a=(I(n.value)?r:xo(r)).flat().filter(MK(i));return a.length===0?new Va(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},PK={description:j(`Transforms a range of cells into a single row.`),args:jK,compute:function(e,t={value:0},n={value:!1}){let r=L(e),i=P(t.value,this.locale),a=(I(n.value)?r:xo(r)).flat().filter(MK(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Va(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},FK={description:j(`Transposes the rows and columns of a range.`),args:[B(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=L(e),n=t[0].length,r=t.length;return vo(n,r,(e,n)=>t[n][e])},isExported:!0},IK={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return pK(e)},isExported:!0},LK={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[B(`range (any, range<any>)`,j(`The range to wrap.`)),B(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),B(`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=L(e),i=ro(t?.value,this.locale);if(!Bx(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return vo(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},RK={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[B(`range (any, range<any>)`,j(`The range to wrap.`)),B(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),B(`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=L(e),i=ro(t?.value,this.locale);if(!Bx(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return vo(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},zK=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],BK={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:[B(`array (range)`,j(`The array to convert into text`)),B(`format (number, default=0)`,j(`The format of the returned data.`),zK)],compute:function(e,t={value:0}){let n=P(t,this.locale),r=L(e);if(n===1)return Dk(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return xo(r).flatMap(e=>e.map(e=>Ja(e.value)?e.value:F(e))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var VK=l({ABS:()=>UK,ACOS:()=>WK,ACOSH:()=>GK,ACOT:()=>KK,ACOTH:()=>qK,ASIN:()=>JK,ASINH:()=>YK,ATAN:()=>XK,ATAN2:()=>ZK,ATANH:()=>QK,CEILING:()=>$K,CEILING_MATH:()=>tq,CEILING_PRECISE:()=>nq,COS:()=>rq,COSH:()=>iq,COT:()=>aq,COTH:()=>oq,COUNTBLANK:()=>sq,COUNTIF:()=>cq,COUNTIFS:()=>lq,COUNTUNIQUE:()=>uq,COUNTUNIQUEIFS:()=>dq,CSC:()=>fq,CSCH:()=>pq,DECIMAL:()=>mq,DEGREES:()=>hq,EXP:()=>gq,FLOOR:()=>_q,FLOOR_MATH:()=>yq,FLOOR_PRECISE:()=>bq,INT:()=>nJ,ISEVEN:()=>xq,ISODD:()=>Cq,ISO_CEILING:()=>Sq,LN:()=>wq,LOG:()=>Tq,MOD:()=>Dq,MUNIT:()=>Oq,ODD:()=>kq,PI:()=>Aq,POWER:()=>jq,PRODUCT:()=>Mq,RAND:()=>Nq,RANDARRAY:()=>Pq,RANDBETWEEN:()=>Fq,ROUND:()=>Iq,ROUNDDOWN:()=>Lq,ROUNDUP:()=>Rq,SEC:()=>zq,SECH:()=>Bq,SEQUENCE:()=>Vq,SIN:()=>Hq,SINH:()=>Uq,SQRT:()=>Wq,SUBTOTAL:()=>Jq,SUM:()=>Yq,SUMIF:()=>Xq,SUMIFS:()=>Zq,TAN:()=>Qq,TANH:()=>$q,TRUNC:()=>tJ});let HK=/^-?[a-z0-9]+$/i,UK={description:j(`Absolute value of a number.`),args:[B(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(P(e,this.locale))},isExported:!0},WK={description:j(`Inverse cosine of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=P(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},GK={description:j(`Inverse hyperbolic cosine of a number.`),args:[B(`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=P(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},KK={description:j(`Inverse cotangent of a value.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=P(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qK={description:j(`Inverse hyperbolic cotangent of a value.`),args:[B(`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=P(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},JK={description:j(`Inverse sine of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=P(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},YK={description:j(`Inverse hyperbolic sine of a number.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(P(e,this.locale))},isExported:!0},XK={description:j(`Inverse tangent of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(P(e,this.locale))},isExported:!0},ZK={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[B(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),B(`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=P(e,this.locale),r=P(t,this.locale);return n===0&&r===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},QK={description:j(`Inverse hyperbolic tangent of a number.`),args:[B(`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=P(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},$K={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),B(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=P(e,this.locale),r=P(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 eq(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 tq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),B(`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=P(t,this.locale);return{value:eq(P(e,this.locale),r,P(n,this.locale)),format:e?.format}},isExported:!0},nq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=P(t,this.locale);return{value:eq(P(e,this.locale),n),format:e?.format}},isExported:!0},rq={description:j(`Cosine of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(P(e,this.locale))},isExported:!0},iq={description:j(`Hyperbolic cosine of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(P(e,this.locale))},isExported:!0},aq={description:j(`Cotangent of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},oq={description:j(`Hyperbolic cotangent of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},sq={description:j(`Number of empty values.`),args:[B(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ho(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},cq={description:j(`A conditional count across a range.`),args:[B(`range (range)`,j(`The range that is tested against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return Do(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},lq={description:j(`Count values depending on multiple criteria.`),args:[B(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return Do(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},uq={description:j(`Counts number of unique values in a range.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return Lx(e)}},dq={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),B(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return Do(t,(t,r)=>{let i=e[t]?.[r];Po(i)&&n.add(i.value)},this.locale),n.size}},fq={description:j(`Cosecant of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},pq={description:j(`Hyperbolic cosecant of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},mq={description:j(`Converts from another base to decimal.`),args:[B(`value (string)`,j(`The number to convert.`)),B(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=P(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=F(e);if(r===``)return 0;if(!HK.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},hq={description:j(`Converts an angle value in radians to degrees.`),args:[B(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return P(e,this.locale)*180/Math.PI},isExported:!0},gq={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[B(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(P(e,this.locale))},isExported:!0},_q={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),B(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=P(e,this.locale),r=P(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 vq(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 yq={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),B(`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=P(t,this.locale);return{value:vq(P(e,this.locale),r,P(n,this.locale)),format:e?.format}},isExported:!0},bq={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=P(t,this.locale);return{value:vq(P(e,this.locale),n),format:e?.format}},isExported:!0},xq={description:j(`Whether the provided value is even.`),args:[B(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=no(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},Sq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:eq(P(e,this.locale),P(t,this.locale)),format:e?.format}},isExported:!0},Cq={description:j(`Whether the provided value is even.`),args:[B(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=no(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},wq={description:j(`The logarithm of a number, base e (euler's number).`),args:[B(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=P(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Tq={description:j(`The logarithm of a number, for a given base.`),args:[B(`value (number)`,j(`The value for which to calculate the logarithm.`)),B(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=P(e,this.locale),r=P(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 Eq(e,t){zx(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 Dq={description:j(`Modulo (remainder) operator.`),args:[B(`dividend (number)`,j(`The number to be divided to find the remainder.`)),B(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=P(t,this.locale);return{value:Eq(P(e,this.locale),n),format:e?.format}},isExported:!0},Oq={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[B(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=ro(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):Wx(t)},isExported:!0},kq={description:j(`Rounds a number up to the nearest odd integer.`),args:[B(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=P(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},Aq={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},jq={description:j(`A number raised to a power.`),args:[B(`base (number)`,j(`The number to raise to the exponent power.`)),B(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=P(e,this.locale),r=P(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},Mq={description:j(`Result of multiplying a series of numbers together.`),args:[B(`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(gt(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),Ja(e))return r}else r!==void 0&&r.value!==null&&(n*=no(r,this.locale),t+=1);return{value:t===0?0:n,format:qa(e[0])}},isExported:!0},Nq={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},Pq={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[B(`rows (number, default=1)`,j(`The number of rows to be returned.`)),B(`columns (number, default=1)`,j(`The number of columns to be returned.`)),B(`min (number, default=0)`,j(`The minimum number you would like returned.`)),B(`max (number, default=1)`,j(`The maximum number you would like returned.`)),B(`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=ro(t,this.locale),o=ro(e,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=I(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},Fq={description:j(`Random integer between two values, inclusive.`),args:[B(`low (number)`,j(`The low end of the random range.`)),B(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=P(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=P(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},Iq={description:j(`Rounds a number according to standard rules.`),args:[B(`value (number)`,j(`The value to round to places number of places.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},Lq={description:j(`Rounds down a number.`),args:[B(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},Rq={description:j(`Rounds up a number.`),args:[B(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},zq={description:j(`Secant of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(P(e,this.locale))},isExported:!0},Bq={description:j(`Hyperbolic secant of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(P(e,this.locale))},isExported:!0},Vq={description:j(`Returns a sequence of numbers.`),args:[B(`rows (number)`,j(`The number of rows to return`)),B(`columns (number, optional, default=1)`,j(`The number of columns to return`)),B(`start (number, optional, default=1)`,j(`The first number in the sequence`)),B(`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=P(n,this.locale),a=P(r,this.locale),o=ro(e,this.locale),s=ro(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)):vo(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},Hq={description:j(`Sine of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(P(e,this.locale))},isExported:!0},Uq={description:j(`Hyperbolic sine of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(P(e,this.locale))},isExported:!0},Wq={description:j(`Positive square root of a positive number.`),args:[B(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=P(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},Gq={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},Kq=Object.entries(Gq).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),qq=Object.entries(Gq).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),Jq={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[B(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...Kq,...qq]),B(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=ro(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=L(e),n=t[0][0]?.position;if(n===void 0)return new Ba(Za);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||!xn(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[Gq[n]].apply(this,[[i]])},isExported:!0},Yq={description:j(`Sum of a series of numbers and/or cells.`),args:[B(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:Ix(e,this.locale),format:qa(t)}},isExported:!0},Xq={description:j(`A conditional sum across a range.`),args:[B(`criteria_range (range)`,j(`The range which is tested against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to range.`)),B(`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 Do([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},Zq={description:j(`Sums a range depending on multiple criteria.`),args:[B(`sum_range (range)`,j(`The range to sum.`)),B(`criteria_range (any, range, repeating)`,j(`Range to check.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return Do(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},Qq={description:j(`Tangent of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(P(e,this.locale))},isExported:!0},$q={description:j(`Hyperbolic tangent of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(P(e,this.locale))},isExported:!0};function eJ(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let tJ={description:j(`Truncates a number.`),args:[B(`value (number)`,j(`The value to be truncated.`)),B(`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:eJ(P(e,this.locale),P(t,this.locale)),format:e?.format}},isExported:!0},nJ={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[B(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(P(e,this.locale))},isExported:!0};var rJ=l({AVEDEV:()=>pJ,AVERAGE:()=>mJ,AVERAGEA:()=>vJ,AVERAGEIF:()=>yJ,AVERAGEIFS:()=>bJ,AVERAGE_WEIGHTED:()=>_J,CORREL:()=>HJ,COUNT:()=>xJ,COUNTA:()=>SJ,COVAR:()=>CJ,COVARIANCE_P:()=>wJ,COVARIANCE_S:()=>TJ,FORECAST:()=>EJ,GROWTH:()=>DJ,INTERCEPT:()=>OJ,LARGE:()=>kJ,LINEST:()=>AJ,LOGEST:()=>jJ,MATTHEWS:()=>MJ,MAX:()=>NJ,MAXA:()=>PJ,MAXIFS:()=>FJ,MEDIAN:()=>IJ,MIN:()=>LJ,MINA:()=>RJ,MINIFS:()=>zJ,PEARSON:()=>VJ,PERCENTILE:()=>UJ,PERCENTILE_EXC:()=>WJ,PERCENTILE_INC:()=>GJ,POLYFIT_COEFFS:()=>KJ,POLYFIT_FORECAST:()=>qJ,QUARTILE:()=>JJ,QUARTILE_EXC:()=>YJ,QUARTILE_INC:()=>XJ,RANK:()=>ZJ,RSQ:()=>QJ,SLOPE:()=>$J,SMALL:()=>eY,SPEARMAN:()=>tY,STDEV:()=>nY,STDEVA:()=>aY,STDEVP:()=>oY,STDEVPA:()=>sY,STDEV_P:()=>rY,STDEV_S:()=>iY,STEYX:()=>cY,TREND:()=>lY,VAR:()=>uY,VARA:()=>pY,VARP:()=>mY,VARPA:()=>hY,VAR_P:()=>dY,VAR_S:()=>fY});let iJ=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],aJ=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],oJ=[{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)`)}],sJ=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],cJ=[{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 lJ(e,t){let n=[],r=[],i=0,a=0;fo([e],e=>{n.push(e),i+=1}),fo([t],e=>{r.push(e),a+=1}),Rx(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 uJ(e,t,n){let{flatDataX:r,flatDataY:i}=lJ(e,t),a=i.length;zx(a),n&&zx(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 dJ(e,t,n,r){let i=0,a=n?_o:go,o=a(e,(e,t)=>(i+=1,e+t),0,r);zx(i),t&&zx(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function fJ(e,t,n,r){let i=P(t,r);Rx(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 fo(e,e=>{let t=e?.value;typeof t==`number`&&(o=Oo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),Rx(s!==0,Fo),n||Rx(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Oa(a,i,n)}let pJ={description:j(`Average magnitude of deviations from mean.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=go(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return go(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},mJ={description:j(`Numerical average value in a dataset, ignoring text.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Qx(e,this.locale),format:qa(e[0])}},isExported:!0},hJ=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),gJ=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),_J={description:j(`Weighted average.`),args:[B(`values (number, range<number>, repeating)`,j(`Value to average.`)),B(`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(!Vx(i,a))return new N(hJ);if(gt(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=gt(a)?a?.[e][r].value:P(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(gJ);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=P(i,this.locale),r=gt(a)?a?.[0][0].value:P(a,this.locale);if(typeof r==`number`){if(r<0)return new N(gJ);t+=e*r,n+=r}}}return n===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:qa(e[0])}}},vJ={description:j(`Numerical average value in a dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=_o(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:qa(e[0])}},isExported:!0},yJ={description:j(`Average of values depending on criteria.`),args:[B(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),B(`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=L(n===void 0?e:n),i=0,a=0;return Do([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},bJ={description:j(`Average of values depending on multiple criteria.`),args:[B(`average_range (range)`,j(`The range to average.`)),B(`criteria_range (any, range, repeating)`,j(`Range to check.`)),B(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=L(e),r=0,i=0;return Do(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},xJ={description:j(`The number of numeric values in dataset.`),args:[B(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return eS(e,this.locale)},isExported:!0},SJ={description:j(`The number of values in a dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return tS(e)},isExported:!0},CJ={description:j(`The covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!1)},isExported:!0},wJ={description:j(`The covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!1)},isExported:!0},TJ={description:j(`The sample covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!0)},isExported:!0},EJ={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[B(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`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}=lJ(t,n);return r.length===0||i.length===0?new Va(Fo):dS([i],[r],yo(L(e),e=>P(e,this.locale)),!0)},isExported:!0},DJ={description:j(`Fits points to exponential growth trend.`),args:[B(`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.`)),B(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),B(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),B(`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.`),iJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Io(`known_data_y`)):lS(dS(uS(to(e,`known_data_y`)),to(t,`known_data_x`),to(n,`new_data_y`),I(r)))}},OJ={description:j(`Compute the intercept of the linear regression.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);let[[],[i]]=aS([n],[r]);return i},isExported:!0},kJ={description:j(`Nth largest element from a data set.`),args:[B(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),B(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(P(t?.value,this.locale)),r=[],i,a=0;fo([e],e=>{typeof e?.value==`number`&&(i=Oo(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(Fo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},AJ={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),B(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),iJ),B(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),aJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Io(`data_y`)):aS(to(t,`data_x`),to(e,`data_y`),I(n),I(r))},isExported:!0},jJ={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),B(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),iJ),B(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),aJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Io(`data_y`));let i=aS(to(t,`data_x`),uS(to(e,`data_y`)),I(n),I(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},MJ={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[B(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),B(`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(Zx(n,r),n.length===0||r.length===0)return new Va(Fo);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=I(n[e]);t===I(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},NJ={description:j(`Maximum value in a numeric dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return nS(e,this.locale)},isExported:!0},PJ={description:j(`Maximum numeric value in a dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=_o(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:qa(e[0])}},isExported:!0},FJ={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),B(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return Do(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},IJ={description:j(`Median value in a numeric dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return po(e,e=>{t.push(e)},this.locale),{value:fJ(t,{value:.5},!0,this.locale),format:qa(t[0])}},isExported:!0},LJ={description:j(`Minimum value in a numeric dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return rS(e,this.locale)},isExported:!0},RJ={description:j(`Minimum numeric value in a dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=_o(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:qa(e[0])}},isExported:!0},zJ={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),B(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return Do(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 BJ(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);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 VJ={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return BJ(e,t)},isExported:!0},HJ=VJ,UJ={description:j(`Value at a given percentile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return GJ.compute.bind(this)(e,t)},isExported:!0},WJ={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`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:fJ([e],t,!1,this.locale),format:qa(e)}},isExported:!0},GJ={description:j(`Value at a given percentile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:fJ([e],t,!0,this.locale),format:qa(e)}},isExported:!0},KJ={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),B(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),oJ),B(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),sJ)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=lJ(e,t);return i.length===0||a.length===0?new Va(Fo):oS(a,i,P(n,this.locale),I(r))},isExported:!1},qJ={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[B(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),B(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),oJ),B(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),sJ)],compute:function(e,t,n,r,i={value:!0}){let a=P(r,this.locale),{flatDataX:o,flatDataY:s}=lJ(t,n);if(o.length===0||s.length===0)return new Va(Fo);let c=oS(s,o,a,I(i)).flat();return yo(L(e),e=>cS(c,P(e,this.locale),a))},isExported:!1},JJ={description:j(`Value nearest to a specific quartile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`quartile_number (number)`,j(`Which quartile value to return.`),cJ)],compute:function(e,t){return XJ.compute.bind(this)(e,t)},isExported:!0},YJ={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`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(P(t,this.locale))};return{value:fJ([e],n,!1,this.locale),format:qa(e)}},isExported:!0},XJ={description:j(`Value nearest to a specific quartile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`quartile_number (number)`,j(`Which quartile value to return.`),cJ)],compute:function(e,t){let n={value:.25*Math.trunc(P(t,this.locale))};return{value:fJ([e],n,!0,this.locale),format:qa(e)}},isExported:!0},ZJ={description:j(`Returns the rank of a specified value in a dataset.`),args:[B(`value (number)`,j(`The value whose rank will be determined.`)),B(`data (range)`,j(`The range containing the dataset to consider.`)),B(`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=I(n),i=P(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=P(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Va(j(`Value not found in the given data.`))},isExported:!0},QJ={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=BJ(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},$J={description:j(`Compute the slope of the linear regression.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);let[[i]]=aS([n],[r]);return i},isExported:!0},eY={description:j(`Nth smallest element in a data set.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(P(t?.value,this.locale)),r=[],i,a=0;fo([e],e=>{typeof e?.value==`number`&&(i=Oo(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(Fo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},tY={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(t,e);if(n.length===0||r.length===0)return new Va(Fo);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},nY={description:j(`Standard deviation.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(uY.compute.bind(this)(...e))},isExported:!0},rY={description:j(`Standard deviation of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(dY.compute.bind(this)(...e))},isExported:!0},iY={description:j(`Standard deviation.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(fY.compute.bind(this)(...e))},isExported:!0},aY={description:j(`Standard deviation of sample (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(pY.compute.bind(this)(...e))},isExported:!0},oY={description:j(`Standard deviation of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(mY.compute.bind(this)(...e))},isExported:!0},sY={description:j(`Standard deviation of entire population (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(hY.compute.bind(this)(...e))},isExported:!0},cY={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);return n.length===0||r.length===0?new Va(Fo):aS([n],[r],!0,!0)[1][2]},isExported:!0},lY={description:j(`Fits points to linear trend derived via least-squares.`),args:[B(`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.`)),B(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),B(`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.`)),B(`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.`),iJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Io(`known_data_y`)):dS(to(e,`known_data_y`),to(t,`known_data_x`),to(n,`new_data_y`),I(r))}},uY={description:j(`Variance.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!1,this.locale)},isExported:!0},dY={description:j(`Variance of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!1,this.locale)},isExported:!0},fY={description:j(`Variance.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!1,this.locale)},isExported:!0},pY={description:j(`Variance of sample (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!0,this.locale)},isExported:!0},mY={description:j(`Variance of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!1,this.locale)},isExported:!0},hY={description:j(`Variance of entire population (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!0,this.locale)},isExported:!0};var gY=l({DAVERAGE:()=>yY,DCOUNT:()=>bY,DCOUNTA:()=>xY,DGET:()=>SY,DMAX:()=>CY,DMIN:()=>wY,DPRODUCT:()=>TY,DSTDEV:()=>EY,DSTDEVP:()=>DY,DSUM:()=>OY,DVAR:()=>kY,DVARP:()=>AY});function _Y(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(F(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=F(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,F(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=F(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)Do(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 vY=[B(`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.`)),B(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),B(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],yY={description:j(`Average of a set of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return mJ.compute.bind(this)([r])},isExported:!0},bY={description:j(`Counts values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return xJ.compute.bind(this)([r])},isExported:!0},xY={description:j(`Counts values and text from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return SJ.compute.bind(this)([r])},isExported:!0},SY={description:j(`Single value from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},CY={description:j(`Maximum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return NJ.compute.bind(this)([r])},isExported:!0},wY={description:j(`Minimum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return LJ.compute.bind(this)([r])},isExported:!0},TY={description:j(`Product of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return Mq.compute.bind(this)([r])},isExported:!0},EY={description:j(`Standard deviation of population sample from table.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return nY.compute.bind(this)([r])},isExported:!0},DY={description:j(`Standard deviation of entire population from table.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return oY.compute.bind(this)([r])},isExported:!0},OY={description:j(`Sum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return Yq.compute.bind(this)([r])},isExported:!0},kY={description:j(`Variance of population sample from table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return uY.compute.bind(this)([r])},isExported:!0},AY={description:j(`Variance of a population from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return mY.compute.bind(this)([r])},isExported:!0},jY=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),MY=j(`There must be both positive and negative values in cashflow_amounts.`),NY=e=>j(`The cost (%s) must be positive or null.`,e),PY=e=>j(`The cost (%s) must be strictly positive.`,e),FY=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),IY=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),LY=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),RY=e=>j(`The discount (%s) must be different from -1.`,e),zY=e=>j(`The discount (%s) must be strictly positive.`,e),BY=e=>j(`The discount (%s) must be smaller than 1.`,e),VY=e=>j(`The effective_rate (%s) must be strictly positive.`,e),HY=e=>j(`The end_period (%s) must be positive or null.`,e),UY=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),WY=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),GY=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),KY=e=>j(`The first_period (%s) must be strictly positive.`,e),qY=e=>j(`The future_value (%s) must be strictly positive.`,e),JY=e=>j(`The investment (%s) must be strictly positive.`,e),YY=e=>j(`The issue (%s) must be positive or null.`,e),XY=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),ZY=e=>j(`The last_period (%s) must be strictly positive.`,e),QY=e=>j(`The life (%s) must be strictly positive.`,e),$Y=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),eX=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),tX=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),nX=e=>j(`The number_of_periods (%s) must be different from zero.`,e),rX=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),iX=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),aX=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),oX=e=>j(`The period (%s) must be positive or null.`,e),sX=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),cX=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),lX=e=>j(`The period (%s) must be strictly positive.`,e),uX=e=>j(`The present_value (%s) must be strictly positive.`,e),dX=e=>j(`The price (%s) must be strictly positive.`,e),fX=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),pX=e=>j(`The purchase_date (%s) must be positive or null.`,e),mX=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),hX=e=>j(`The rate (%s) must be positive or null.`,e),gX=e=>j(`The rate (%s) must be strictly positive.`,e),_X=e=>j(`The redemption (%s) must be strictly positive.`,e),vX=e=>j(`The salvage (%s) must be positive or null.`,e),yX=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),bX=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),xX=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),SX=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),CX=e=>j(`The start_period (%s) must be positive or null.`,e),wX=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),TX=e=>j(`The unit (%s) must be strictly positive.`,e),EX=e=>j(`The yield (%s) must be positive or null.`,e);function DX(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function OX(e){return![0,1,2,3,4].includes(e)}function kX(e){return![1,2,4].includes(e)}function AX(e,t,n){let r=co(e,n),i=co(t,n),a=co(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let jX=[{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 MX=l({DATE:()=>PX,DATEDIF:()=>FX,DATEVALUE:()=>IX,DAY:()=>LX,DAYS:()=>RX,DAYS360:()=>zX,EDATE:()=>BX,EOMONTH:()=>VX,HOUR:()=>HX,ISOWEEKNUM:()=>UX,MINUTE:()=>WX,MONTH:()=>GX,MONTH_END:()=>cZ,MONTH_START:()=>sZ,NETWORKDAYS:()=>KX,NETWORKDAYS_INTL:()=>YX,NOW:()=>XX,QUARTER:()=>lZ,QUARTER_END:()=>dZ,QUARTER_START:()=>uZ,SECOND:()=>ZX,TIME:()=>QX,TIMEVALUE:()=>$X,TODAY:()=>eZ,WEEKDAY:()=>tZ,WEEKNUM:()=>nZ,WORKDAY:()=>rZ,WORKDAY_INTL:()=>iZ,YEAR:()=>aZ,YEARFRAC:()=>oZ,YEAR_END:()=>pZ,YEAR_START:()=>fZ}),NX=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}(NX||{});let PX={description:j(`Converts year/month/day into a date.`),args:[B(`year (number)`,j(`The year component of the date.`)),B(`month (number)`,j(`The month component of the date.`)),B(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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=oa(new Ni(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},FX={description:j(`Calculates the number of days, months, or years between two dates.`),args:[B(`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.`)),B(`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.`)),B(`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=F(n).toUpperCase();if(!Object.values(NX).includes(r))return new N($a(Object.values(NX),F(n)));let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=aa(i),s=aa(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 ha(o,s);case`M`:return pa(o,s);case`D`:return ma(o,s);case`YM`:return pa(o,s)-ha(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=ca(new Ni(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(ga(i,a))return ma(o,s);let e=new Ni(o.getFullYear(),s.getMonth(),s.getDate()),t=ma(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=ma(o,e)),t}}},isExported:!0},IX={description:j(`Converts a date string to a date value.`),args:[B(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=F(e),n=Yi(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},LX={description:j(`Day of the month that a specific date falls on.`),args:[B(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return co(e,this.locale).getDate()},isExported:!0},RX={description:j(`Number of days between two dates.`),args:[B(`end_date (date)`,j(`The end of the date range.`)),B(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=co(e,this.locale),r=co(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Fi)},isExported:!0},zX={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[B(`start_date (date)`,j(`The start date to consider in the calculation.`)),B(`end_date (date)`,j(`The end date to consider in the calculation.`)),B(`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(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=fa(r,i,I(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},BX={description:j(`Date a number of months before/after another date.`),args:[B(`start_date (date)`,j(`The date from which to calculate the result.`)),B(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:oa(ua(co(e,this.locale),Math.trunc(P(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},VX={description:j(`Last day of a month before or after a date.`),args:[B(`start_date (date)`,j(`The date from which to calculate the result.`)),B(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=co(e,this.locale),r=Math.trunc(P(t,this.locale));return{value:oa(new Ni(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},HX={description:j(`Hour component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return co(e,this.locale).getHours()},isExported:!0},UX={description:j(`ISO week number of the year.`),args:[B(`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=co(e,this.locale),n=t.getFullYear(),r=1;for(;new Ni(n,0,r).getDay()!==4;)r+=1;let i=new Ni(n,0,r-3),a=31;for(;new Ni(n,11,a).getDay()!==4;)--a;let o=new Ni(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 Ni(n,11,a+3+1);break;case-1:let e=1;for(;new Ni(n-1,0,e).getDay()!==4;)e+=1;c=new Ni(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Fi;return Math.floor(l/7)+1},isExported:!0},WX={description:j(`Minute component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return co(e,this.locale).getMinutes()},isExported:!0},GX={description:j(`Month of the year a specific date falls in`),args:[B(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return co(e,this.locale).getMonth()+1},isExported:!0},KX={description:j(`Net working days between two provided days.`),args:[B(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),B(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),B(`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 YX.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function qX(e){let t=e?.value;if(typeof t==`string`){Rx(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 Rx(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 JX=[{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`)}],YX={description:j(`Net working days between two dates (specifying weekends).`),args:[B(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),B(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),B(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),JX),B(`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=co(e,this.locale),a=co(t,this.locale),o=qX(n),s=new Set;r!==void 0&&fo([r],e=>{let t=co(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=Ni.fromTimestamp((c?i:a).getTime()),u=Ni.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},XX={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=Ni.now(),t=e.getTime()-Pi.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Fi)+n,format:z_(this.locale)}},isExported:!0},ZX={description:j(`Minute component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return co(e,this.locale).getSeconds()},isExported:!0},QX={description:j(`Converts hour/minute/second into a time.`),args:[B(`hour (number)`,j(`The hour component of the time.`)),B(`minute (number)`,j(`The minute component of the time.`)),B(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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},$X={description:j(`Converts a time string into its serial number representation.`),args:[B(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=F(e),n=Yi(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},eZ={description:j(`Current date as a date value.`),args:[],compute:function(){let e=Ni.now();return{value:oa(new Ni(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},tZ={description:j(`Day of the week of the date provided (as number).`),args:[B(`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.`)),B(`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=co(e,this.locale),r=Math.round(P(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},nZ={description:j(`Week number of the year.`),args:[B(`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.`)),B(`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=co(e,this.locale),r=Math.round(P(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 UX.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 Ni(a,0,o);for(;s.getDay()!==i;)o+=1,s=new Ni(a,0,o);let c=(n.getTime()-s.getTime())/Fi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},rZ={description:j(`Date after a number of workdays.`),args:[B(`start_date (date)`,j(`The date from which to begin counting.`)),B(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),B(`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 iZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0},iZ={description:j(`Date after a number of workdays (specifying weekends).`),args:[B(`start_date (date)`,j(`The date from which to begin counting.`)),B(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),B(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),JX),B(`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=co(e,this.locale),a=Math.trunc(P(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=qX(n),s=new Set;r!==void 0&&fo([r],e=>{let t=co(e,this.locale);s.add(t.getTime())});let c=Ni.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-Pi.getTime();return{value:Math.round(f/Fi),format:this.locale.dateFormat}},isExported:!0},aZ={description:j(`Year specified by a given date.`),args:[B(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return co(e,this.locale).getFullYear()},isExported:!0},oZ={description:j(`Exact number of years between two dates.`),args:[B(`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.`)),B(`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.`)),B(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n={value:0}){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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)):fa(r,i,a)}},sZ={description:j(`First day of the month preceding a date.`),args:[B(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=co(e,this.locale);return{value:oa(new Ni(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},cZ={description:j(`Last day of the month following a date.`),args:[B(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return VX.compute.bind(this)(e,{value:0})}},lZ={description:j(`Quarter of the year a specific date falls in`),args:[B(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((co(e,this.locale).getMonth()+1)/3)}},uZ={description:j(`First day of the quarter of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=lZ.compute.bind(this)(e);return{value:oa(new Ni(aZ.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},dZ={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=lZ.compute.bind(this)(e);return{value:oa(new Ni(aZ.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},fZ={description:j(`First day of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:oa(new Ni(aZ.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},pZ={description:j(`Last day of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:oa(new Ni(aZ.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var mZ=l({DELTA:()=>hZ});let hZ={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[B(`number1 (number)`,j(`The first number to compare.`)),B(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(P(e,this.locale)===P(t,this.locale))},isExported:!0};var gZ=l({FILTER:()=>vZ,SORT:()=>yZ,SORTN:()=>bZ,UNIQUE:()=>xZ});function _Z(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;Rx(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(I(Jx(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(gt(s)&&(s.length>1||s[0].length>1))Rx(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=P(Jx(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:iV(`desc`),asc:iV(`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 vZ={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[B(`range (any, range<any>)`,j(`The data to be filtered.`)),B(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=L(e),r=t.map(e=>yo(L(e),e=>e.value));for(let e of r)if(!Bx(e))return new N(j(`The arguments condition must be a single column or row.`));if(!Vx(...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`?xo(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`?xo(o):o:new Va(j(`No match found in FILTER evaluation`))},isExported:!1},yZ={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[B(`range (range)`,j(`The data to be sorted.`)),B(`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.`)),B(`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 xo(_Z(xo(e),this.locale,...t))},isExported:!0},bZ={description:j(`Returns the first n items in a data set after performing a sort.`),args:[B(`range (range)`,j(`The data to be sorted.`)),B(`n (number)`,j(`The number of items to return.`)),B(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),B(`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.`)),B(`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=P(t?.value??1,this.locale),i=n.length%2==0?0:P(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=_Z(xo(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 xo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return xo(o.slice(0,e));return xo(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 xo(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 xo(e)}}},isExported:!1},xZ={description:j(`Unique rows in the provided source range.`),args:[B(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),B(`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`)}]),B(`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(!gt(e))return[[e]];let r=I(t?.value)||!1,i=I(n?.value)||!1;r||(e=xo(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:xo(o):new N(j(`No unique values found`))},isExported:!0};var SZ=l({ACCRINTM:()=>DZ,AMORLINC:()=>OZ,COUPDAYBS:()=>AZ,COUPDAYS:()=>kZ,COUPDAYSNC:()=>jZ,COUPNCD:()=>MZ,COUPNUM:()=>NZ,COUPPCD:()=>PZ,CUMIPMT:()=>FZ,CUMPRINC:()=>IZ,DB:()=>LZ,DDB:()=>zZ,DISC:()=>BZ,DOLLARDE:()=>VZ,DOLLARFR:()=>HZ,DURATION:()=>UZ,EFFECT:()=>WZ,FV:()=>KZ,FVSCHEDULE:()=>qZ,INTRATE:()=>JZ,IPMT:()=>XZ,IRR:()=>QZ,ISPMT:()=>$Z,MDURATION:()=>eQ,MIRR:()=>tQ,NOMINAL:()=>nQ,NPER:()=>rQ,NPV:()=>aQ,PDURATION:()=>oQ,PMT:()=>cQ,PPMT:()=>uQ,PRICE:()=>fQ,PRICEDISC:()=>pQ,PRICEMAT:()=>mQ,PV:()=>dQ,RATE:()=>gQ,RECEIVED:()=>_Q,RRI:()=>vQ,SLN:()=>yQ,SYD:()=>bQ,TBILLEQ:()=>CQ,TBILLPRICE:()=>SQ,TBILLYIELD:()=>wQ,VDB:()=>TQ,XIRR:()=>EQ,XNPV:()=>DQ,YIELD:()=>OQ,YIELDDISC:()=>kQ,YIELDMAT:()=>AQ});let CZ=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],wZ=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],TZ=[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)];function EZ(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)){Rx(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,Rx(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let DZ={description:j(`Accrued interest of security paying at maturity.`),args:[B(`issue (date)`,j(`The date the security was initially issued.`)),B(`maturity (date)`,j(`The maturity date of the security.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(r,this.locale),c=P(n,this.locale),l=Math.trunc(P(i,this.locale));if(a<0)return new N(YY(a));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(_X(s));if(c<=0)return new N(gX(c));let u=fa(a,o,l);return s*c*u},isExported:!0},OZ={description:j(`Depreciation for an accounting period.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`purchase_date (date)`,j(`The date the asset was purchased.`)),B(`first_period_end (date)`,j(`The date the first period ended.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`rate (number)`,j(`The deprecation rate.`)),B(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=P(e,this.locale),c=Math.trunc(P(t,this.locale)),l=Math.trunc(P(n,this.locale)),u=P(r,this.locale),d=P(i,this.locale),f=P(a,this.locale),p=Math.trunc(P(o,this.locale));if(s<=0)return new N(PY(s));if(c<0)return new N(pX(c));if(u<0)return new N(vX(u));if(u>s)return new N(yX(u,s));if(d<0)return new N(oX(d));if(f<=0)return new N(gX(f));if(OX(p))return new N(IY(p));if(c>l)return new N(fX(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=fa(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},kZ={description:j(`Days in coupon period containing settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));if(s===1){let i=PZ.compute.bind(this)(e,t,n,r).value,a=MZ.compute.bind(this)(e,t,n,r).value;return P(a,this.locale)-P(i,this.locale)}return(s===3?365:360)/o},isExported:!0},AZ={description:j(`Days from settlement until next coupon.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=PZ.compute.bind(this)(e,t,n,r).value,l=P(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=fa(l,i,s);return Math.round(e*360)}let u=co(i,this.locale),d=co(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&&la(d)&&la(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&la(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},jZ={description:j(`Days from settlement until next coupon.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=MZ.compute.bind(this)(e,t,n,r).value,l=P(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=fa(i,l,s);return Math.round(e*360)}let u=AZ.compute.bind(this)(e,t,n,r);return P(kZ.compute.bind(this)(e,t,n,r),this.locale)-P(u,this.locale)},isExported:!0},MZ={description:j(`Next coupon date after the settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=12/o,l=NZ.compute.bind(this)(e,t,n,r);return{value:oa(ua(co(a,this.locale),-(P(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},NZ={description:j(`Number of coupons between settlement and maturity.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=1,l=a,u=12/o;for(;l>i;)l=oa(ua(co(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},PZ={description:j(`Last coupon date prior to or on the settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=12/o,l=NZ.compute.bind(this)(e,t,n,r);return{value:oa(ua(co(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},FZ={description:j(`Cumulative interest paid over a set of periods.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),B(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i,a={value:0}){let o=P(r,this.locale),s=P(i,this.locale),c=P(e,this.locale),l=P(n,this.locale),u=P(t,this.locale),d=+!!I(a);if(u<=0)return new N(rX(u));if(o<=0)return new N(KY(o));if(s<=0)return new N(ZY(s));if(o>s)return new N(GY(o,s));if(s>u)return new N(XY(s,u));if(c<=0)return new N(gX(c));if(l<=0)return new N(uX(l));let f=0;for(let e=o;e<=s;e++)f+=YZ(c,e,u,l,0,d);return f},isExported:!0},IZ={description:j(`Cumulative principal paid over a set of periods.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),B(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i,a={value:0}){let o=P(r,this.locale),s=P(i,this.locale),c=P(e,this.locale),l=P(n,this.locale),u=P(t,this.locale),d=+!!I(a);if(u<=0)return new N(rX(u));if(o<=0)return new N(KY(o));if(s<=0)return new N(ZY(s));if(o>s)return new N(GY(o,s));if(s>u)return new N(XY(s,u));if(c<=0)return new N(gX(c));if(l<=0)return new N(uX(l));let f=0;for(let e=o;e<=s;e++)f+=lQ(c,e,u,l,0,d);return f},isExported:!0},LZ={description:j(`Depreciation via declining balance method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=Math.trunc(P(r,this.locale)),l=i.length?Math.trunc(P(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(NY(a));if(o<0)return new N(vX(o));if(c<=0)return new N(lX(c));if(s<=0)return new N(QY(s));if(1>l||l>12)return new N(eX(l));if(c>u)return new N(aX(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},RZ=`#,##0.00`,zZ={description:j(`Depreciation via double-declining balance method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=P(i,this.locale);if(a<0)return new N(NY(a));if(o<0)return new N(vX(o));if(c<=0)return new N(lX(c));if(s<=0)return new N(QY(s));if(c>s)return new N(cX(c,s));if(l<=0)return new N(LY(l));if(a===0||o>=a)return{value:0,format:RZ};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:RZ};if(c<=1)return{value:a*u,format:RZ};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:RZ}},isExported:!0},BZ={description:j(`Discount rate of a security based on price.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(dX(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return(c-s)/c/u},isExported:!0},VZ={description:j(`Convert a decimal fraction to decimal value.`),args:[B(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),B(`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=P(e,this.locale),r=Math.trunc(P(t,this.locale));if(r<=0)return new N(TX(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},HZ={description:j(`Convert a decimal value to decimal fraction.`),args:[B(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),B(`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=P(e,this.locale),r=Math.trunc(P(t,this.locale));if(r<=0)return new N(TX(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},UZ={description:j(`Number of periods for an investment to reach a value.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=P(n,this.locale),l=P(r,this.locale),u=Math.trunc(P(i,this.locale)),d=Math.trunc(P(a,this.locale));if(o>=s)return new N($Y(o,s));if(kX(u))return new N(FY(u));if(OX(d))return new N(IY(d));if(c<0)return new N(hX(c));if(l<0)return new N(EX(l));let f=fa(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},WZ={description:j(`Annual effective interest rate.`),args:[B(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),B(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=P(e,this.locale),r=Math.trunc(P(t,this.locale));return n<=0?new N(tX(n)):r<=0?new N(sX(r)):(1+n/r)**+r-1},isExported:!0};function GZ(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 KZ={description:j(`Future value of an annuity investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_amount (number)`,j(`The amount per period to be paid.`)),B(`present_value (number, default=0)`,j(`The current value of the annuity.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:GZ(P(e,this.locale),P(t,this.locale),P(n,this.locale),P(r,this.locale),+!!I(i)),format:`#,##0.00`}},isExported:!0},qZ={description:j(`Future value of principal from series of rates.`),args:[B(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),B(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=P(e,this.locale);return ho([t],(e,t)=>e*(1+P(t,this.locale)),n)},isExported:!0},JZ={description:j(`Calculates effective interest rate.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`investment (number)`,j(`The amount invested in the security.`)),B(`redemption (number)`,j(`The amount to be received at maturity.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(r,this.locale),c=P(n,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(c<=0)return new N(JY(c));if(s<=0)return new N(_X(s));if(OX(l))return new N(IY(l));let u=fa(a,o,l);return(s-c)/c/u},isExported:!0};function YZ(e,t,n,r,i,a){return sQ(e,n,r,i,a)-lQ(e,t,n,r,i,a)}let XZ={description:j(`Payment on the principal of an investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`period (number)`,j(`The amortization period, in terms of number of periods.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:YZ(P(e,this.locale),P(t,this.locale),P(n,this.locale),P(r,this.locale),P(i,this.locale),+!!I(a)),format:`#,##0.00`}},isExported:!0},ZZ=.1,QZ={description:j(`Internal rate of return given periodic cashflows.`),args:[B(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),B(`rate_guess (number, default=${ZZ})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:ZZ}){let n=P(t,this.locale);if(n<=-1)return new N(mX(n));let r=!1,i=!1,a=[];if(po([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(MY);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:EZ(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},$Z={description:j(`Returns the interest paid at a particular period of an investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`period (number)`,j(`The period for which you want to view the interest payment.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=P(e,this.locale),a=P(t,this.locale),o=P(n,this.locale),s=P(r,this.locale);return o===0?new N(nX(o)):-1*(s-a/o*s)*i},isExported:!0},eQ={description:j(`Modified Macaulay duration.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`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=UZ.compute.bind(this)(e,t,n,r,i,a),s=P(r,this.locale),c=Math.trunc(P(i,this.locale));return P(o,this.locale)/(1+s/c)},isExported:!0},tQ={description:j(`Modified internal rate of return.`),args:[B(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),B(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),B(`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=P(t,this.locale),i=P(n,this.locale),a=xo(e).flat().filter(e=>e.value!==null).map(e=>P(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(MY);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},nQ={description:j(`Annual nominal interest rate.`),args:[B(`effective_rate (number)`,j(`The effective interest rate per year.`)),B(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=P(e,this.locale),r=Math.trunc(P(t,this.locale));return n<=0?new N(VY(n)):r<=0?new N(sX(r)):((n+1)**(1/r)-1)*r},isExported:!0},rQ={description:j(`Number of payment periods for an investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`payment_amount (number)`,j(`The amount of each payment made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=+!!I(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 iQ(e,t,n,r){let i=0;return go(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let aQ={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[B(`discount (number)`,j(`The discount rate of the investment over one period.`)),B(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=P(e,this.locale);return n===-1?new N(RY(n)):{value:iQ(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},oQ={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[B(`rate (number)`,j(`The rate at which the investment grows each period.`)),B(`present_value (number)`,j(`The investment's current value.`)),B(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return r<=0?new N(gX(r)):i<=0?new N(uX(i)):a<=0?new N(qY(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function sQ(e,t,n,r,i){if(t<=0)throw new N(rX(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 cQ={description:j(`Periodic payment for an annuity investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){let a=P(t,this.locale),o=P(e,this.locale),s=+!!I(i),c=P(r,this.locale);return{value:sQ(o,a,P(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function lQ(e,t,n,r,i,a){if(n<=0)throw new N(rX(n));if(t<=0||t>n)throw new N(iX(n));let o=sQ(e,n,r,i,a);return a===1&&t===1?o:o+-GZ(e,a===0?t-1:t-2,o,r+o*a,0)*e}let uQ={description:j(`Payment on the principal of an investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`period (number)`,j(`The amortization period, in terms of number of periods.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=P(n,this.locale),s=P(e,this.locale),c=P(t,this.locale),l=+!!I(a),u=P(i,this.locale);return{value:lQ(s,c,o,P(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},dQ={description:j(`Present value of an annuity investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_amount (number)`,j(`The amount per period to be paid.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=+!!I(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},fQ={description:j(`Price of a security paying periodic interest.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(P(e,this.locale)),c=Math.trunc(P(t,this.locale)),l=P(n,this.locale),u=P(r,this.locale),d=P(i,this.locale),f=Math.trunc(P(a,this.locale)),p=Math.trunc(P(o,this.locale));if(s>=c)return new N($Y(s,c));if(kX(f))return new N(FY(f));if(OX(p))return new N(IY(p));if(l<0)return new N(hX(l));if(u<0)return new N(EX(u));if(d<=0)return new N(_X(d));let m=fa(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 ee=0;for(let e=1;e<=h;e++)ee+=v/_**(e-1+g);return d/_**(h-1+g)+ee-v*(1-g)},isExported:!0},pQ={description:j(`Price of a discount security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(zY(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return c-s*c*u},isExported:!0},mQ={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`issue (date)`,j(`The date the security was initially issued.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=Math.trunc(P(n,this.locale)),l=P(r,this.locale),u=P(i,this.locale),d=Math.trunc(P(a,this.locale));if(o<=c)return new N(SX(o,c));if(o>=s)return new N($Y(o,s));if(OX(d))return new N(IY(d));if(l<0)return new N(hX(l));if(u<0)return new N(EX(u));let f=fa(o,s,d),p=fa(o,c,d),m=100+fa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},hQ=.1,gQ={description:j(`Interest rate of an annuity investment.`),args:[B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_per_period (number)`,j(`The amount per period to be paid.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ),B(`rate_guess (number, default=${hQ})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:hQ}){let o=P(e,this.locale),s=P(t,this.locale),c=+!!I(i),l=P(a,this.locale)||hQ,u=P(r,this.locale),d=P(n,this.locale);return o<=0?new N(rX(o)):DX([s,d,u])?l<=-1?new N(mX(l)):(u-=s*c,d+=s*c,{value:EZ(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},_Q={description:j(`Amount received at maturity for a security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),B(`discount (number)`,j(`The discount rate of the security invested in.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));return a>=o?new N($Y(a,o)):OX(l)?new N(IY(l)):s<=0?new N(JY(s)):c<=0?new N(zY(c)):s/(1-c*fa(a,o,l))},isExported:!0},vQ={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[B(`number_of_periods (number)`,j(`The number of periods.`)),B(`present_value (number)`,j(`The present value of the investment.`)),B(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return r<=0?new N(rX(r)):(a/i)**(1/r)-1},isExported:!0},yQ={description:j(`Depreciation of an asset using the straight-line method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},bQ={description:j(`Depreciation via sum of years digit method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=P(e,this.locale),a=P(t,this.locale),o=P(n,this.locale),s=P(r,this.locale);if(s<=0)return new N(lX(s));if(o<=0)return new N(QY(o));if(s>o)return new N(cX(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function xQ(e,t,n){return 100*(1-n*fa(e,t,2))}let SQ={description:j(`Price of a US Treasury bill.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);return r>=i?new N($Y(r,i)):AX(r,i,this.locale)?a<=0?new N(zY(a)):a>=1?new N(BY(a)):xQ(r,i,a):new N(xX(r,i))},isExported:!0},CQ={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);if(r>=i)return new N($Y(r,i));if(!AX(r,i,this.locale))return new N(xX(r,i));if(a<=0)return new N(zY(a));if(a>=1)return new N(BY(a));let o=RX.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=xQ(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},wQ={description:j(`The yield of a US Treasury bill based on price.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);if(r>=i)return new N($Y(r,i));if(!AX(r,i,this.locale))return new N(xX(r,i));if(a<=0)return new N(dX(a));let o=fa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},TQ={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`start (number)`,j(`Starting period to calculate depreciation.`)),B(`end (number)`,j(`Ending period to calculate depreciation.`)),B(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),B(`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=P(e,this.locale),c=P(t,this.locale),l=P(n,this.locale),u=Math.trunc(P(r,this.locale)),d=Math.trunc(P(i,this.locale)),f=P(a,this.locale),p=I(o);if(s<0)return new N(NY(s));if(c<0)return new N(vX(c));if(l<=0)return new N(QY(l));if(u<0)return new N(CX(u));if(d<0)return new N(HY(d));if(u>d)return new N(wX(u,d));if(d>l)return new N(UY(d,l));if(f<=0)return new N(LY(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},EQ={description:j(`Internal rate of return given non-periodic cash flows.`),args:[B(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),B(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),B(`rate_guess (number, default=${hQ})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:hQ}){let r=P(n,this.locale);if(!Vx(e,t))return new N(jY);let i=e.flat().map(e=>P(e,this.locale)),a=t.flat().map(e=>P(e,this.locale));if(!DX(i))return new N(MY);if(a.some(e=>e<a[0]))return new N(WY(a[0]));if(r<=-1)return new N(mX(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 EZ(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},DQ={description:j(`Net present value given to non-periodic cash flows..`),args:[B(`discount (number)`,j(`The discount rate of the investment over one period.`)),B(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),B(`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=P(e,this.locale);if(!Vx(t,n))return new N(jY);let i=L(t).flat().map(e=>no(e,this.locale)),a=L(n).flat().map(e=>no(e,this.locale));if(a.some(e=>e<a[0]))return new N(WY(a[0]));if(r<=0)return new N(gX(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},OQ={description:j(`Annual yield of a security paying periodic interest.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(P(e,this.locale)),c=Math.trunc(P(t,this.locale)),l=P(n,this.locale),u=P(r,this.locale),d=P(i,this.locale),f=Math.trunc(P(a,this.locale)),p=Math.trunc(P(o,this.locale));if(s>=c)return new N($Y(s,c));if(kX(f))return new N(FY(f));if(OX(p))return new N(IY(p));if(l<0)return new N(hX(l));if(u<=0)return new N(dX(u));if(d<=0)return new N(_X(d));let m=fa(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 ee(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 y(e){return v(u,g,h,e,_,d)}function b(e){return ee(u,g,h,e,_)}return(EZ(y,b,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},kQ={description:j(`Annual yield of a discount security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(dX(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return(c/s-1)/u},isExported:!0},AQ={description:j(`Annual yield of a security paying interest at maturity.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`issue (date)`,j(`The date the security was initially issued.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`price (number)`,j(`The price at which the security is bought.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=Math.trunc(P(n,this.locale)),l=P(r,this.locale),u=P(i,this.locale),d=Math.trunc(P(a,this.locale));if(o>=s)return new N($Y(o,s));if(OX(d))return new N(IY(d));if(o<c)return new N(bX(o,c));if(l<0)return new N(hX(l));if(u<=0)return new N(dX(u));let f=fa(c,s,d),p=fa(c,o,d),m=fa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var jQ=l({CELL:()=>NQ,ISBLANK:()=>VQ,ISERR:()=>PQ,ISERROR:()=>FQ,ISFORMULA:()=>UQ,ISLOGICAL:()=>IQ,ISNA:()=>LQ,ISNONTEXT:()=>RQ,ISNUMBER:()=>zQ,ISTEXT:()=>BQ,NA:()=>HQ});let MQ=[{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.`)}],NQ={description:j(`Gets information about a cell.`),args:[B(`info_type (string)`,j(`The type of information requested.`),MQ),B(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=F(e).toLowerCase();if(!MQ.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,MQ.join(`, `)));let r=L(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`:Xs(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},PQ={description:j(`Whether a value is an error other than #N/A.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Ja(t)&&t!==M.NotAvailable},isExported:!0},FQ={description:j(`Whether a value is an error.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Ja(t)},isExported:!0},IQ={description:j("Whether a value is `true` or `false`."),args:[B(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},LQ={description:j(`Whether a value is the error #N/A.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},RQ={description:j(`Whether a value is non-textual.`),args:[B(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!BQ.compute.bind(this)(e)},isExported:!0},zQ={description:j(`Whether a value is a number.`),args:[B(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},BQ={description:j(`Whether a value is text.`),args:[B(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&Ja(e?.value)===!1},isExported:!0},VQ={description:j(`Whether the referenced cell is empty`),args:[B(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},HQ={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},UQ={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[B(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Ba(Za):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var WQ=l({AND:()=>GQ,FALSE:()=>KQ,IF:()=>qQ,IFERROR:()=>JQ,IFNA:()=>YQ,IFS:()=>XQ,NOT:()=>ZQ,OR:()=>QQ,SWITCH:()=>$Q,TRUE:()=>e$,XOR:()=>t$});let GQ={description:j("Logical `and` operator."),args:[B(`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}=Px(e);return n?t:new N(Fo)},isExported:!0},KQ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},qQ={description:j(`Returns value depending on logical expression.`),args:[B(`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.`)),B(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),B(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Xx(e)?lc(this,bc.get(`IF`),[e,t,n]):(I(Jx(e))?t:n)??{value:0}},isExported:!0},JQ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[B(`value (any, range)`,j(`The value to return if value itself is not an error.`)),B(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Xx(e)?lc(this,bc.get(`IFERROR`),[e,t]):(Ja(Jx(e)?.value)?t:e)??{value:0}},isExported:!0},YQ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[B(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),B(`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 Xx(e)?lc(this,bc.get(`IFNA`),[e,t]):(Jx(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},XQ={description:j(`Returns a value depending on multiple logical expressions.`),args:[B(`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.`)),B(`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(Xx(e[0]))return lc(this,bc.get(`IFS`),e);let t=I(Jx(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},ZQ={description:j(`Returns opposite of provided logical value.`),args:[B(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!I(e)},isExported:!0},QQ={description:j("Logical `or` operator."),args:[B(`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}=Fx(e);return n?t:new N(Fo)},isExported:!0},$Q={description:j(`Returns a value by comparing cases to an expression.`),args:[B(`expression (number, boolean, string)`,j(`The value to be checked.`)),B(`case (any, repeating)`,j(`Case to be checked against expression.`)),B(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),B(`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?Ya(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&Ja(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},e$={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},t$={description:j("Logical `xor` operator."),args:[B(`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 Co(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Fo)},isExported:!0};function n$(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function r$(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 i$(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function a$(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=Yn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Ba;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&sr(D(e.__originCellPosition),n))throw new za;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 o$=l({ADDRESS:()=>l$,CHOOSE:()=>E$,COLUMN:()=>u$,COLUMNS:()=>d$,DROP:()=>D$,FORMULATEXT:()=>k$,HLOOKUP:()=>f$,INDEX:()=>p$,INDIRECT:()=>m$,LOOKUP:()=>h$,MATCH:()=>g$,OFFSET:()=>T$,PIVOT:()=>w$,PIVOT_HEADER:()=>C$,PIVOT_VALUE:()=>S$,ROW:()=>_$,ROWS:()=>v$,TAKE:()=>O$,VLOOKUP:()=>y$,XLOOKUP:()=>x$});let s$=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],c$=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],l$={description:j(`Returns a cell reference as a string. `),args:[B(`row (number)`,j(`The row number of the cell reference. `)),B(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),B(`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)`)}]),B(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),s$),B(`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=io(e,this.locale),o=io(t,this.locale);if(a<1)return new N(Ux(a));if(o<1)return new N(Ux(o));let s=io(n,this.locale);if(![1,2,3,4].includes(s))return new N(Qa(1,4,s));let c=I(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:Pc(F(i),l)},isExported:!0},u$={description:j(`Column number of a specified cell.`),args:[B(`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=L(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 Ba(Za);let r=n.position.col;return t.length===1?r+1:vo(t.length,1,e=>({value:r+e+1}))},isExported:!0},d$={description:j(`Number of columns in a specified array or range.`),args:[B(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=L(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},f$={description:j(`Horizontal lookup`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),B(`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.`),c$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(P(n?.value,this.locale)),a=L(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[I(r.value)?Oo(a,e,`nextSmaller`,`asc`,a.length,o):ko(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ya(e):s[i-1]},isExported:!0},p$={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[B(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),B(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),B(`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=L(e),i=P(t.value,this.locale),a=P(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},m$={description:j(`Returns the content of a cell, specified by a string.`),args:[B(`reference (string)`,j(`The range of cells from which the values are returned.`)),B(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),s$)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Ba(j(`Reference should be defined.`));if(!I(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 Ba;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},h$={description:j(`Look up a value.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`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=L(t),i=L(n),a=r.length,o=r[0].length,s=o>=a,c=Oo(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?Ya(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},g$={description:j(`Position of item in range that matches value.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`range (any, range)`,j(`The one-dimensional array to be searched.`)),B(`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=P(n,this.locale),i=L(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=Oo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=ko(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=Oo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ya(e):s+1},isExported:!0},_$={description:j(`Row number of a specified cell.`),args:[B(`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=L(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 Ba(Za);let r=n.position.row;return t[0].length===1?r+1:vo(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},v$={description:j(`Number of rows in a specified array or range.`),args:[B(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=L(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},y$={description:j(`Vertical lookup.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),B(`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.`),c$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(P(n?.value,this.locale)),a=L(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=I(r.value)?Oo(a,e,`nextSmaller`,`asc`,a[0].length,o):ko(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ya(e):c},isExported:!0},b$={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},x$={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[B(`search_key (string,number,boolean)`,j(`The value to search for.`)),B(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),B(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),B(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),B(`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`)}]),B(`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(P(i.value,this.locale)),s=Math.trunc(P(a.value,this.locale)),c=L(t),l=L(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=b$[o],m=s===-1,h=s===2||s===-2?Oo(c,e,p,s===2?`asc`:`desc`,f,d):ko(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ya(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},S$={description:j(`Get the value from a pivot.`),args:[B(`pivot_id (number,string)`,j(`ID of the pivot.`)),B(`measure_name (string)`,j(`Name of the measure.`)),B(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),B(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=F(e),i=F(t),a=n$(r,this.getters);r$(a,i,this.getters),i$(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);a$(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)}},C$={description:j(`Get the header of a pivot.`),args:[B(`pivot_id (number,string)`,j(`ID of the pivot.`)),B(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),B(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=F(e),r=n$(n,this.getters);i$(t);let i=this.getters.getPivot(r);a$(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(F(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}}},w$={description:j(`Get a pivot table.`),args:[B(`pivot_id (string)`,j(`ID of the pivot.`)),B(`row_count (number, optional)`,j(`number of rows`)),B(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),B(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),B(`column_count (number, optional)`,j(`number of columns`)),B(`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=n$(F(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=iC(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.`));a$(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(x_(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(YS(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}},T$={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[B(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),B(`offset_rows (number)`,j(`The number of rows to offset by.`)),B(`offset_columns (number)`,j(`The number of columns to offset by.`)),B(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),B(`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 Ba(Za);let a=L(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 Ba(Za);let s=a[0].length,c=a.length;if(r){let e=P(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=P(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=P(t,this.locale),u=P(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 Ba(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 Ba:(d&&this.addDependencies?.(d,[g]),vo(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},E$={description:j(`Returns an element from a list of choices based on index.`),args:[B(`index (number)`,j(`Which choice to return.`)),B(`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(P(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},D$={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[B(`array (range)`,j(`The array from which to drop rows or columns`)),B(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),B(`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=P(t,this.locale),i=P(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},O$={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[B(`array (range)`,j(`The array from which to take rows or columns.`)),B(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),B(`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?P(t,this.locale):e[0].length,i=P(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},k$={description:j(`Returns a formula as a string.`),args:[B(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Ba(Za);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Va(j(`The cell does not contain a formula.`))},isExported:!0};var A$=l({ADD:()=>j$,CONCAT:()=>M$,DIVIDE:()=>N$,EQ:()=>L$,GT:()=>z$,GTE:()=>B$,LT:()=>V$,LTE:()=>H$,MINUS:()=>U$,MULTIPLY:()=>W$,NE:()=>G$,POW:()=>K$,SPILLED_RANGE:()=>q$,UMINUS:()=>J$,UNARY_PERCENT:()=>Y$,UPLUS:()=>X$});let j$={description:j(`Sum of two numbers.`),args:[B(`value1 (number)`,j(`The first addend.`)),B(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:P(e,this.locale)+P(t,this.locale),format:e?.format||t?.format}}},M$={description:j(`Concatenation of two values.`),args:[B(`value1 (string)`,j(`The value to which value2 will be appended.`)),B(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return F(e)+F(t)},isExported:!0},N$={description:j(`One number divided by another.`),args:[B(`dividend (number)`,j(`The number to be divided.`)),B(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=P(t,this.locale);return n===0?new Wa(j(`The divisor must be different from zero.`)):{value:P(e,this.locale)/n,format:e?.format||t?.format}}};function P$(e){return e===void 0||e.value===null}let F$={number:0,string:``,boolean:!1};function I$(e,t,n=2e-16){return Math.abs(e-t)<n}let L$={description:j(`Equal.`),args:[B(`value1 (string, number, boolean)`,j(`The first value.`)),B(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(Ja(e?.value))return e;if(Ja(t?.value))return t;let n=P$(e)?F$[typeof t?.value]:e?.value,r=P$(t)?F$[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:I$(n,r)}:{value:n===r}}};function R$(e,t,n){if(Ja(e?.value))return e;if(Ja(t?.value))return t;let r=P$(e)?F$[typeof t?.value]:e?.value,i=P$(t)?F$[typeof e?.value]:t?.value;typeof r!=`number`&&(r=F(r).toUpperCase()),typeof i!=`number`&&(i=F(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 z$={description:j(`Strictly greater than.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return R$(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!I$(e,t)&&e>t:e>t)}},B$={description:j(`Greater than or equal to.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return R$(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?I$(e,t)||e>t:e>=t)}},V$={description:j(`Less than.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=B$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},H$={description:j(`Less than or equal to.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=z$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},U$={description:j(`Difference of two numbers.`),args:[B(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),B(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:P(e,this.locale)-P(t,this.locale),format:e?.format||t?.format}}},W$={description:j(`Product of two numbers`),args:[B(`factor1 (number)`,j(`The first multiplicand.`)),B(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:P(e,this.locale)*P(t,this.locale),format:e?.format||t?.format}}},G$={description:j(`Not equal.`),args:[B(`value1 (string, number, boolean)`,j(`The first value.`)),B(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=L$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},K$={description:j(`A number raised to a power.`),args:[B(`base (number)`,j(`The number to raise to the exponent power.`)),B(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return jq.compute.bind(this)(e,t)}},q$={description:j(`Gets the spilled range of an array formula.`),args:[B(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Ba(Za);let t=L(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(Ja(n.value))return n;if(n.position===void 0)return new Ba(Za);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Ba;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),vo(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},J$={description:j(`A number with the sign reversed.`),args:[B(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-P(e,this.locale),format:e?.format}}},Y$={description:j(`Value interpreted as a percentage.`),args:[B(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return P(e,this.locale)/100}},X$={description:j(`A specified number, unchanged.`),args:[B(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Z$={transform:e=>e,inverseTransform:e=>e},Q$=1e-10,$$=.0254,e1=$$/72,t1=.3048,n1=.9144,r1=1609.34,i1=1852,a1=946073047258e4,o1={g:{...Z$,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:{...Z$,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(Q$),category:`distance`},Picapt:{...$(e1),category:`distance`},pica:{...$($$/6),category:`distance`},in:{...$($$),category:`distance`},ft:{...$(t1),category:`distance`},yd:{...$(n1),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(r1),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(i1),category:`distance`},ly:{...$(a1),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...Z$,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...Z$,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:{...Z$,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...Z$,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:{...Z$,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...Z$,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...Z$,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":{...Z$,category:`volume`,order:3},"ang^3":{...$(Q$**3),category:`volume`,order:3},"Picapt^3":{...$(e1**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$($$**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":{...$(t1**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(n1**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(r1**3),category:`volume`,order:3},"Nmi^3":{...$(i1**3),category:`volume`,order:3},"ly^3":{...$(a1**3),category:`volume`,order:3},"m^2":{...Z$,category:`area`,order:2},"ang^2":{...$(Q$**2),category:`area`,order:2},"Picapt^2":{...$(e1**2),category:`area`,order:2},"in^2":{...$($$**2),category:`area`,order:2},"ft^2":{...$(t1**2),category:`area`,order:2},"yd^2":{...$(n1**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":{...$(r1**2),category:`area`,order:2},"Nmi^2":{...$(i1**2),category:`area`,order:2},"ly^2":{...$(a1**2),category:`area`,order:2},bit:{...Z$,category:`information`},byte:{...$(8),category:`information`},"m/s":{...Z$,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`}},s1={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`},c1={"":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},l1={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`)},u1=Object.entries(o1).map(([e,t])=>({value:e,label:d1(t.category)}));function d1(e){return l1[e]??``}function f1(e){for(let[t,n]of Object.entries(c1)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=o1[r];if(!i&&s1[r]&&(i=o1[s1[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var p1=l({CONVERT:()=>m1});let m1={description:j(`Converts a numeric value to a different unit of measure.`),args:[B(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),B(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),u1),B(`end_unit (string)`,j(`The unit of measure into which to convert value`),u1)],compute:function(e,t,n){let r=P(e,this.locale),i=F(t),a=F(n),o=f1(i),s=f1(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')`,d1(o.category),d1(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 h1=l({CHAR:()=>y1,CLEAN:()=>b1,CONCATENATE:()=>x1,EXACT:()=>S1,FIND:()=>C1,FORMAT_LARGE_NUMBER:()=>w1,JOIN:()=>T1,LEFT:()=>E1,LEN:()=>D1,LOWER:()=>O1,MID:()=>k1,PROPER:()=>A1,REGEXEXTRACT:()=>M1,REGEXREPLACE:()=>N1,REGEXTEST:()=>j1,REPLACE:()=>P1,RIGHT:()=>F1,SEARCH:()=>I1,SPLIT:()=>L1,SUBSTITUTE:()=>R1,TEXT:()=>U1,TEXTAFTER:()=>G1,TEXTBEFORE:()=>K1,TEXTJOIN:()=>z1,TEXTSPLIT:()=>B1,TRIM:()=>V1,UPPER:()=>H1,VALUE:()=>W1});let g1=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,_1=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],v1=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],y1={description:j(`Gets character associated with number.`),args:[B(`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(P(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},b1={description:j(`Remove non-printable characters from a piece of text.`),args:[B(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=F(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},x1={description:j(`Appends strings to one another.`),args:[B(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ho(e,(e,t)=>e+F(t),``)},isExported:!0},S1={description:j(`Tests whether two strings are identical.`),args:[B(`string1 (string)`,j(`The first string to compare.`)),B(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return F(e)===F(t)},isExported:!0},C1={description:j(`First position of string found in text, case-sensitive.`),args:[B(`search_for (string)`,j(`The string to look for within text_to_search.`)),B(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),B(`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=F(e),i=F(t),a=P(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},w1={description:j(`Apply a large number format`),args:[B(`value (number)`,j(`The number.`)),B(`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:P(e,this.locale),format:Hs(e,t,this.locale)}}},T1={description:j(`Concatenates elements of arrays with delimiter.`),args:[B(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),B(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=F(e);return ho(t,(e,t)=>(e?e+n:``)+F(t),``)}},E1={description:j(`Substring from beginning of specified string.`),args:[B(`text (string)`,j(`The string from which the left portion will be returned.`)),B(`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?P(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):F(e).substring(0,n)},isExported:!0},D1={description:j(`Length of a string.`),args:[B(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return F(e).length},isExported:!0},O1={description:j(`Converts a specified string to lowercase.`),args:[B(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return F(e).toLowerCase()},isExported:!0},k1={description:j(`A segment of a string.`),args:[B(`text (string)`,j(`The string to extract a segment from.`)),B(`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.`)),B(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=F(e),i=P(t,this.locale),a=P(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},A1={description:j(`Capitalizes each word in a specified string.`),args:[B(`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 F(e).replace(g1,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},j1={description:j(`Checks whether a string matches the supplied regular expression.`),args:[B(`text (string)`,j(`The string to test.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`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=F(e),i=F(t),a=P(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},M1={description:j(`Extract text from a string based on the supplied regular expression.`),args:[B(`text (string)`,j(`The string on which you want to extract text.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`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`)}]),B(`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=F(e),a=F(t),o=P(n,this.locale),s=P(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},N1={description:j(`Replace text in a string based on the supplied regular expression.`),args:[B(`text (string)`,j(`The string in which you want to replace text.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`replacement (string)`,j(`The text to use as the replacement.`)),B(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),B(`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=F(e),o=F(t),s=F(n),c=P(r,this.locale),l=P(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},P1={description:j(`Replaces part of a text string with different text.`),args:[B(`text (string)`,j(`The text, a part of which will be replaced.`)),B(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),B(`length (number)`,j(`The number of characters in the text to be replaced.`)),B(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=P(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=F(e),o=P(n,this.locale),s=F(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},F1={description:j(`A substring from the end of a specified string.`),args:[B(`text (string)`,j(`The string from which the right portion will be returned.`)),B(`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?P(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=F(e),i=r.length;return r.substring(i-n,i)},isExported:!0},I1={description:j(`First position of string found in text, ignoring case.`),args:[B(`search_for (string)`,j(`The string to look for within text_to_search.`)),B(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),B(`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=F(e).toLowerCase(),i=F(t).toLowerCase(),a=P(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},L1={description:j(`Split text by specific character delimiter(s).`),args:[B(`text (string)`,j(`The text to divide.`)),B(`delimiter (string)`,j(`The character or characters to use to split text.`)),B(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),B(`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=F(e),a=St(F(t)),o=I(n),s=I(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!==``)),xo([l])},isExported:!1},R1={description:j(`Replaces existing text with new text in a string.`),args:[B(`text_to_search (string)`,j(`The text within which to search and replace.`)),B(`search_for (string)`,j(`The string to search for within text_to_search.`)),B(`replace_with (string)`,j(`The string that will replace search_for.`)),B(`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=P(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=F(e),o=F(t);if(o===``)return a;let s=F(n),c=new RegExp(St(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},z1={description:j(`Combines text from multiple strings and/or arrays.`),args:[B(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),B(`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)`)}]),B(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=F(e),i=I(t),a=0;return ho(n,(e,t)=>i&&F(t)===``?e:(a++?e+r:``)+F(t),``)},isExported:!0},B1={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[B(`text (string)`,j(`The text to split.`)),B(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),B(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),B(`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`)}]),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`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 Va){let o=F(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=L(t).flat().map(e=>St(F(e))),c=L(n).flat().map(e=>St(F(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=I(r),u=P(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 xo(d)},isExported:!0},V1={description:j(`Removes space characters.`),args:[B(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return un(F(e))},isExported:!0},H1={description:j(`Converts a specified string to uppercase.`),args:[B(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return F(e).toUpperCase()},isExported:!0},U1={description:j(`Converts a number to text according to a specified format.`),args:[B(`number (number)`,j(`The number, date or time to format.`)),B(`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 z(P(e,this.locale),{format:F(t),locale:this.locale})},isExported:!0},W1={description:j(`Converts a string to a numeric value.`),args:[B(`value (number)`,j(`the string to be converted`))],compute:function(e){return P(e,this.locale)},isExported:!0},G1={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[B(`text (string)`,j(`The source text.`)),B(`delimiter (string)`,j(`The substring after which text will be returned.`)),B(`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.`)),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),v1),B(`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 Va){let o=F(e),s=P(n,this.locale),c=P(r,this.locale),l=P(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=F(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=St(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},K1={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[B(`text (string)`,j(`The source text.`)),B(`delimiter (string)`,j(`The substring after which text will be returned.`)),B(`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.`)),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),v1),B(`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 Va){let o=F(e),s=P(n,this.locale),c=P(r,this.locale),l=P(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=F(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=St(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 q1=l({HYPERLINK:()=>J1});let J1={description:j(`Creates a hyperlink in a cell.`),args:[B(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),B(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=F(e).trim(),r=F(t)||n;return n===``?r:Ft(r,n)},isExported:!0},Y1=[{name:j(`Array`),functions:dK},{name:j(`Database`),functions:gY},{name:j(`Date`),functions:MX},{name:j(`Filter`),functions:gZ},{name:j(`Financial`),functions:SZ},{name:j(`Info`),functions:jQ},{name:j(`Lookup`),functions:o$},{name:j(`Logical`),functions:WQ},{name:j(`Math`),functions:VK},{name:j(`Operator`),functions:A$},{name:j(`Statistical`),functions:rJ},{name:j(`Text`),functions:h1},{name:j(`Engineering`),functions:mZ},{name:j(`Web`),functions:q1},{name:j(`Parser`),functions:p1}];for(let e of Y1){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),bc.add(n,{isExported:!1,...r})}}let X1={},Z1={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},Q1={autoCompleteProviders:Mk,autofillModifiersRegistry:wz,autofillRulesRegistry:Tz,cellMenuRegistry:lI,colMenuRegistry:wI,errorTypes:La,functionRegistry:bc,featurePluginRegistry:wV,iconsOnCellRegistry:iz,statefulUIPluginRegistry:TV,coreViewsPluginRegistry:EV,corePluginRegistry:CV,rowMenuRegistry:jI,sidePanelRegistry:kP,figureRegistry:o_,chartSidePanelComponentRegistry:iA,chartDataSourceSidePanelComponentRegistry:eE,chartComponentRegistry:_g,chartTypeRegistry:ib,chartSubtypeRegistry:ng,chartDataSourceRegistry:rb,topbarMenuRegistry:QV,topbarComponentRegistry:_H,topBarToolBarRegistry:vU,clickableCellRegistry:DV,otRegistry:Yz,inverseCommandRegistry:AV,urlRegistry:nd,cellPopoverRegistry:zC,numberFormatMenuRegistry:JV,repeatLocalCommandTransformRegistry:JB,repeatCommandTransformRegistry:qB,clipboardHandlersRegistries:SL,pivotRegistry:xN,pivotTimeAdapterRegistry:mS,pivotSidePanelRegistry:IN,pivotNormalizationValueRegistry:KS,supportedPivotPositionalFormulaRegistry:tR,pivotToFunctionValueRegistry:qS,migrationStepRegistry:dC,chartJsExtensionRegistry:Wr,onIterationEndEvaluationRegistry:JR,specificRangeTransformRegistry:Xz},$1={arg:B,isEvaluationError:Ja,toBoolean:I,toJsDate:co,toNumber:P,toString:F,toNormalizedPivotValue:HS,toFunctionPivotValue:WS,toXC:E,toZone:Wn,toUnboundedZone:Un,toCartesian:Mn,numberToLetters:Cn,lettersToNumber:wn,UuidGenerator:G,formatValue:z,createCurrencyFormat:Fs,ColorGenerator:Gf,computeTextWidth:Nd,createEmptyWorkbookData:jC,createEmptySheet:AC,createEmptyExcelSheet:MC,doesCellContainFunction:xn,rgbaToHex:_f,colorToRGBA:vf,positionToZone:D,isDefined:w,isMatrix:gt,lazy:Kt,genericRepeat:gH,createAction:xe,createActions:ve,transformRangeData:Nr,deepEquals:T,overlap:ir,union:er,isInside:or,deepCopy:x,expandZoneOnInsertion:Xn,reduceZoneOnDeletion:$n,unquote:Tt,getMaxObjectId:PS,getFirstPivotFunction:EN,getNumberOfPivotFunctions:ON,parseDimension:LS,isDateOrDatetimeField:RS,makeFieldProposal:kN,periodYearToComparable:pS,insertTokenAfterArgSeparator:jN,insertTokenAfterLeftParenthesis:MN,mergeContiguousZones:Ar,getPivotHighlights:vM,pivotTimeAdapter:hS,UNDO_REDO_PIVOT_COMMANDS:xz,createPivotFormula:VS,areDomainArgsFieldsValid:BS,splitReference:Nc,sanitizeSheetName:Dt,getUniqueText:vn,isNumber:Ta,isDateTime:qi,createCustomFields:$S,schemeToColorScale:cC,isDateTimeFormat:Os,jsDateToNumber:sa,numberToJsDate:aa,DateTime:Ni,parseFormat:Qo,isFormula:yn,domainToColRowDomain:KM,collapseHierarchicalDisplayName:aC,getCanonicalSymbolName:Et,fuzzyLookup:jk,replaceSymbolInFormula:fu},e0={isMarkdownLink:Nt,parseMarkdownLink:It,markdownLink:Ft,openLink:sd,urlRepresentation:od},t0={Checkbox:tE,Section:Z,Select:t_,RoundColorPicker:OE,ChartDataSeries:pE,ChartErrorSection:_E,ChartLabelRange:mE,ChartRangeDataSourceComponent:UO,ChartTitle:TE,ChartPanel:cA,ChartFigure:i_,ChartJsComponent:Qm,ClickableCellSortIcon:nR,ZoomableChartJsComponent:lg,Grid:eR,GridOverlay:OL,ScorecardChart:yh,GaugeChartComponent:hg,LineConfigPanel:Uk,BarConfigPanel:yE,PieChartDesignPanel:Kk,GenericChartConfigPanel:vE,ChartWithAxisDesignPanel:FE,GenericZoomableChartDesignPanel:IE,LineChartDesignPanel:Wk,GaugeChartConfigPanel:sk,GaugeChartDesignPanel:Rk,ScorecardChartConfigPanel:Yk,ScorecardChartDesignPanel:Xk,GeoChartDesignPanel:Vk,RadarChartDesignPanel:qk,WaterfallChartDesignPanel:rA,ComboChartDesignPanel:ik,FunnelChartDesignPanel:ok,SunburstChartDesignPanel:Zk,TreeMapChartDesignPanel:nA,ChartTypePicker:oA,FigureComponent:s_,MenuPopover:e_,Popover:Xg,SelectionInput:fE,StandaloneComposer:Lk,ValidationMessages:gE,AddDimensionButton:PM,PivotDimensionGranularity:IM,PivotDimensionOrder:LM,PivotDimension:jM,PivotLayoutConfigurator:VM,PivotHTMLRenderer:iR,PivotDeferUpdate:bM,PivotTitleSection:HM,CogWheelMenu:QT,TextInput:GT,SidePanelCollapsible:xE,RadioSelection:DE,GeoChartRegionSelectSection:zk,ChartDashboardMenu:n_,FullScreenFigure:rR,NumberInput:SE,TopBar:yU,Composer:vk},n0={useDragAndDropListItems:LT,useHighlights:dA,useHighlightsOnHover:uA},r0={Component:k,useExternalListener:mi,EnvPlugin:gi,App:xi},i0={useStoreProvider:Ti,DependencyContainer:Ci,CellPopoverStore:BC,ComposerFocusStore:Ur,CellComposerStore:cL,FindAndReplaceStore:QA,HighlightStore:lE,DelayedHoveredCellStore:c_,HoveredTableStore:TL,ModelStore:Ir,NotificationStore:Nk,RendererStore:Br,SelectionInputStore:dE,SpreadsheetStore:Vr,useStore:A,useLocalStore:Ei,SidePanelStore:jP,PivotSidePanelStore:PN,PivotMeasureDisplayPanelStore:gM,ClientFocusStore:NI,GridRenderer:LL};function a0(e,t){return bc.add(e,t),{addFunction:(e,t)=>a0(e,t)}}let o0={DEFAULT_LOCALE:R,HIGHLIGHT_COLOR:De,PIVOT_STATIC_TABLE_CONFIG:ct,PIVOT_INSERT_TABLE_STYLE_ID:lt,ChartTerms:f_,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:sC,DARK_MODE_FILTER_STRING:kf},s0={...HO,...aR};e.AbstractCellClipboardHandler=LB,e.AbstractChart=$m,e.AbstractFigureClipboardHandler=AG,e.BadExpressionError=Ra,e.CHART_TYPES=sC,e.CellErrorType=M,e.CellValueType=Pu,e.CircularDependencyError=za,e.ClientDisconnectedError=jB,e.ClipboardMIMEType=VC,e.CommandResult=ed,e.CompiledFormula=Du,e.CorePlugin=U_,e.CoreViewPlugin=PP,e.DEFAULT_LOCALE=R,e.DEFAULT_LOCALES=Lo,e.DEFAULT_LOCALE_DIGIT_GROUPING=`[3,0]`,e.DIRECTION=vt,e.DispatchResult=Qu,e.DivisionByZeroError=Wa,e.EvaluationError=N,e.InvalidReferenceError=Ba,e.LocalTransportService=vH,e.Model=DG,e.NEXT_VALUE=u_,e.NotAvailableError=Va,e.NumberTooLargeError=Ga,e.OrderedLayers=Rr,e.PREVIOUS_VALUE=l_,e.PivotRuntimeDefinition=xM,e.Registry=O,e.Revision=AB,e.SPREADSHEET_DIMENSIONS=Z1,e.SplillBlockedError=Ua,e.Spreadsheet=SU,e.SpreadsheetPivotTable=lN,e.UIPlugin=Iz,e.UnknownFunctionError=Ha,e.__info__=X1,e.addFunction=a0,e.addRenderingLayer=zr,e.astToFormula=iL,e.availableConditionalFormatOperators=LA,e.availableDataValidationOperators=YA,e.availableFiltersOperators=CM,e.borderPositions=_t,e.borderStyles=ht,e.canExecuteInReadonly=Zu,e.categories=Y1,e.chartHelpers=s0,e.compatibility=r0,e.components=t0,e.composerFocusTypes=yt,e.constants=o0,e.convertAstNodes=Ol,e.coreTypes=Yu,e.createAutocompleteArgumentsProvider=qG,e.errorTypes=La,e.filterDateCriterionOperators=EM,e.filterNumberCriterionOperators=TM,e.filterTextCriterionOperators=wM,e.findCellInNewZone=_r,e.functionCache=Tu,e.getCaretDownSvg=sy,e.getCaretUpSvg=cy,e.helpers=$1,e.hooks=n0,e.invalidSubtotalFormulasCommands=Ku,e.invalidateBordersCommands=Gu,e.invalidateCFEvaluationCommands=Wu,e.invalidateChartEvaluationCommands=Hu,e.invalidateDependenciesCommands=Uu,e.invalidateEvaluationCommands=Vu,e.isCoreCommand=Xu,e.isHeadersDependant=Iu,e.isMatrix=gt,e.isPositionDependent=zu,e.isRangeDependant=Ru,e.isSheetDependent=Fu,e.isTargetDependent=Lu,e.isZoneDependent=Bu,e.iterateAstNodes=kl,e.links=e0,e.load=gC,e.lockedSheetAllowedCommands=Ju,e.parse=El,e.parseTokens=Dl,e.readonlyAllowedCommands=qu,e.registries=Q1,e.schemeToColorScale=cC,e.setDefaultSheetViewSize=ot,e.setTranslationMethod=Pa,e.stores=i0,e.tokenColors=mt,e.tokenize=Gc,X1.version=`19.4.0-alpha.12`,X1.date=`2026-06-06T06:24:48.209Z`,X1.hash=`a71f829`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
963
+ `),`_rels/.rels`)}function TG(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=vn(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(`'?${St(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function EG(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>cr(Wn(e.range)).numberOfRows>1);return e}var DG=class e extends Si{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=!1){let i=performance.now();console.debug(`##### Model creation #####`),super(),Fa(),n=wC(e,n);let a=gC(e,r);this.state=new zU,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(a.revisionId),this.coreGetters={},this.range=new FU(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.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 LU(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 CV.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of EV.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of TV.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of wV.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()-i,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession({shouldSnapshot:e}={shouldSnapshot:!0}){let t=e&&!this.getters.isReadonly()?Kt(()=>this.exportData()):void 0;await this.session.leave(t)}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 MB(MU({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 CU(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:G.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new vH,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 wU(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(Lo));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,colorScheme:this.config.colorScheme}}checkDispatchAllowed(e){let t=Xu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Qu(e.flat()):Qu.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(OG(e,t));dispatch=(e,t)=>{let n=OG(e,t),r=this.status;if(this.getters.isReadonly()&&!Zu(n))return new Qu(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Qu(`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();Xu(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(Xu(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(Xu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Qu.Success};dispatchFromCorePlugin=(e,t)=>{let n=OG(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Qu.Success};dispatchToHandlers(e,t){let n=Xu(t);for(let r of e)!n&&r instanceof U_||r.beforeHandle(t);for(let r of e)!n&&r instanceof U_||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 vH};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=jC();for(let n of this.handlers)n instanceof U_&&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=NC();for(let t of this.handlers)t instanceof H_&&await t.exportForExcel(e);return e=x(e),gG(e)}};function OG(e,t={}){let n=x(t);return n.type=e,n}var kG=class extends LB{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=Nn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},AG=class extends IB{copy(e){}getCopyRect(e){return Wg(...e.figureIds.map(t=>this.getters.getFigure(e.sheetId,t)).filter(w).map(t=>this.getters.getFigureUI(e.sheetId,t)))}},jG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`carousel`)continue;let a={...e},o=this.getters.getCarousel(i),{x:s,y:c}=this.getters.getFigureUI(t,e),l={};for(let e of o.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);l[e.chartId]=t}n.push({figureId:i,copiedFigure:a,copiedCarousel:o,copiedCharts:l,copiedSheetId:t,offset:{x:s-r.x,y:c-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,{col:l,row:u,offset:d}=Kh(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CAROUSEL`,{figureId:o,sheetId:i,definition:{items:[]},col:l,row:u,offset:d,size:{height:c,width:s}});let f=x(a.copiedCarousel.items);for(let e of f){if(e.type!==`chart`)continue;let t=a.copiedCharts[e.chartId],n=G.smallUuid(),r=WO.fromDefinition(this.getters,i,t.copyInSheetId(i)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:o,chartId:n,sheetId:i,definition:r}),e.chartId=n}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:i,figureId:o,definition:{...a.copiedCarousel,items:f}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedSheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},MG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`chart`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=this.getters.getChartFromFigureId(i);if(!c)throw Error(`No chart for the given id: ${i}`);n.push({figureId:i,copiedFigure:a,copiedChart:c,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,l=a.copiedChart,u=WO.fromDefinition(this.getters,i,l.copyInSheetId(i)).getDefinition();u=WO.fromStrDefinition(this.getters,i,u).getDefinition();let{col:d,row:f,offset:p}=Kh(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CHART`,{figureId:o,chartId:G.smallUuid(),sheetId:i,definition:u,col:d,row:f,offset:p,size:{height:c,width:s}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedChart.sheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},NG=class extends LB{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:G.smallUuid(),ranges:[]}}},PG=class extends LB{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?G.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=Nn([...Nn(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})}}},FG=class extends AG{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`image`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=x(this.getters.getImage(i));n.push({figureId:i,copiedFigure:a,copiedImage:c,sheetId:t,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{sheetId:e,zones:[],figureIds:i}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e;for(let i of t.figures){let a=e.figureIds[i.figureId],o=this.getters.getActiveSheetId(),{width:s,height:c}=i.copiedFigure,l=x(i.copiedImage),{col:u,row:d,offset:f}=Kh(this.getters,o,{col:r[0].left,row:r[0].top},{...i.copiedFigure,offset:i.offset});this.dispatch(`CREATE_IMAGE`,{figureId:a,sheetId:o,col:u,row:d,offset:f,size:{height:c,width:s},definition:l}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:i.sheetId,figureId:i.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:a,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},IG=class extends LB{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}]})}},LG=class extends LB{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})}}},RG=class extends LB{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Cr(GC(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},zG=class extends LB{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=>sr(f,e))){s.add(u.id);let{numberOfRows:e}=cr(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=>sr(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=Qt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Qt(n)},border:{...r,...Qt(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=cr(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}))}};SL.figureHandlers.add(`chart`,MG).add(`image`,FG).add(`carousel`,jG),SL.cellHandlers.add(`dataValidation`,PG).add(`cell`,RB).add(`sheet`,RG).add(`merge`,IG).add(`border`,kG).add(`table`,zG).add(`conditionalFormat`,NG).add(`references`,LG);var BG=class extends k{static maxSize={maxHeight:80};static template=`o-spreadsheet-ErrorToolTip`;props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){let e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return``;let e=this.evaluationError?.errorOriginPosition;if(!e||T(e,this.props.cellPosition))return``;let t=e.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(t,D(e)),this.env.model.getters.getActiveSheetId())}selectCell(){let e=this.evaluationError?.errorOriginPosition;if(!e)return;let t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}get isSpillErrorBecauseOfMissingHeaders(){let e=this.evaluationError;return e?.value===M.SpilledBlocked&&!e.errorOriginPosition&&!this.env.model.getters.getSpreadZone(this.props.cellPosition,{ignoreSpillError:!0})}getMissingHeadersForSpread(){if(!this.isSpillErrorBecauseOfMissingHeaders)return;let e=this.env.model.getters.getCell(this.props.cellPosition);if(!e||!e.isFormula)return;let t=e.compiledFormula.toFormulaString(this.env.model.getters);return Sn(this.env.model.getters,this.props.cellPosition,t)}addMissingHeaders({missingCols:e,missingRows:t}){let n=this.props.cellPosition.sheetId;e>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`COL`,base:this.env.model.getters.getNumberCols(n)-1,position:`after`,quantity:e+20}),t>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`ROW`,base:this.env.model.getters.getNumberRows(n)-1,position:`after`,quantity:t+50})}getAddMissingHeadersButtonText(e){return e.missingCols>0&&e.missingRows>0?j(`Add missing columns and rows`):e.missingCols>0?j(`Add missing columns`):j(`Add missing rows`)}};let VG={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return n.type===`error`&&n.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:BG,cellCorner:`top-right`}:{isOpen:!1}}};var HG=class extends k{static template=`o-spreadsheet-FilterMenu`;static components={FilterMenuValueList:kM,SidePanelCollapsible:xE,FilterMenuCriterion:DM};props=(0,t.props)({filterPosition:W.Position(),"onClosed?":W.function([])});state;criterionCategory=`text`;updatedCriterionValue;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition),this.state.values=this.getFilterHiddenValues(e.filterPosition))}),this.state=(0,t.proxy)({values:this.getFilterHiddenValues(this.props.filterPosition)}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;let e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&e?.type!==`dynamic`}get table(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterValue({sheetId:e,...t})?.filterType}getCriterionCategory(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n||!n.filteredRange)return`text`;let r={text:0,number:0,date:0},i=n.filteredRange.zone;for(let n=i.top;n<=i.bottom&&!(n>100);n++){let i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:n,col:e.col});i.type===`text`||i.type===`boolean`?r.text++:i.type===`number`&&(i.format&&Os(i.format)?r.date++:r.number++)}let a=Math.max(r.text,r.number,r.date);return Object.keys(r).find(e=>r[e]===a)||`text`}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:`values`,hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue){this.props.onClosed?.();return}let e=this.props.filterPosition;this.env.model.dispatch(`UPDATE_FILTER`,{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return this.criterionCategory===`date`?EM:this.criterionCategory===`number`?TM:wM}cancel(){this.props.onClosed?.()}sortFilterZone(e){let t=this.props.filterPosition,n=this.table?.range.zone;if(!t||!n||n.top===n.bottom)return;let r=this.env.model.getters.getActiveSheetId(),i={...n,top:n.top+1},a={col:t.col,row:i.top};dI(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n?.filteredRange)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=dr(n.filteredRange.zone);r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.row)));let a=i.map(e=>this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(Wd)),c=new Set,l=[],u=e=>{let t=Wd(e);c.has(t)||(l.push({string:e||``,checked:r?.filterType===`criterion`?!1:!s.has(t),normalizedValue:t}),c.add(t))};return a.forEach(u),o.forEach(u),l.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:`base`}))}getFilterCriterionValue(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return n?.filterType===`criterion`?x(n):{filterType:`criterion`,type:`none`,values:[]}}};let UG={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:HG,cellCorner:`bottom-left`})};var WG=class extends k{static template=`o-spreadsheet-LinkDisplay`;props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});cellPopovers;setup(){this.cellPopovers=A(BC)}get cell(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;let{col:e,row:t}=this.props.cellPosition;throw Error(`LinkDisplay Component can only be used with link cells. ${E(e,t)} is not a link.`)}getUrlRepresentation(e){return od(e,this.env.model.getters)}openLink(e){sd(this.link,this.env,ue(e))}edit(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},`LinkEditor`)}unlink(){let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.props.cellPosition,r=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:n}),i=r?.textColor===`#017E84`?void 0:r?.textColor;this.env.model.dispatch(`UPDATE_CELL`,{col:t,row:n,sheetId:e,content:this.link.label,style:{...r,textColor:i,underline:void 0}})}};let GG={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:WG,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var KG=class extends k{static template=`o-spreadsheet-LinkEditor`;static components={MenuPopover:e_};props=(0,t.props)({cellPosition:W.CellPosition(),"onClosed?":W.function([])});static size={maxHeight:500};urlInput=(0,t.signal)(null);suggestionListRef=(0,t.signal)(null);urlInputContainer=(0,t.signal)(null);state=(0,t.proxy)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput()?.focus())}computeLinks(){this.state.selectedIndex=null,this.state.linksByCategory=this.linkProposalByCategory,this.state.linksList=Object.values(this.state.linksByCategory).flat()}get linkProposalByCategory(){let e={},t=-1,n=this.state.url;for(let r of nd.getKeys()){let i=nd.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?jk(n,a,e=>i.urlRepresentation(e.url,this.env.model.getters)):a;o.length!==0&&(e[i.title]=o.map(e=>{t++;let n=i.urlRepresentation(e.url,this.env.model.getters),r=t;return{text:n,icon:e.icon,index:r,onSelect:()=>{this.state.url=e.url,this.state.label=e.label,this.state.isUrlEditable=e.isUrlEditable,this.state.selectedIndex=r,this.urlInputContainer()?.focus()}}}))}return e}get defaultState(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t});return r.link?{url:r.link.url,label:r.formattedValue,isUrlEditable:r.link.isUrlEditable,selectedIndex:null,linksByCategory:{},linksList:[]}:{label:r.formattedValue,url:``,isUrlEditable:!0,selectedIndex:null,linksByCategory:{},linksList:[]}}getUrlRepresentation(e){return od(e,this.env.model.getters)}removeLink(){this.state.url=``,this.state.isUrlEditable=!0,this.computeLinks()}save(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getLocale(),r=this.state.label?C_(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Ft(r,this.state.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case`Enter`:this.state.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case`Escape`:this.cancel(),e.stopPropagation();break}}onInputKeyDown(e){switch(e.key){case`Enter`:if(this.state.selectedIndex!==null){let t=this.state.linksList[this.state.selectedIndex];if(t){let n=this.state.url;t.onSelect(),this.state.url!==n&&(e.stopPropagation(),e.preventDefault())}}break;case`ArrowDown`:this.state.selectedIndex=this.state.selectedIndex===null||this.state.selectedIndex===this.state.linksList.length-1?0:(this.state.selectedIndex+1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault();break;case`ArrowUp`:this.state.selectedIndex!==null&&(this.state.selectedIndex=this.state.selectedIndex===0?this.state.linksList.length-1:(this.state.selectedIndex-1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault());break}}showSelectedProposal(){this.suggestionListRef()?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};zC.add(`ErrorToolTip`,VG).add(`LinkCell`,GG).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:KG,cellCorner:`bottom-left`})}).add(`FilterMenu`,UG),Mk.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(yn(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:Nf(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t.text),this.composer.stopEdition()}}),Mk.add(`functions_and_named_ranges`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;if(!yn(this.composer.currentContent))return[];let n=Object.entries(bc.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({type:`function`,text:e,icon:`o-spreadsheet-Icon.FX_SVG`,description:n,htmlContent:NM(t,e,Me,`o-semi-bold`)}));return n.push(...this.getters.getNamedRanges().map(e=>({type:`named_range`,text:e.name,description:this.getters.getRangeString(e.range),icon:`o-spreadsheet-Icon.NAMED_RANGE`,htmlContent:NM(t,e.name,Me,`o-semi-bold`)}))),n.sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)),n},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens,a=t.text;if(t.type===`function`){a+=`(`;let t=i.map(e=>e.start).indexOf(e.start);t+1<i.length&&i[t+1]?.type===`LEFT_PAREN`&&r++}this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(a)}});function qG(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||Mk.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:JG,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?mt.STRING:mt.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function JG(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}bc.getAll().forEach(e=>qG(e.name,e.args)),Mk.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:mt.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(w)},selectProposal:JG}),Mk.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:j(`Count`),htmlContent:[{value:e,color:mt.STRING}],fuzzySearchKey:j(`Count`)+e}}return AN(e)}).filter(w):[]},selectProposal:JG}),Mk.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!YG(e)&&!XG(e))return;let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(w),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=tR.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(w);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?kN(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:j(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:mt.STRING}],fuzzySearchKey:t.string+n}})).filter(w)},selectProposal:JG});function YG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function XG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}Mk.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!ZG(e)&&!QG(e))return;let n=NN(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(fs).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:mt.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:j(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`day_of_month`?C(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`iso_week_number`?C(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`day_of_week`?C(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`hour_number`?C(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`minute_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):s.granularity===`second_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:mt.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?mt.STRING:mt.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:JG});function ZG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function QG(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}Mk.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Et(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text+`!`)}});function $G(e){return e.yRanges.length&&!Dc.test(e.yRanges[0])?`InvalidYRange`:e.xRange&&!Dc.test(e.xRange)?`InvalidXRange`:e.labelRange&&!Dc.test(e.labelRange)?`InvalidLabelRange`:e.sizeRange&&!Dc.test(e.sizeRange)?`InvalidBubbleSizeRange`:`Success`}let eK={sequence:40,allowedDefinitionKeys:[...$m.commonKeys,`yRanges`,`xRange`,`labelRange`,`sizeRange`,`dataSetsHaveTitle`,`verticalAxisPosition`,`labelsAsText`,`bubbleColor`,`legendPosition`,`axesDesign`,`showValues`],fromStrDefinition(e,t,n){let r=e.yRanges.map(e=>Bl(n,t,e)).filter(w),i=Bl(n,t,e.xRange),a=Bl(n,t,e.labelRange),o=Bl(n,t,e.sizeRange);return{...e,yRanges:r,xRange:i,labelRange:a,sizeRange:o}},toStrDefinition(e,t,n){return{...e,yRanges:e.yRanges.map(e=>n.getRangeString(e,t)),xRange:e.xRange?n.getRangeString(e.xRange,t):void 0,labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,sizeRange:e.sizeRange?n.getRangeString(e.sizeRange,t):void 0}},validateDefinition(e,t){return e.checkValidations(t,$G)},transformDefinition(e,t,{adaptRangeString:n}){let r=e=>{if(!e)return;let{changeType:r,range:i}=n(t,e);return r===`REMOVE`?void 0:i};return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),sizeRange:r(e.sizeRange),labelRange:r(e.labelRange)}},getDefinitionFromContextCreation(e,t){let n=e.dataSource?.type===`range`;return{background:e.background,yRanges:n?e.dataSource.dataSets?.map(e=>e.dataRange)??[]:[],verticalAxisPosition:e.dataSetStyles?.[0]?.verticalAxisPosition,dataSetsHaveTitle:n?e.dataSource.dataSetsHaveTitle??!1:!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bubble`,labelRange:e.bubbleLabelRange||void 0,labelsAsText:e.labelsAsText??!1,xRange:e.auxiliaryRange||void 0,sizeRange:e.bubbleSizeRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize,bubbleColor:e.bubbleColorMode||{color:`multiple`}}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.yRanges.map((e,t)=>({dataSetId:`${t}`,dataRange:e}))},bubbleLabelRange:e.labelRange,auxiliaryRange:e.xRange,bubbleSizeRange:e.sizeRange,bubbleColorMode:e.bubbleColor}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=e.yRanges.map(e=>gp(e,t)).filter(w),r=gp(e.xRange,t),i=gp(e.labelRange,t),a=gp(e.sizeRange,t);return{...e,yRanges:n,xRange:r,labelRange:i,sizeRange:a}},duplicateInDuplicatedSheet(e,t,n){let r=e=>hp(t,n,e);return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),labelRange:r(e.labelRange),sizeRange:r(e.sizeRange)}},copyInSheetId:e=>e,getRuntime(e,t){let n=iD(t,e);return{chartJsConfig:{type:`line`,data:{datasets:Cm(t,n),labels:n.labels},options:{...Lh,layout:kD(t,n),scales:im(t,n),plugins:{title:lO(t,e),legend:KD(t,n),tooltip:gO(t,n),chartShowValuesPlugin:rO(t,n),background:{color:t.background}}}}}}};function tK(e){return!$O.includes(e.horizontalGroupBy)||!$O.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let nK={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,tK)},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=XE(t,n(),e),{labels:i,datasets:a}=ym(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Lh,indexAxis:`x`,layout:AD(t,r),scales:Qp(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:mO(t,r),chartShowValuesPlugin:iO(t,r),chartColorScalePlugin:$p(t,r),background:{color:r.background}}}}}}},rK={sequence:15,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r,verticalAxis:Dp(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=qE(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:Em(t,a)},options:{...Lh,layout:kD(t,a),scales:Zp(t,a),plugins:{title:lO(t,e),legend:qD(t,a),tooltip:pO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},iK={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.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=nD(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:km(t,a)},options:{...Lh,indexAxis:`y`,layout:kD(t,a),scales:lm(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:SO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}}}}},aK={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...$m.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=tD(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Om(t,a)},options:{...Lh,layout:kD(t,a),scales:cm(t,a),plugins:{title:lO(t,e),tooltip:xO(t,a),legend:{display:!1},background:{color:a.background}},...i}}}}},oK={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...$m.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 i=ZE(t,JO(e,t.dataSource),e),{dataSetsValues:a}=i,o=Math.max(...a.map(e=>Math.max(...e.data.map(e=>V(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:BE(i.background||`#FFFFFF`),fontColor:BE(xp(i.background)),dataSets:n,labelRange:r,verticalAxis:Dp(t),maxValue:o}},getRuntime(e,t,{extractData:n},r,i){let a=ZE(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:_m(t,a)},options:{...Lh,indexAxis:`y`,layout:kD(t,a),scales:om(t,a),plugins:{title:lO(t,e),legend:HD(t,a),tooltip:yO(t,a),chartShowValuesPlugin:oO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sK={sequence:80,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=eD(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Dm(t,a)},options:{...Lh,layout:kD(t,a),scales:sm(t,a),plugins:{title:lO(t,e),legend:YD(t,a),tooltip:bO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cK={sequence:60,allowedDefinitionKeys:[...$m.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:BE(t.background||`#FFFFFF`),fontColor:BE(xp(t.background)),dataSets:n,labelRange:r,verticalAxis:Dp(t)}},getRuntime(e,t,{extractData:n},r,i){let a=QE(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:Sm(t,a)},options:{...Lh,layout:kD(t,a),scales:rm(t,a),plugins:{title:lO(t,e),legend:GD(t,a),tooltip:hO(t,a),chartShowValuesPlugin:rO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},lK={sequence:30,allowedDefinitionKeys:[...$m.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=rD(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:jm(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...Lh,layout:kD(t,a),plugins:{title:lO(t,e),legend:XD(t,a),tooltip:CO(t,a),sunburstLabelsPlugin:aO(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:a.background}},...i}}}}},uK={sequence:100,allowedDefinitionKeys:[...$m.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=rD(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:Im(t,a)},options:{...Lh,layout:kD(t,a),plugins:{title:lO(t,e),legend:{display:!1},tooltip:wO(t,a),background:{color:a.background}},...i}}}}};ib.add(`bar`,OO),ib.add(`combo`,rK),ib.add(`line`,zO),ib.add(`pie`,BO),ib.add(`scorecard`,lh),ib.add(`gauge`,PO),ib.add(`scatter`,cK),ib.add(`waterfall`,VO),ib.add(`pyramid`,oK),ib.add(`radar`,sK),ib.add(`geo`,aK),ib.add(`funnel`,iK),ib.add(`sunburst`,lK),ib.add(`treemap`,uK),ib.add(`calendar`,nK),ib.add(`bubble`,eK),ng.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(`bubble`,{displayName:j(`Bubble`),chartType:`bubble`,chartSubtype:`bubble`,category:`misc`,preview:`o-spreadsheet-ChartPreview.BUBBLE_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`}),iz.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=hf(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:my(n,r,!1),hoverSvg:my(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(BC),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});var dK=l({ARRAYTOTEXT:()=>BK,ARRAY_CONSTRAIN:()=>mK,ARRAY_LITERAL:()=>hK,ARRAY_ROW:()=>gK,CHOOSECOLS:()=>_K,CHOOSEROWS:()=>vK,EXPAND:()=>yK,FLATTEN:()=>bK,FREQUENCY:()=>xK,HSTACK:()=>SK,MDETERM:()=>CK,MINVERSE:()=>wK,MMULT:()=>TK,SUMPRODUCT:()=>EK,SUMX2MY2:()=>OK,SUMX2PY2:()=>kK,SUMXMY2:()=>AK,TOCOL:()=>NK,TOROW:()=>PK,TRANSPOSE:()=>FK,VSTACK:()=>IK,WRAPCOLS:()=>LK,WRAPROWS:()=>RK});function fK(e,t){let n=e.map(L),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 pK(e,t){let n=e.map(L),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=vo(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 mK={description:j(`Returns a result array constrained to a specific width and height.`),args:[B(`input_range (any, range<any>)`,j(`The range to constrain.`)),B(`rows (number)`,j(`The number of rows in the constrained array.`)),B(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=L(e),i=ro(t?.value,this.locale),a=ro(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 vo(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},hK={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return pK(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},gK={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return fK(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},_K={description:j(`Creates a new array from the selected columns in the existing range.`),args:[B(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),B(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=L(e),r=No(t,e=>ro(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},vK={description:j(`Creates a new array from the selected rows in the existing range.`),args:[B(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),B(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=L(e),r=No(t,e=>ro(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?vo(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},yK={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[B(`array (any, range<any>)`,j(`The array to expand.`)),B(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),B(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),B(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=L(e),a=ro(t?.value,this.locale),o=n===void 0?i.length:ro(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())):vo(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},bK={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[No(e,e=>e===void 0?{value:``}:e)]},isExported:!1},xK={description:j(`Calculates the frequency distribution of a range.`),args:[B(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),B(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=No([e],e=>e.value).filter(e=>typeof e==`number`),r=No([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},SK={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return fK(e)},isExported:!0},CK={description:j(`Returns the matrix determinant of a square matrix.`),args:[B(`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=to(e,`square_matrix`);return Hx(t)?Gx(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},wK={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[B(`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=to(e,`square_matrix`);if(!Hx(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=Gx(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},TK={description:j(`Calculates the matrix product of two matrices.`),args:[B(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),B(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=to(e,`matrix1`),r=to(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?qx(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},EK={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[B(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!Vx(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(L),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*=P(n[e][r],this.locale);n+=i}return n},isExported:!0};function DK(e,t,n){if(!Vx(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=L(e),i=L(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 OK={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>e**2-t**2)},isExported:!0},kK={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>e**2+t**2)},isExported:!0},AK={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[B(`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.`)),B(`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 DK(e,t,(e,t)=>(e-t)**2)},isExported:!0},jK=[B(`array (any, range<any>)`,j(`The array which will be transformed.`)),B(`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`)}]),B(`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 MK(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!Ja(e.value);if(t===3)return e=>e.value!==null&&!Ja(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let NK={description:j(`Transforms a range of cells into a single column.`),args:jK,compute:function(e,t={value:0},n={value:!1}){let r=L(e),i=P(t.value,this.locale),a=(I(n.value)?r:xo(r)).flat().filter(MK(i));return a.length===0?new Va(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},PK={description:j(`Transforms a range of cells into a single row.`),args:jK,compute:function(e,t={value:0},n={value:!1}){let r=L(e),i=P(t.value,this.locale),a=(I(n.value)?r:xo(r)).flat().filter(MK(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Va(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},FK={description:j(`Transposes the rows and columns of a range.`),args:[B(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=L(e),n=t[0].length,r=t.length;return vo(n,r,(e,n)=>t[n][e])},isExported:!0},IK={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[B(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return pK(e)},isExported:!0},LK={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[B(`range (any, range<any>)`,j(`The range to wrap.`)),B(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),B(`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=L(e),i=ro(t?.value,this.locale);if(!Bx(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return vo(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},RK={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[B(`range (any, range<any>)`,j(`The range to wrap.`)),B(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),B(`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=L(e),i=ro(t?.value,this.locale);if(!Bx(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return vo(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},zK=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],BK={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:[B(`array (range)`,j(`The array to convert into text`)),B(`format (number, default=0)`,j(`The format of the returned data.`),zK)],compute:function(e,t={value:0}){let n=P(t,this.locale),r=L(e);if(n===1)return Dk(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return xo(r).flatMap(e=>e.map(e=>Ja(e.value)?e.value:F(e))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var VK=l({ABS:()=>UK,ACOS:()=>WK,ACOSH:()=>GK,ACOT:()=>KK,ACOTH:()=>qK,ASIN:()=>JK,ASINH:()=>YK,ATAN:()=>XK,ATAN2:()=>ZK,ATANH:()=>QK,CEILING:()=>$K,CEILING_MATH:()=>tq,CEILING_PRECISE:()=>nq,COS:()=>rq,COSH:()=>iq,COT:()=>aq,COTH:()=>oq,COUNTBLANK:()=>sq,COUNTIF:()=>cq,COUNTIFS:()=>lq,COUNTUNIQUE:()=>uq,COUNTUNIQUEIFS:()=>dq,CSC:()=>fq,CSCH:()=>pq,DECIMAL:()=>mq,DEGREES:()=>hq,EXP:()=>gq,FLOOR:()=>_q,FLOOR_MATH:()=>yq,FLOOR_PRECISE:()=>bq,INT:()=>nJ,ISEVEN:()=>xq,ISODD:()=>Cq,ISO_CEILING:()=>Sq,LN:()=>wq,LOG:()=>Tq,MOD:()=>Dq,MUNIT:()=>Oq,ODD:()=>kq,PI:()=>Aq,POWER:()=>jq,PRODUCT:()=>Mq,RAND:()=>Nq,RANDARRAY:()=>Pq,RANDBETWEEN:()=>Fq,ROUND:()=>Iq,ROUNDDOWN:()=>Lq,ROUNDUP:()=>Rq,SEC:()=>zq,SECH:()=>Bq,SEQUENCE:()=>Vq,SIN:()=>Hq,SINH:()=>Uq,SQRT:()=>Wq,SUBTOTAL:()=>Jq,SUM:()=>Yq,SUMIF:()=>Xq,SUMIFS:()=>Zq,TAN:()=>Qq,TANH:()=>$q,TRUNC:()=>tJ});let HK=/^-?[a-z0-9]+$/i,UK={description:j(`Absolute value of a number.`),args:[B(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(P(e,this.locale))},isExported:!0},WK={description:j(`Inverse cosine of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=P(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},GK={description:j(`Inverse hyperbolic cosine of a number.`),args:[B(`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=P(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},KK={description:j(`Inverse cotangent of a value.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=P(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qK={description:j(`Inverse hyperbolic cotangent of a value.`),args:[B(`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=P(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},JK={description:j(`Inverse sine of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=P(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},YK={description:j(`Inverse hyperbolic sine of a number.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(P(e,this.locale))},isExported:!0},XK={description:j(`Inverse tangent of a value, in radians.`),args:[B(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(P(e,this.locale))},isExported:!0},ZK={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[B(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),B(`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=P(e,this.locale),r=P(t,this.locale);return n===0&&r===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},QK={description:j(`Inverse hyperbolic tangent of a number.`),args:[B(`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=P(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},$K={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),B(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=P(e,this.locale),r=P(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 eq(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 tq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),B(`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=P(t,this.locale);return{value:eq(P(e,this.locale),r,P(n,this.locale)),format:e?.format}},isExported:!0},nq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=P(t,this.locale);return{value:eq(P(e,this.locale),n),format:e?.format}},isExported:!0},rq={description:j(`Cosine of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(P(e,this.locale))},isExported:!0},iq={description:j(`Hyperbolic cosine of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(P(e,this.locale))},isExported:!0},aq={description:j(`Cotangent of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},oq={description:j(`Hyperbolic cotangent of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},sq={description:j(`Number of empty values.`),args:[B(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ho(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},cq={description:j(`A conditional count across a range.`),args:[B(`range (range)`,j(`The range that is tested against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return Do(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},lq={description:j(`Count values depending on multiple criteria.`),args:[B(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return Do(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},uq={description:j(`Counts number of unique values in a range.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return Lx(e)}},dq={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),B(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return Do(t,(t,r)=>{let i=e[t]?.[r];Po(i)&&n.add(i.value)},this.locale),n.size}},fq={description:j(`Cosecant of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},pq={description:j(`Hyperbolic cosecant of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=P(e,this.locale);return t===0?new Wa(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},mq={description:j(`Converts from another base to decimal.`),args:[B(`value (string)`,j(`The number to convert.`)),B(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=P(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=F(e);if(r===``)return 0;if(!HK.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},hq={description:j(`Converts an angle value in radians to degrees.`),args:[B(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return P(e,this.locale)*180/Math.PI},isExported:!0},gq={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[B(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(P(e,this.locale))},isExported:!0},_q={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),B(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=P(e,this.locale),r=P(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 vq(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 yq={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),B(`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=P(t,this.locale);return{value:vq(P(e,this.locale),r,P(n,this.locale)),format:e?.format}},isExported:!0},bq={description:j(`Rounds number down to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=P(t,this.locale);return{value:vq(P(e,this.locale),n),format:e?.format}},isExported:!0},xq={description:j(`Whether the provided value is even.`),args:[B(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=no(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},Sq={description:j(`Rounds number up to nearest multiple of factor.`),args:[B(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),B(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:eq(P(e,this.locale),P(t,this.locale)),format:e?.format}},isExported:!0},Cq={description:j(`Whether the provided value is even.`),args:[B(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=no(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},wq={description:j(`The logarithm of a number, base e (euler's number).`),args:[B(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=P(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Tq={description:j(`The logarithm of a number, for a given base.`),args:[B(`value (number)`,j(`The value for which to calculate the logarithm.`)),B(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=P(e,this.locale),r=P(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 Eq(e,t){zx(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 Dq={description:j(`Modulo (remainder) operator.`),args:[B(`dividend (number)`,j(`The number to be divided to find the remainder.`)),B(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=P(t,this.locale);return{value:Eq(P(e,this.locale),n),format:e?.format}},isExported:!0},Oq={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[B(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=ro(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):Wx(t)},isExported:!0},kq={description:j(`Rounds a number up to the nearest odd integer.`),args:[B(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=P(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},Aq={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},jq={description:j(`A number raised to a power.`),args:[B(`base (number)`,j(`The number to raise to the exponent power.`)),B(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=P(e,this.locale),r=P(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},Mq={description:j(`Result of multiplying a series of numbers together.`),args:[B(`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(gt(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),Ja(e))return r}else r!==void 0&&r.value!==null&&(n*=no(r,this.locale),t+=1);return{value:t===0?0:n,format:qa(e[0])}},isExported:!0},Nq={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},Pq={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[B(`rows (number, default=1)`,j(`The number of rows to be returned.`)),B(`columns (number, default=1)`,j(`The number of columns to be returned.`)),B(`min (number, default=0)`,j(`The minimum number you would like returned.`)),B(`max (number, default=1)`,j(`The maximum number you would like returned.`)),B(`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=ro(t,this.locale),o=ro(e,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=I(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},Fq={description:j(`Random integer between two values, inclusive.`),args:[B(`low (number)`,j(`The low end of the random range.`)),B(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=P(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=P(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},Iq={description:j(`Rounds a number according to standard rules.`),args:[B(`value (number)`,j(`The value to round to places number of places.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},Lq={description:j(`Rounds down a number.`),args:[B(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},Rq={description:j(`Rounds up a number.`),args:[B(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),B(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=P(e,this.locale),r=P(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},zq={description:j(`Secant of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(P(e,this.locale))},isExported:!0},Bq={description:j(`Hyperbolic secant of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(P(e,this.locale))},isExported:!0},Vq={description:j(`Returns a sequence of numbers.`),args:[B(`rows (number)`,j(`The number of rows to return`)),B(`columns (number, optional, default=1)`,j(`The number of columns to return`)),B(`start (number, optional, default=1)`,j(`The first number in the sequence`)),B(`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=P(n,this.locale),a=P(r,this.locale),o=ro(e,this.locale),s=ro(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)):vo(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},Hq={description:j(`Sine of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(P(e,this.locale))},isExported:!0},Uq={description:j(`Hyperbolic sine of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(P(e,this.locale))},isExported:!0},Wq={description:j(`Positive square root of a positive number.`),args:[B(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=P(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},Gq={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},Kq=Object.entries(Gq).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),qq=Object.entries(Gq).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),Jq={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[B(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...Kq,...qq]),B(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=ro(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=L(e),n=t[0][0]?.position;if(n===void 0)return new Ba(Za);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||!xn(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[Gq[n]].apply(this,[[i]])},isExported:!0},Yq={description:j(`Sum of a series of numbers and/or cells.`),args:[B(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:Ix(e,this.locale),format:qa(t)}},isExported:!0},Xq={description:j(`A conditional sum across a range.`),args:[B(`criteria_range (range)`,j(`The range which is tested against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to range.`)),B(`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 Do([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},Zq={description:j(`Sums a range depending on multiple criteria.`),args:[B(`sum_range (range)`,j(`The range to sum.`)),B(`criteria_range (any, range, repeating)`,j(`Range to check.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return Do(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},Qq={description:j(`Tangent of an angle provided in radians.`),args:[B(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(P(e,this.locale))},isExported:!0},$q={description:j(`Hyperbolic tangent of any real number.`),args:[B(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(P(e,this.locale))},isExported:!0};function eJ(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let tJ={description:j(`Truncates a number.`),args:[B(`value (number)`,j(`The value to be truncated.`)),B(`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:eJ(P(e,this.locale),P(t,this.locale)),format:e?.format}},isExported:!0},nJ={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[B(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(P(e,this.locale))},isExported:!0};var rJ=l({AVEDEV:()=>pJ,AVERAGE:()=>mJ,AVERAGEA:()=>vJ,AVERAGEIF:()=>yJ,AVERAGEIFS:()=>bJ,AVERAGE_WEIGHTED:()=>_J,CORREL:()=>HJ,COUNT:()=>xJ,COUNTA:()=>SJ,COVAR:()=>CJ,COVARIANCE_P:()=>wJ,COVARIANCE_S:()=>TJ,FORECAST:()=>EJ,GROWTH:()=>DJ,INTERCEPT:()=>OJ,LARGE:()=>kJ,LINEST:()=>AJ,LOGEST:()=>jJ,MATTHEWS:()=>MJ,MAX:()=>NJ,MAXA:()=>PJ,MAXIFS:()=>FJ,MEDIAN:()=>IJ,MIN:()=>LJ,MINA:()=>RJ,MINIFS:()=>zJ,PEARSON:()=>VJ,PERCENTILE:()=>UJ,PERCENTILE_EXC:()=>WJ,PERCENTILE_INC:()=>GJ,POLYFIT_COEFFS:()=>KJ,POLYFIT_FORECAST:()=>qJ,QUARTILE:()=>JJ,QUARTILE_EXC:()=>YJ,QUARTILE_INC:()=>XJ,RANK:()=>ZJ,RSQ:()=>QJ,SLOPE:()=>$J,SMALL:()=>eY,SPEARMAN:()=>tY,STDEV:()=>nY,STDEVA:()=>aY,STDEVP:()=>oY,STDEVPA:()=>sY,STDEV_P:()=>rY,STDEV_S:()=>iY,STEYX:()=>cY,TREND:()=>lY,VAR:()=>uY,VARA:()=>pY,VARP:()=>mY,VARPA:()=>hY,VAR_P:()=>dY,VAR_S:()=>fY});let iJ=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],aJ=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],oJ=[{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)`)}],sJ=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],cJ=[{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 lJ(e,t){let n=[],r=[],i=0,a=0;fo([e],e=>{n.push(e),i+=1}),fo([t],e=>{r.push(e),a+=1}),Rx(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 uJ(e,t,n){let{flatDataX:r,flatDataY:i}=lJ(e,t),a=i.length;zx(a),n&&zx(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 dJ(e,t,n,r){let i=0,a=n?_o:go,o=a(e,(e,t)=>(i+=1,e+t),0,r);zx(i),t&&zx(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function fJ(e,t,n,r){let i=P(t,r);Rx(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 fo(e,e=>{let t=e?.value;typeof t==`number`&&(o=Oo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),Rx(s!==0,Fo),n||Rx(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Oa(a,i,n)}let pJ={description:j(`Average magnitude of deviations from mean.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=go(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return go(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},mJ={description:j(`Numerical average value in a dataset, ignoring text.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Qx(e,this.locale),format:qa(e[0])}},isExported:!0},hJ=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),gJ=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),_J={description:j(`Weighted average.`),args:[B(`values (number, range<number>, repeating)`,j(`Value to average.`)),B(`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(!Vx(i,a))return new N(hJ);if(gt(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=gt(a)?a?.[e][r].value:P(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(gJ);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=P(i,this.locale),r=gt(a)?a?.[0][0].value:P(a,this.locale);if(typeof r==`number`){if(r<0)return new N(gJ);t+=e*r,n+=r}}}return n===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:qa(e[0])}}},vJ={description:j(`Numerical average value in a dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=_o(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:qa(e[0])}},isExported:!0},yJ={description:j(`Average of values depending on criteria.`),args:[B(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),B(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),B(`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=L(n===void 0?e:n),i=0,a=0;return Do([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},bJ={description:j(`Average of values depending on multiple criteria.`),args:[B(`average_range (range)`,j(`The range to average.`)),B(`criteria_range (any, range, repeating)`,j(`Range to check.`)),B(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=L(e),r=0,i=0;return Do(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Wa(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},xJ={description:j(`The number of numeric values in dataset.`),args:[B(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return eS(e,this.locale)},isExported:!0},SJ={description:j(`The number of values in a dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return tS(e)},isExported:!0},CJ={description:j(`The covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!1)},isExported:!0},wJ={description:j(`The covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!1)},isExported:!0},TJ={description:j(`The sample covariance of a dataset.`),args:[B(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uJ(e,t,!0)},isExported:!0},EJ={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[B(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`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}=lJ(t,n);return r.length===0||i.length===0?new Va(Fo):dS([i],[r],yo(L(e),e=>P(e,this.locale)),!0)},isExported:!0},DJ={description:j(`Fits points to exponential growth trend.`),args:[B(`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.`)),B(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),B(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),B(`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.`),iJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Io(`known_data_y`)):lS(dS(uS(to(e,`known_data_y`)),to(t,`known_data_x`),to(n,`new_data_y`),I(r)))}},OJ={description:j(`Compute the intercept of the linear regression.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);let[[],[i]]=aS([n],[r]);return i},isExported:!0},kJ={description:j(`Nth largest element from a data set.`),args:[B(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),B(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(P(t?.value,this.locale)),r=[],i,a=0;fo([e],e=>{typeof e?.value==`number`&&(i=Oo(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(Fo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},AJ={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),B(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),iJ),B(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),aJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Io(`data_y`)):aS(to(t,`data_x`),to(e,`data_y`),I(n),I(r))},isExported:!0},jJ={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),B(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),iJ),B(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),aJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Io(`data_y`));let i=aS(to(t,`data_x`),uS(to(e,`data_y`)),I(n),I(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},MJ={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[B(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),B(`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(Zx(n,r),n.length===0||r.length===0)return new Va(Fo);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=I(n[e]);t===I(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},NJ={description:j(`Maximum value in a numeric dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return nS(e,this.locale)},isExported:!0},PJ={description:j(`Maximum numeric value in a dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=_o(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:qa(e[0])}},isExported:!0},FJ={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),B(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return Do(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},IJ={description:j(`Median value in a numeric dataset.`),args:[B(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return po(e,e=>{t.push(e)},this.locale),{value:fJ(t,{value:.5},!0,this.locale),format:qa(t[0])}},isExported:!0},LJ={description:j(`Minimum value in a numeric dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return rS(e,this.locale)},isExported:!0},RJ={description:j(`Minimum numeric value in a dataset.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=_o(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:qa(e[0])}},isExported:!0},zJ={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[B(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),B(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),B(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return Do(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 BJ(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);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 VJ={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return BJ(e,t)},isExported:!0},HJ=VJ,UJ={description:j(`Value at a given percentile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return GJ.compute.bind(this)(e,t)},isExported:!0},WJ={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`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:fJ([e],t,!1,this.locale),format:qa(e)}},isExported:!0},GJ={description:j(`Value at a given percentile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:fJ([e],t,!0,this.locale),format:qa(e)}},isExported:!0},KJ={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),B(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),oJ),B(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),sJ)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=lJ(e,t);return i.length===0||a.length===0?new Va(Fo):oS(a,i,P(n,this.locale),I(r))},isExported:!1},qJ={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[B(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),B(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),oJ),B(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),sJ)],compute:function(e,t,n,r,i={value:!0}){let a=P(r,this.locale),{flatDataX:o,flatDataY:s}=lJ(t,n);if(o.length===0||s.length===0)return new Va(Fo);let c=oS(s,o,a,I(i)).flat();return yo(L(e),e=>cS(c,P(e,this.locale),a))},isExported:!1},JJ={description:j(`Value nearest to a specific quartile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`quartile_number (number)`,j(`Which quartile value to return.`),cJ)],compute:function(e,t){return XJ.compute.bind(this)(e,t)},isExported:!0},YJ={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`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(P(t,this.locale))};return{value:fJ([e],n,!1,this.locale),format:qa(e)}},isExported:!0},XJ={description:j(`Value nearest to a specific quartile of a dataset.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`quartile_number (number)`,j(`Which quartile value to return.`),cJ)],compute:function(e,t){let n={value:.25*Math.trunc(P(t,this.locale))};return{value:fJ([e],n,!0,this.locale),format:qa(e)}},isExported:!0},ZJ={description:j(`Returns the rank of a specified value in a dataset.`),args:[B(`value (number)`,j(`The value whose rank will be determined.`)),B(`data (range)`,j(`The range containing the dataset to consider.`)),B(`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=I(n),i=P(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=P(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Va(j(`Value not found in the given data.`))},isExported:!0},QJ={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=BJ(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},$J={description:j(`Compute the slope of the linear regression.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);if(n.length===0||r.length===0)return new Va(Fo);let[[i]]=aS([n],[r]);return i},isExported:!0},eY={description:j(`Nth smallest element in a data set.`),args:[B(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),B(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(P(t?.value,this.locale)),r=[],i,a=0;fo([e],e=>{typeof e?.value==`number`&&(i=Oo(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(Fo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},tY={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(t,e);if(n.length===0||r.length===0)return new Va(Fo);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},nY={description:j(`Standard deviation.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(uY.compute.bind(this)(...e))},isExported:!0},rY={description:j(`Standard deviation of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(dY.compute.bind(this)(...e))},isExported:!0},iY={description:j(`Standard deviation.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(fY.compute.bind(this)(...e))},isExported:!0},aY={description:j(`Standard deviation of sample (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(pY.compute.bind(this)(...e))},isExported:!0},oY={description:j(`Standard deviation of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(mY.compute.bind(this)(...e))},isExported:!0},sY={description:j(`Standard deviation of entire population (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(hY.compute.bind(this)(...e))},isExported:!0},cY={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[B(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),B(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lJ(e,t);return n.length===0||r.length===0?new Va(Fo):aS([n],[r],!0,!0)[1][2]},isExported:!0},lY={description:j(`Fits points to linear trend derived via least-squares.`),args:[B(`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.`)),B(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),B(`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.`)),B(`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.`),iJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Io(`known_data_y`)):dS(to(e,`known_data_y`),to(t,`known_data_x`),to(n,`new_data_y`),I(r))}},uY={description:j(`Variance.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!1,this.locale)},isExported:!0},dY={description:j(`Variance of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!1,this.locale)},isExported:!0},fY={description:j(`Variance.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!1,this.locale)},isExported:!0},pY={description:j(`Variance of sample (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return dJ(e,!0,!0,this.locale)},isExported:!0},mY={description:j(`Variance of entire population.`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!1,this.locale)},isExported:!0},hY={description:j(`Variance of entire population (text as 0).`),args:[B(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return dJ(e,!1,!0,this.locale)},isExported:!0};var gY=l({DAVERAGE:()=>yY,DCOUNT:()=>bY,DCOUNTA:()=>xY,DGET:()=>SY,DMAX:()=>CY,DMIN:()=>wY,DPRODUCT:()=>TY,DSTDEV:()=>EY,DSTDEVP:()=>DY,DSUM:()=>OY,DVAR:()=>kY,DVARP:()=>AY});function _Y(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(F(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=F(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,F(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=F(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)Do(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 vY=[B(`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.`)),B(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),B(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],yY={description:j(`Average of a set of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return mJ.compute.bind(this)([r])},isExported:!0},bY={description:j(`Counts values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return xJ.compute.bind(this)([r])},isExported:!0},xY={description:j(`Counts values and text from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return SJ.compute.bind(this)([r])},isExported:!0},SY={description:j(`Single value from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},CY={description:j(`Maximum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return NJ.compute.bind(this)([r])},isExported:!0},wY={description:j(`Minimum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return LJ.compute.bind(this)([r])},isExported:!0},TY={description:j(`Product of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return Mq.compute.bind(this)([r])},isExported:!0},EY={description:j(`Standard deviation of population sample from table.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return nY.compute.bind(this)([r])},isExported:!0},DY={description:j(`Standard deviation of entire population from table.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return oY.compute.bind(this)([r])},isExported:!0},OY={description:j(`Sum of values from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return Yq.compute.bind(this)([r])},isExported:!0},kY={description:j(`Variance of population sample from table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return uY.compute.bind(this)([r])},isExported:!0},AY={description:j(`Variance of a population from a table-like range.`),args:vY,compute:function(e,t,n){let r=_Y(e,t,n,this.locale);return mY.compute.bind(this)([r])},isExported:!0},jY=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),MY=j(`There must be both positive and negative values in cashflow_amounts.`),NY=e=>j(`The cost (%s) must be positive or null.`,e),PY=e=>j(`The cost (%s) must be strictly positive.`,e),FY=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),IY=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),LY=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),RY=e=>j(`The discount (%s) must be different from -1.`,e),zY=e=>j(`The discount (%s) must be strictly positive.`,e),BY=e=>j(`The discount (%s) must be smaller than 1.`,e),VY=e=>j(`The effective_rate (%s) must be strictly positive.`,e),HY=e=>j(`The end_period (%s) must be positive or null.`,e),UY=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),WY=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),GY=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),KY=e=>j(`The first_period (%s) must be strictly positive.`,e),qY=e=>j(`The future_value (%s) must be strictly positive.`,e),JY=e=>j(`The investment (%s) must be strictly positive.`,e),YY=e=>j(`The issue (%s) must be positive or null.`,e),XY=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),ZY=e=>j(`The last_period (%s) must be strictly positive.`,e),QY=e=>j(`The life (%s) must be strictly positive.`,e),$Y=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),eX=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),tX=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),nX=e=>j(`The number_of_periods (%s) must be different from zero.`,e),rX=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),iX=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),aX=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),oX=e=>j(`The period (%s) must be positive or null.`,e),sX=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),cX=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),lX=e=>j(`The period (%s) must be strictly positive.`,e),uX=e=>j(`The present_value (%s) must be strictly positive.`,e),dX=e=>j(`The price (%s) must be strictly positive.`,e),fX=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),pX=e=>j(`The purchase_date (%s) must be positive or null.`,e),mX=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),hX=e=>j(`The rate (%s) must be positive or null.`,e),gX=e=>j(`The rate (%s) must be strictly positive.`,e),_X=e=>j(`The redemption (%s) must be strictly positive.`,e),vX=e=>j(`The salvage (%s) must be positive or null.`,e),yX=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),bX=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),xX=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),SX=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),CX=e=>j(`The start_period (%s) must be positive or null.`,e),wX=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),TX=e=>j(`The unit (%s) must be strictly positive.`,e),EX=e=>j(`The yield (%s) must be positive or null.`,e);function DX(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function OX(e){return![0,1,2,3,4].includes(e)}function kX(e){return![1,2,4].includes(e)}function AX(e,t,n){let r=co(e,n),i=co(t,n),a=co(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let jX=[{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 MX=l({DATE:()=>PX,DATEDIF:()=>FX,DATEVALUE:()=>IX,DAY:()=>LX,DAYS:()=>RX,DAYS360:()=>zX,EDATE:()=>BX,EOMONTH:()=>VX,HOUR:()=>HX,ISOWEEKNUM:()=>UX,MINUTE:()=>WX,MONTH:()=>GX,MONTH_END:()=>cZ,MONTH_START:()=>sZ,NETWORKDAYS:()=>KX,NETWORKDAYS_INTL:()=>YX,NOW:()=>XX,QUARTER:()=>lZ,QUARTER_END:()=>dZ,QUARTER_START:()=>uZ,SECOND:()=>ZX,TIME:()=>QX,TIMEVALUE:()=>$X,TODAY:()=>eZ,WEEKDAY:()=>tZ,WEEKNUM:()=>nZ,WORKDAY:()=>rZ,WORKDAY_INTL:()=>iZ,YEAR:()=>aZ,YEARFRAC:()=>oZ,YEAR_END:()=>pZ,YEAR_START:()=>fZ}),NX=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}(NX||{});let PX={description:j(`Converts year/month/day into a date.`),args:[B(`year (number)`,j(`The year component of the date.`)),B(`month (number)`,j(`The month component of the date.`)),B(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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=oa(new Ni(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},FX={description:j(`Calculates the number of days, months, or years between two dates.`),args:[B(`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.`)),B(`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.`)),B(`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=F(n).toUpperCase();if(!Object.values(NX).includes(r))return new N($a(Object.values(NX),F(n)));let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=aa(i),s=aa(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 ha(o,s);case`M`:return pa(o,s);case`D`:return ma(o,s);case`YM`:return pa(o,s)-ha(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=ca(new Ni(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(ga(i,a))return ma(o,s);let e=new Ni(o.getFullYear(),s.getMonth(),s.getDate()),t=ma(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=ma(o,e)),t}}},isExported:!0},IX={description:j(`Converts a date string to a date value.`),args:[B(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=F(e),n=Yi(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},LX={description:j(`Day of the month that a specific date falls on.`),args:[B(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return co(e,this.locale).getDate()},isExported:!0},RX={description:j(`Number of days between two dates.`),args:[B(`end_date (date)`,j(`The end of the date range.`)),B(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=co(e,this.locale),r=co(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Fi)},isExported:!0},zX={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[B(`start_date (date)`,j(`The start date to consider in the calculation.`)),B(`end_date (date)`,j(`The end date to consider in the calculation.`)),B(`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(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=fa(r,i,I(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},BX={description:j(`Date a number of months before/after another date.`),args:[B(`start_date (date)`,j(`The date from which to calculate the result.`)),B(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:oa(ua(co(e,this.locale),Math.trunc(P(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},VX={description:j(`Last day of a month before or after a date.`),args:[B(`start_date (date)`,j(`The date from which to calculate the result.`)),B(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=co(e,this.locale),r=Math.trunc(P(t,this.locale));return{value:oa(new Ni(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},HX={description:j(`Hour component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return co(e,this.locale).getHours()},isExported:!0},UX={description:j(`ISO week number of the year.`),args:[B(`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=co(e,this.locale),n=t.getFullYear(),r=1;for(;new Ni(n,0,r).getDay()!==4;)r+=1;let i=new Ni(n,0,r-3),a=31;for(;new Ni(n,11,a).getDay()!==4;)--a;let o=new Ni(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 Ni(n,11,a+3+1);break;case-1:let e=1;for(;new Ni(n-1,0,e).getDay()!==4;)e+=1;c=new Ni(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Fi;return Math.floor(l/7)+1},isExported:!0},WX={description:j(`Minute component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return co(e,this.locale).getMinutes()},isExported:!0},GX={description:j(`Month of the year a specific date falls in`),args:[B(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return co(e,this.locale).getMonth()+1},isExported:!0},KX={description:j(`Net working days between two provided days.`),args:[B(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),B(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),B(`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 YX.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function qX(e){let t=e?.value;if(typeof t==`string`){Rx(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 Rx(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 JX=[{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`)}],YX={description:j(`Net working days between two dates (specifying weekends).`),args:[B(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),B(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),B(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),JX),B(`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=co(e,this.locale),a=co(t,this.locale),o=qX(n),s=new Set;r!==void 0&&fo([r],e=>{let t=co(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=Ni.fromTimestamp((c?i:a).getTime()),u=Ni.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},XX={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=Ni.now(),t=e.getTime()-Pi.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Fi)+n,format:z_(this.locale)}},isExported:!0},ZX={description:j(`Minute component of a specific time.`),args:[B(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return co(e,this.locale).getSeconds()},isExported:!0},QX={description:j(`Converts hour/minute/second into a time.`),args:[B(`hour (number)`,j(`The hour component of the time.`)),B(`minute (number)`,j(`The minute component of the time.`)),B(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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},$X={description:j(`Converts a time string into its serial number representation.`),args:[B(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=F(e),n=Yi(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},eZ={description:j(`Current date as a date value.`),args:[],compute:function(){let e=Ni.now();return{value:oa(new Ni(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},tZ={description:j(`Day of the week of the date provided (as number).`),args:[B(`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.`)),B(`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=co(e,this.locale),r=Math.round(P(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},nZ={description:j(`Week number of the year.`),args:[B(`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.`)),B(`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=co(e,this.locale),r=Math.round(P(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 UX.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 Ni(a,0,o);for(;s.getDay()!==i;)o+=1,s=new Ni(a,0,o);let c=(n.getTime()-s.getTime())/Fi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},rZ={description:j(`Date after a number of workdays.`),args:[B(`start_date (date)`,j(`The date from which to begin counting.`)),B(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),B(`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 iZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0},iZ={description:j(`Date after a number of workdays (specifying weekends).`),args:[B(`start_date (date)`,j(`The date from which to begin counting.`)),B(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),B(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),JX),B(`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=co(e,this.locale),a=Math.trunc(P(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=qX(n),s=new Set;r!==void 0&&fo([r],e=>{let t=co(e,this.locale);s.add(t.getTime())});let c=Ni.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-Pi.getTime();return{value:Math.round(f/Fi),format:this.locale.dateFormat}},isExported:!0},aZ={description:j(`Year specified by a given date.`),args:[B(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return co(e,this.locale).getFullYear()},isExported:!0},oZ={description:j(`Exact number of years between two dates.`),args:[B(`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.`)),B(`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.`)),B(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n={value:0}){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=Math.trunc(P(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)):fa(r,i,a)}},sZ={description:j(`First day of the month preceding a date.`),args:[B(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=co(e,this.locale);return{value:oa(new Ni(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},cZ={description:j(`Last day of the month following a date.`),args:[B(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return VX.compute.bind(this)(e,{value:0})}},lZ={description:j(`Quarter of the year a specific date falls in`),args:[B(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((co(e,this.locale).getMonth()+1)/3)}},uZ={description:j(`First day of the quarter of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=lZ.compute.bind(this)(e);return{value:oa(new Ni(aZ.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},dZ={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=lZ.compute.bind(this)(e);return{value:oa(new Ni(aZ.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},fZ={description:j(`First day of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:oa(new Ni(aZ.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},pZ={description:j(`Last day of the year a specific date falls in.`),args:[B(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:oa(new Ni(aZ.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var mZ=l({DELTA:()=>hZ});let hZ={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[B(`number1 (number)`,j(`The first number to compare.`)),B(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(P(e,this.locale)===P(t,this.locale))},isExported:!0};var gZ=l({FILTER:()=>vZ,SORT:()=>yZ,SORTN:()=>bZ,UNIQUE:()=>xZ});function _Z(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;Rx(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(I(Jx(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(gt(s)&&(s.length>1||s[0].length>1))Rx(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=P(Jx(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:iV(`desc`),asc:iV(`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 vZ={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[B(`range (any, range<any>)`,j(`The data to be filtered.`)),B(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=L(e),r=t.map(e=>yo(L(e),e=>e.value));for(let e of r)if(!Bx(e))return new N(j(`The arguments condition must be a single column or row.`));if(!Vx(...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`?xo(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`?xo(o):o:new Va(j(`No match found in FILTER evaluation`))},isExported:!1},yZ={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[B(`range (range)`,j(`The data to be sorted.`)),B(`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.`)),B(`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 xo(_Z(xo(e),this.locale,...t))},isExported:!0},bZ={description:j(`Returns the first n items in a data set after performing a sort.`),args:[B(`range (range)`,j(`The data to be sorted.`)),B(`n (number)`,j(`The number of items to return.`)),B(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),B(`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.`)),B(`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=P(t?.value??1,this.locale),i=n.length%2==0?0:P(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=_Z(xo(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 xo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return xo(o.slice(0,e));return xo(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 xo(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 xo(e)}}},isExported:!1},xZ={description:j(`Unique rows in the provided source range.`),args:[B(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),B(`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`)}]),B(`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(!gt(e))return[[e]];let r=I(t?.value)||!1,i=I(n?.value)||!1;r||(e=xo(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:xo(o):new N(j(`No unique values found`))},isExported:!0};var SZ=l({ACCRINTM:()=>DZ,AMORLINC:()=>OZ,COUPDAYBS:()=>AZ,COUPDAYS:()=>kZ,COUPDAYSNC:()=>jZ,COUPNCD:()=>MZ,COUPNUM:()=>NZ,COUPPCD:()=>PZ,CUMIPMT:()=>FZ,CUMPRINC:()=>IZ,DB:()=>LZ,DDB:()=>zZ,DISC:()=>BZ,DOLLARDE:()=>VZ,DOLLARFR:()=>HZ,DURATION:()=>UZ,EFFECT:()=>WZ,FV:()=>KZ,FVSCHEDULE:()=>qZ,INTRATE:()=>JZ,IPMT:()=>XZ,IRR:()=>QZ,ISPMT:()=>$Z,MDURATION:()=>eQ,MIRR:()=>tQ,NOMINAL:()=>nQ,NPER:()=>rQ,NPV:()=>aQ,PDURATION:()=>oQ,PMT:()=>cQ,PPMT:()=>uQ,PRICE:()=>fQ,PRICEDISC:()=>pQ,PRICEMAT:()=>mQ,PV:()=>dQ,RATE:()=>gQ,RECEIVED:()=>_Q,RRI:()=>vQ,SLN:()=>yQ,SYD:()=>bQ,TBILLEQ:()=>CQ,TBILLPRICE:()=>SQ,TBILLYIELD:()=>wQ,VDB:()=>TQ,XIRR:()=>EQ,XNPV:()=>DQ,YIELD:()=>OQ,YIELDDISC:()=>kQ,YIELDMAT:()=>AQ});let CZ=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],wZ=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],TZ=[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)];function EZ(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)){Rx(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,Rx(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let DZ={description:j(`Accrued interest of security paying at maturity.`),args:[B(`issue (date)`,j(`The date the security was initially issued.`)),B(`maturity (date)`,j(`The maturity date of the security.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(r,this.locale),c=P(n,this.locale),l=Math.trunc(P(i,this.locale));if(a<0)return new N(YY(a));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(_X(s));if(c<=0)return new N(gX(c));let u=fa(a,o,l);return s*c*u},isExported:!0},OZ={description:j(`Depreciation for an accounting period.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`purchase_date (date)`,j(`The date the asset was purchased.`)),B(`first_period_end (date)`,j(`The date the first period ended.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`rate (number)`,j(`The deprecation rate.`)),B(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=P(e,this.locale),c=Math.trunc(P(t,this.locale)),l=Math.trunc(P(n,this.locale)),u=P(r,this.locale),d=P(i,this.locale),f=P(a,this.locale),p=Math.trunc(P(o,this.locale));if(s<=0)return new N(PY(s));if(c<0)return new N(pX(c));if(u<0)return new N(vX(u));if(u>s)return new N(yX(u,s));if(d<0)return new N(oX(d));if(f<=0)return new N(gX(f));if(OX(p))return new N(IY(p));if(c>l)return new N(fX(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=fa(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},kZ={description:j(`Days in coupon period containing settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));if(s===1){let i=PZ.compute.bind(this)(e,t,n,r).value,a=MZ.compute.bind(this)(e,t,n,r).value;return P(a,this.locale)-P(i,this.locale)}return(s===3?365:360)/o},isExported:!0},AZ={description:j(`Days from settlement until next coupon.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=PZ.compute.bind(this)(e,t,n,r).value,l=P(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=fa(l,i,s);return Math.round(e*360)}let u=co(i,this.locale),d=co(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&&la(d)&&la(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&la(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},jZ={description:j(`Days from settlement until next coupon.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=MZ.compute.bind(this)(e,t,n,r).value,l=P(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=fa(i,l,s);return Math.round(e*360)}let u=AZ.compute.bind(this)(e,t,n,r);return P(kZ.compute.bind(this)(e,t,n,r),this.locale)-P(u,this.locale)},isExported:!0},MZ={description:j(`Next coupon date after the settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=12/o,l=NZ.compute.bind(this)(e,t,n,r);return{value:oa(ua(co(a,this.locale),-(P(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},NZ={description:j(`Number of coupons between settlement and maturity.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=1,l=a,u=12/o;for(;l>i;)l=oa(ua(co(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},PZ={description:j(`Last coupon date prior to or on the settlement date.`),args:TZ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(P(e,this.locale)),a=Math.trunc(P(t,this.locale)),o=Math.trunc(P(n,this.locale)),s=Math.trunc(P(r,this.locale));if(i>=a)return new N($Y(i,a));if(kX(o))return new N(FY(o));if(OX(s))return new N(IY(s));let c=12/o,l=NZ.compute.bind(this)(e,t,n,r);return{value:oa(ua(co(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},FZ={description:j(`Cumulative interest paid over a set of periods.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),B(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i,a={value:0}){let o=P(r,this.locale),s=P(i,this.locale),c=P(e,this.locale),l=P(n,this.locale),u=P(t,this.locale),d=+!!I(a);if(u<=0)return new N(rX(u));if(o<=0)return new N(KY(o));if(s<=0)return new N(ZY(s));if(o>s)return new N(GY(o,s));if(s>u)return new N(XY(s,u));if(c<=0)return new N(gX(c));if(l<=0)return new N(uX(l));let f=0;for(let e=o;e<=s;e++)f+=YZ(c,e,u,l,0,d);return f},isExported:!0},IZ={description:j(`Cumulative principal paid over a set of periods.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),B(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i,a={value:0}){let o=P(r,this.locale),s=P(i,this.locale),c=P(e,this.locale),l=P(n,this.locale),u=P(t,this.locale),d=+!!I(a);if(u<=0)return new N(rX(u));if(o<=0)return new N(KY(o));if(s<=0)return new N(ZY(s));if(o>s)return new N(GY(o,s));if(s>u)return new N(XY(s,u));if(c<=0)return new N(gX(c));if(l<=0)return new N(uX(l));let f=0;for(let e=o;e<=s;e++)f+=lQ(c,e,u,l,0,d);return f},isExported:!0},LZ={description:j(`Depreciation via declining balance method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=Math.trunc(P(r,this.locale)),l=i.length?Math.trunc(P(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(NY(a));if(o<0)return new N(vX(o));if(c<=0)return new N(lX(c));if(s<=0)return new N(QY(s));if(1>l||l>12)return new N(eX(l));if(c>u)return new N(aX(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},RZ=`#,##0.00`,zZ={description:j(`Depreciation via double-declining balance method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),B(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=P(i,this.locale);if(a<0)return new N(NY(a));if(o<0)return new N(vX(o));if(c<=0)return new N(lX(c));if(s<=0)return new N(QY(s));if(c>s)return new N(cX(c,s));if(l<=0)return new N(LY(l));if(a===0||o>=a)return{value:0,format:RZ};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:RZ};if(c<=1)return{value:a*u,format:RZ};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:RZ}},isExported:!0},BZ={description:j(`Discount rate of a security based on price.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(dX(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return(c-s)/c/u},isExported:!0},VZ={description:j(`Convert a decimal fraction to decimal value.`),args:[B(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),B(`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=P(e,this.locale),r=Math.trunc(P(t,this.locale));if(r<=0)return new N(TX(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},HZ={description:j(`Convert a decimal value to decimal fraction.`),args:[B(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),B(`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=P(e,this.locale),r=Math.trunc(P(t,this.locale));if(r<=0)return new N(TX(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},UZ={description:j(`Number of periods for an investment to reach a value.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=P(n,this.locale),l=P(r,this.locale),u=Math.trunc(P(i,this.locale)),d=Math.trunc(P(a,this.locale));if(o>=s)return new N($Y(o,s));if(kX(u))return new N(FY(u));if(OX(d))return new N(IY(d));if(c<0)return new N(hX(c));if(l<0)return new N(EX(l));let f=fa(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},WZ={description:j(`Annual effective interest rate.`),args:[B(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),B(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=P(e,this.locale),r=Math.trunc(P(t,this.locale));return n<=0?new N(tX(n)):r<=0?new N(sX(r)):(1+n/r)**+r-1},isExported:!0};function GZ(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 KZ={description:j(`Future value of an annuity investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_amount (number)`,j(`The amount per period to be paid.`)),B(`present_value (number, default=0)`,j(`The current value of the annuity.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:GZ(P(e,this.locale),P(t,this.locale),P(n,this.locale),P(r,this.locale),+!!I(i)),format:`#,##0.00`}},isExported:!0},qZ={description:j(`Future value of principal from series of rates.`),args:[B(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),B(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=P(e,this.locale);return ho([t],(e,t)=>e*(1+P(t,this.locale)),n)},isExported:!0},JZ={description:j(`Calculates effective interest rate.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`investment (number)`,j(`The amount invested in the security.`)),B(`redemption (number)`,j(`The amount to be received at maturity.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(r,this.locale),c=P(n,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(c<=0)return new N(JY(c));if(s<=0)return new N(_X(s));if(OX(l))return new N(IY(l));let u=fa(a,o,l);return(s-c)/c/u},isExported:!0};function YZ(e,t,n,r,i,a){return sQ(e,n,r,i,a)-lQ(e,t,n,r,i,a)}let XZ={description:j(`Payment on the principal of an investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`period (number)`,j(`The amortization period, in terms of number of periods.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:YZ(P(e,this.locale),P(t,this.locale),P(n,this.locale),P(r,this.locale),P(i,this.locale),+!!I(a)),format:`#,##0.00`}},isExported:!0},ZZ=.1,QZ={description:j(`Internal rate of return given periodic cashflows.`),args:[B(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),B(`rate_guess (number, default=${ZZ})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:ZZ}){let n=P(t,this.locale);if(n<=-1)return new N(mX(n));let r=!1,i=!1,a=[];if(po([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(MY);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:EZ(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},$Z={description:j(`Returns the interest paid at a particular period of an investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`period (number)`,j(`The period for which you want to view the interest payment.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=P(e,this.locale),a=P(t,this.locale),o=P(n,this.locale),s=P(r,this.locale);return o===0?new N(nX(o)):-1*(s-a/o*s)*i},isExported:!0},eQ={description:j(`Modified Macaulay duration.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`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=UZ.compute.bind(this)(e,t,n,r,i,a),s=P(r,this.locale),c=Math.trunc(P(i,this.locale));return P(o,this.locale)/(1+s/c)},isExported:!0},tQ={description:j(`Modified internal rate of return.`),args:[B(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),B(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),B(`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=P(t,this.locale),i=P(n,this.locale),a=xo(e).flat().filter(e=>e.value!==null).map(e=>P(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(MY);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},nQ={description:j(`Annual nominal interest rate.`),args:[B(`effective_rate (number)`,j(`The effective interest rate per year.`)),B(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=P(e,this.locale),r=Math.trunc(P(t,this.locale));return n<=0?new N(VY(n)):r<=0?new N(sX(r)):((n+1)**(1/r)-1)*r},isExported:!0},rQ={description:j(`Number of payment periods for an investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`payment_amount (number)`,j(`The amount of each payment made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=+!!I(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 iQ(e,t,n,r){let i=0;return go(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let aQ={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[B(`discount (number)`,j(`The discount rate of the investment over one period.`)),B(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=P(e,this.locale);return n===-1?new N(RY(n)):{value:iQ(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},oQ={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[B(`rate (number)`,j(`The rate at which the investment grows each period.`)),B(`present_value (number)`,j(`The investment's current value.`)),B(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return r<=0?new N(gX(r)):i<=0?new N(uX(i)):a<=0?new N(qY(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function sQ(e,t,n,r,i){if(t<=0)throw new N(rX(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 cQ={description:j(`Periodic payment for an annuity investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){let a=P(t,this.locale),o=P(e,this.locale),s=+!!I(i),c=P(r,this.locale);return{value:sQ(o,a,P(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function lQ(e,t,n,r,i,a){if(n<=0)throw new N(rX(n));if(t<=0||t>n)throw new N(iX(n));let o=sQ(e,n,r,i,a);return a===1&&t===1?o:o+-GZ(e,a===0?t-1:t-2,o,r+o*a,0)*e}let uQ={description:j(`Payment on the principal of an investment.`),args:[B(`rate (number)`,j(`The annualized rate of interest.`)),B(`period (number)`,j(`The amortization period, in terms of number of periods.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=P(n,this.locale),s=P(e,this.locale),c=P(t,this.locale),l=+!!I(a),u=P(i,this.locale);return{value:lQ(s,c,o,P(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},dQ={description:j(`Present value of an annuity investment.`),args:[B(`rate (number)`,j(`The interest rate.`)),B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_amount (number)`,j(`The amount per period to be paid.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=P(e,this.locale),o=P(t,this.locale),s=P(n,this.locale),c=P(r,this.locale),l=+!!I(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},fQ={description:j(`Price of a security paying periodic interest.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(P(e,this.locale)),c=Math.trunc(P(t,this.locale)),l=P(n,this.locale),u=P(r,this.locale),d=P(i,this.locale),f=Math.trunc(P(a,this.locale)),p=Math.trunc(P(o,this.locale));if(s>=c)return new N($Y(s,c));if(kX(f))return new N(FY(f));if(OX(p))return new N(IY(p));if(l<0)return new N(hX(l));if(u<0)return new N(EX(u));if(d<=0)return new N(_X(d));let m=fa(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 ee=0;for(let e=1;e<=h;e++)ee+=v/_**(e-1+g);return d/_**(h-1+g)+ee-v*(1-g)},isExported:!0},pQ={description:j(`Price of a discount security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(zY(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return c-s*c*u},isExported:!0},mQ={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`issue (date)`,j(`The date the security was initially issued.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`yield (number)`,j(`The expected annual yield of the security.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=Math.trunc(P(n,this.locale)),l=P(r,this.locale),u=P(i,this.locale),d=Math.trunc(P(a,this.locale));if(o<=c)return new N(SX(o,c));if(o>=s)return new N($Y(o,s));if(OX(d))return new N(IY(d));if(l<0)return new N(hX(l));if(u<0)return new N(EX(u));let f=fa(o,s,d),p=fa(o,c,d),m=100+fa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},hQ=.1,gQ={description:j(`Interest rate of an annuity investment.`),args:[B(`number_of_periods (number)`,j(`The number of payments to be made.`)),B(`payment_per_period (number)`,j(`The amount per period to be paid.`)),B(`present_value (number)`,j(`The current value of the annuity.`)),B(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),B(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),wZ),B(`rate_guess (number, default=${hQ})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:hQ}){let o=P(e,this.locale),s=P(t,this.locale),c=+!!I(i),l=P(a,this.locale)||hQ,u=P(r,this.locale),d=P(n,this.locale);return o<=0?new N(rX(o)):DX([s,d,u])?l<=-1?new N(mX(l)):(u-=s*c,d+=s*c,{value:EZ(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},_Q={description:j(`Amount received at maturity for a security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),B(`discount (number)`,j(`The discount rate of the security invested in.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));return a>=o?new N($Y(a,o)):OX(l)?new N(IY(l)):s<=0?new N(JY(s)):c<=0?new N(zY(c)):s/(1-c*fa(a,o,l))},isExported:!0},vQ={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[B(`number_of_periods (number)`,j(`The number of periods.`)),B(`present_value (number)`,j(`The present value of the investment.`)),B(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return r<=0?new N(rX(r)):(a/i)**(1/r)-1},isExported:!0},yQ={description:j(`Depreciation of an asset using the straight-line method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=P(e,this.locale),i=P(t,this.locale),a=P(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},bQ={description:j(`Depreciation via sum of years digit method.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=P(e,this.locale),a=P(t,this.locale),o=P(n,this.locale),s=P(r,this.locale);if(s<=0)return new N(lX(s));if(o<=0)return new N(QY(o));if(s>o)return new N(cX(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function xQ(e,t,n){return 100*(1-n*fa(e,t,2))}let SQ={description:j(`Price of a US Treasury bill.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);return r>=i?new N($Y(r,i)):AX(r,i,this.locale)?a<=0?new N(zY(a)):a>=1?new N(BY(a)):xQ(r,i,a):new N(xX(r,i))},isExported:!0},CQ={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);if(r>=i)return new N($Y(r,i));if(!AX(r,i,this.locale))return new N(xX(r,i));if(a<=0)return new N(zY(a));if(a>=1)return new N(BY(a));let o=RX.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=xQ(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},wQ={description:j(`The yield of a US Treasury bill based on price.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(P(e,this.locale)),i=Math.trunc(P(t,this.locale)),a=P(n,this.locale);if(r>=i)return new N($Y(r,i));if(!AX(r,i,this.locale))return new N(xX(r,i));if(a<=0)return new N(dX(a));let o=fa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},TQ={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[B(`cost (number)`,j(`The initial cost of the asset.`)),B(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),B(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),B(`start (number)`,j(`Starting period to calculate depreciation.`)),B(`end (number)`,j(`Ending period to calculate depreciation.`)),B(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),B(`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=P(e,this.locale),c=P(t,this.locale),l=P(n,this.locale),u=Math.trunc(P(r,this.locale)),d=Math.trunc(P(i,this.locale)),f=P(a,this.locale),p=I(o);if(s<0)return new N(NY(s));if(c<0)return new N(vX(c));if(l<=0)return new N(QY(l));if(u<0)return new N(CX(u));if(d<0)return new N(HY(d));if(u>d)return new N(wX(u,d));if(d>l)return new N(UY(d,l));if(f<=0)return new N(LY(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},EQ={description:j(`Internal rate of return given non-periodic cash flows.`),args:[B(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),B(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),B(`rate_guess (number, default=${hQ})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:hQ}){let r=P(n,this.locale);if(!Vx(e,t))return new N(jY);let i=e.flat().map(e=>P(e,this.locale)),a=t.flat().map(e=>P(e,this.locale));if(!DX(i))return new N(MY);if(a.some(e=>e<a[0]))return new N(WY(a[0]));if(r<=-1)return new N(mX(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 EZ(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},DQ={description:j(`Net present value given to non-periodic cash flows..`),args:[B(`discount (number)`,j(`The discount rate of the investment over one period.`)),B(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),B(`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=P(e,this.locale);if(!Vx(t,n))return new N(jY);let i=L(t).flat().map(e=>no(e,this.locale)),a=L(n).flat().map(e=>no(e,this.locale));if(a.some(e=>e<a[0]))return new N(WY(a[0]));if(r<=0)return new N(gX(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},OQ={description:j(`Annual yield of a security paying periodic interest.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),CZ),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(P(e,this.locale)),c=Math.trunc(P(t,this.locale)),l=P(n,this.locale),u=P(r,this.locale),d=P(i,this.locale),f=Math.trunc(P(a,this.locale)),p=Math.trunc(P(o,this.locale));if(s>=c)return new N($Y(s,c));if(kX(f))return new N(FY(f));if(OX(p))return new N(IY(p));if(l<0)return new N(hX(l));if(u<=0)return new N(dX(u));if(d<=0)return new N(_X(d));let m=fa(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 ee(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 y(e){return v(u,g,h,e,_,d)}function b(e){return ee(u,g,h,e,_)}return(EZ(y,b,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},kQ={description:j(`Annual yield of a discount security.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),B(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(P(e,this.locale)),o=Math.trunc(P(t,this.locale)),s=P(n,this.locale),c=P(r,this.locale),l=Math.trunc(P(i,this.locale));if(a>=o)return new N($Y(a,o));if(OX(l))return new N(IY(l));if(s<=0)return new N(dX(s));if(c<=0)return new N(_X(c));let u=fa(a,o,l);return(c/s-1)/u},isExported:!0},AQ={description:j(`Annual yield of a security paying interest at maturity.`),args:[B(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),B(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),B(`issue (date)`,j(`The date the security was initially issued.`)),B(`rate (number)`,j(`The annualized rate of interest.`)),B(`price (number)`,j(`The price at which the security is bought.`)),B(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),jX)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(P(e,this.locale)),s=Math.trunc(P(t,this.locale)),c=Math.trunc(P(n,this.locale)),l=P(r,this.locale),u=P(i,this.locale),d=Math.trunc(P(a,this.locale));if(o>=s)return new N($Y(o,s));if(OX(d))return new N(IY(d));if(o<c)return new N(bX(o,c));if(l<0)return new N(hX(l));if(u<=0)return new N(dX(u));let f=fa(c,s,d),p=fa(c,o,d),m=fa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var jQ=l({CELL:()=>NQ,ISBLANK:()=>VQ,ISERR:()=>PQ,ISERROR:()=>FQ,ISFORMULA:()=>UQ,ISLOGICAL:()=>IQ,ISNA:()=>LQ,ISNONTEXT:()=>RQ,ISNUMBER:()=>zQ,ISTEXT:()=>BQ,NA:()=>HQ});let MQ=[{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.`)}],NQ={description:j(`Gets information about a cell.`),args:[B(`info_type (string)`,j(`The type of information requested.`),MQ),B(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=F(e).toLowerCase();if(!MQ.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,MQ.join(`, `)));let r=L(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`:Xs(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},PQ={description:j(`Whether a value is an error other than #N/A.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Ja(t)&&t!==M.NotAvailable},isExported:!0},FQ={description:j(`Whether a value is an error.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Ja(t)},isExported:!0},IQ={description:j("Whether a value is `true` or `false`."),args:[B(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},LQ={description:j(`Whether a value is the error #N/A.`),args:[B(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},RQ={description:j(`Whether a value is non-textual.`),args:[B(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!BQ.compute.bind(this)(e)},isExported:!0},zQ={description:j(`Whether a value is a number.`),args:[B(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},BQ={description:j(`Whether a value is text.`),args:[B(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&Ja(e?.value)===!1},isExported:!0},VQ={description:j(`Whether the referenced cell is empty`),args:[B(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},HQ={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},UQ={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[B(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Ba(Za):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var WQ=l({AND:()=>GQ,FALSE:()=>KQ,IF:()=>qQ,IFERROR:()=>JQ,IFNA:()=>YQ,IFS:()=>XQ,NOT:()=>ZQ,OR:()=>QQ,SWITCH:()=>$Q,TRUE:()=>e$,XOR:()=>t$});let GQ={description:j("Logical `and` operator."),args:[B(`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}=Px(e);return n?t:new N(Fo)},isExported:!0},KQ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},qQ={description:j(`Returns value depending on logical expression.`),args:[B(`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.`)),B(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),B(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Xx(e)?lc(this,bc.get(`IF`),[e,t,n]):(I(Jx(e))?t:n)??{value:0}},isExported:!0},JQ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[B(`value (any, range)`,j(`The value to return if value itself is not an error.`)),B(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Xx(e)?lc(this,bc.get(`IFERROR`),[e,t]):(Ja(Jx(e)?.value)?t:e)??{value:0}},isExported:!0},YQ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[B(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),B(`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 Xx(e)?lc(this,bc.get(`IFNA`),[e,t]):(Jx(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},XQ={description:j(`Returns a value depending on multiple logical expressions.`),args:[B(`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.`)),B(`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(Xx(e[0]))return lc(this,bc.get(`IFS`),e);let t=I(Jx(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},ZQ={description:j(`Returns opposite of provided logical value.`),args:[B(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!I(e)},isExported:!0},QQ={description:j("Logical `or` operator."),args:[B(`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}=Fx(e);return n?t:new N(Fo)},isExported:!0},$Q={description:j(`Returns a value by comparing cases to an expression.`),args:[B(`expression (number, boolean, string)`,j(`The value to be checked.`)),B(`case (any, repeating)`,j(`Case to be checked against expression.`)),B(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),B(`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?Ya(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&Ja(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},e$={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},t$={description:j("Logical `xor` operator."),args:[B(`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 Co(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Fo)},isExported:!0};function n$(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function r$(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 i$(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function a$(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=Yn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Ba;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&sr(D(e.__originCellPosition),n))throw new za;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 o$=l({ADDRESS:()=>l$,CHOOSE:()=>E$,COLUMN:()=>u$,COLUMNS:()=>d$,DROP:()=>D$,FORMULATEXT:()=>k$,HLOOKUP:()=>f$,INDEX:()=>p$,INDIRECT:()=>m$,LOOKUP:()=>h$,MATCH:()=>g$,OFFSET:()=>T$,PIVOT:()=>w$,PIVOT_HEADER:()=>C$,PIVOT_VALUE:()=>S$,ROW:()=>_$,ROWS:()=>v$,TAKE:()=>O$,VLOOKUP:()=>y$,XLOOKUP:()=>x$});let s$=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],c$=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],l$={description:j(`Returns a cell reference as a string. `),args:[B(`row (number)`,j(`The row number of the cell reference. `)),B(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),B(`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)`)}]),B(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),s$),B(`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=io(e,this.locale),o=io(t,this.locale);if(a<1)return new N(Ux(a));if(o<1)return new N(Ux(o));let s=io(n,this.locale);if(![1,2,3,4].includes(s))return new N(Qa(1,4,s));let c=I(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:Pc(F(i),l)},isExported:!0},u$={description:j(`Column number of a specified cell.`),args:[B(`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=L(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 Ba(Za);let r=n.position.col;return t.length===1?r+1:vo(t.length,1,e=>({value:r+e+1}))},isExported:!0},d$={description:j(`Number of columns in a specified array or range.`),args:[B(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=L(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},f$={description:j(`Horizontal lookup`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),B(`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.`),c$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(P(n?.value,this.locale)),a=L(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[I(r.value)?Oo(a,e,`nextSmaller`,`asc`,a.length,o):ko(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ya(e):s[i-1]},isExported:!0},p$={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[B(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),B(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),B(`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=L(e),i=P(t.value,this.locale),a=P(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},m$={description:j(`Returns the content of a cell, specified by a string.`),args:[B(`reference (string)`,j(`The range of cells from which the values are returned.`)),B(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),s$)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Ba(j(`Reference should be defined.`));if(!I(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 Ba;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},h$={description:j(`Look up a value.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`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=L(t),i=L(n),a=r.length,o=r[0].length,s=o>=a,c=Oo(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?Ya(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},g$={description:j(`Position of item in range that matches value.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`range (any, range)`,j(`The one-dimensional array to be searched.`)),B(`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=P(n,this.locale),i=L(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=Oo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=ko(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=Oo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ya(e):s+1},isExported:!0},_$={description:j(`Row number of a specified cell.`),args:[B(`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=L(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 Ba(Za);let r=n.position.row;return t[0].length===1?r+1:vo(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},v$={description:j(`Number of rows in a specified array or range.`),args:[B(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=L(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},y$={description:j(`Vertical lookup.`),args:[B(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),B(`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.`)),B(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),B(`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.`),c$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(P(n?.value,this.locale)),a=L(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=I(r.value)?Oo(a,e,`nextSmaller`,`asc`,a[0].length,o):ko(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ya(e):c},isExported:!0},b$={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},x$={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[B(`search_key (string,number,boolean)`,j(`The value to search for.`)),B(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),B(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),B(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),B(`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`)}]),B(`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(P(i.value,this.locale)),s=Math.trunc(P(a.value,this.locale)),c=L(t),l=L(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=b$[o],m=s===-1,h=s===2||s===-2?Oo(c,e,p,s===2?`asc`:`desc`,f,d):ko(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ya(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},S$={description:j(`Get the value from a pivot.`),args:[B(`pivot_id (number,string)`,j(`ID of the pivot.`)),B(`measure_name (string)`,j(`Name of the measure.`)),B(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),B(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=F(e),i=F(t),a=n$(r,this.getters);r$(a,i,this.getters),i$(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);a$(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)}},C$={description:j(`Get the header of a pivot.`),args:[B(`pivot_id (number,string)`,j(`ID of the pivot.`)),B(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),B(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=F(e),r=n$(n,this.getters);i$(t);let i=this.getters.getPivot(r);a$(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(F(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}}},w$={description:j(`Get a pivot table.`),args:[B(`pivot_id (string)`,j(`ID of the pivot.`)),B(`row_count (number, optional)`,j(`number of rows`)),B(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),B(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),B(`column_count (number, optional)`,j(`number of columns`)),B(`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=n$(F(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=iC(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.`));a$(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(x_(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(YS(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}},T$={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[B(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),B(`offset_rows (number)`,j(`The number of rows to offset by.`)),B(`offset_columns (number)`,j(`The number of columns to offset by.`)),B(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),B(`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 Ba(Za);let a=L(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 Ba(Za);let s=a[0].length,c=a.length;if(r){let e=P(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=P(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=P(t,this.locale),u=P(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 Ba(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 Ba:(d&&this.addDependencies?.(d,[g]),vo(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},E$={description:j(`Returns an element from a list of choices based on index.`),args:[B(`index (number)`,j(`Which choice to return.`)),B(`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(P(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},D$={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[B(`array (range)`,j(`The array from which to drop rows or columns`)),B(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),B(`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=P(t,this.locale),i=P(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},O$={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[B(`array (range)`,j(`The array from which to take rows or columns.`)),B(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),B(`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?P(t,this.locale):e[0].length,i=P(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},k$={description:j(`Returns a formula as a string.`),args:[B(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Ba(Za);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Va(j(`The cell does not contain a formula.`))},isExported:!0};var A$=l({ADD:()=>j$,CONCAT:()=>M$,DIVIDE:()=>N$,EQ:()=>L$,GT:()=>z$,GTE:()=>B$,LT:()=>V$,LTE:()=>H$,MINUS:()=>U$,MULTIPLY:()=>W$,NE:()=>G$,POW:()=>K$,SPILLED_RANGE:()=>q$,UMINUS:()=>J$,UNARY_PERCENT:()=>Y$,UPLUS:()=>X$});let j$={description:j(`Sum of two numbers.`),args:[B(`value1 (number)`,j(`The first addend.`)),B(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:P(e,this.locale)+P(t,this.locale),format:e?.format||t?.format}}},M$={description:j(`Concatenation of two values.`),args:[B(`value1 (string)`,j(`The value to which value2 will be appended.`)),B(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return F(e)+F(t)},isExported:!0},N$={description:j(`One number divided by another.`),args:[B(`dividend (number)`,j(`The number to be divided.`)),B(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=P(t,this.locale);return n===0?new Wa(j(`The divisor must be different from zero.`)):{value:P(e,this.locale)/n,format:e?.format||t?.format}}};function P$(e){return e===void 0||e.value===null}let F$={number:0,string:``,boolean:!1};function I$(e,t,n=2e-16){return Math.abs(e-t)<n}let L$={description:j(`Equal.`),args:[B(`value1 (string, number, boolean)`,j(`The first value.`)),B(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(Ja(e?.value))return e;if(Ja(t?.value))return t;let n=P$(e)?F$[typeof t?.value]:e?.value,r=P$(t)?F$[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:I$(n,r)}:{value:n===r}}};function R$(e,t,n){if(Ja(e?.value))return e;if(Ja(t?.value))return t;let r=P$(e)?F$[typeof t?.value]:e?.value,i=P$(t)?F$[typeof e?.value]:t?.value;typeof r!=`number`&&(r=F(r).toUpperCase()),typeof i!=`number`&&(i=F(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 z$={description:j(`Strictly greater than.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return R$(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!I$(e,t)&&e>t:e>t)}},B$={description:j(`Greater than or equal to.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return R$(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?I$(e,t)||e>t:e>=t)}},V$={description:j(`Less than.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=B$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},H$={description:j(`Less than or equal to.`),args:[B(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),B(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=z$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},U$={description:j(`Difference of two numbers.`),args:[B(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),B(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:P(e,this.locale)-P(t,this.locale),format:e?.format||t?.format}}},W$={description:j(`Product of two numbers`),args:[B(`factor1 (number)`,j(`The first multiplicand.`)),B(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:P(e,this.locale)*P(t,this.locale),format:e?.format||t?.format}}},G$={description:j(`Not equal.`),args:[B(`value1 (string, number, boolean)`,j(`The first value.`)),B(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=L$.compute.bind(this)(e,t);return Ja(n.value)?n:{value:!n.value}}},K$={description:j(`A number raised to a power.`),args:[B(`base (number)`,j(`The number to raise to the exponent power.`)),B(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return jq.compute.bind(this)(e,t)}},q$={description:j(`Gets the spilled range of an array formula.`),args:[B(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Ba(Za);let t=L(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(Ja(n.value))return n;if(n.position===void 0)return new Ba(Za);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Ba;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),vo(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},J$={description:j(`A number with the sign reversed.`),args:[B(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-P(e,this.locale),format:e?.format}}},Y$={description:j(`Value interpreted as a percentage.`),args:[B(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return P(e,this.locale)/100}},X$={description:j(`A specified number, unchanged.`),args:[B(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Z$={transform:e=>e,inverseTransform:e=>e},Q$=1e-10,$$=.0254,e1=$$/72,t1=.3048,n1=.9144,r1=1609.34,i1=1852,a1=946073047258e4,o1={g:{...Z$,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:{...Z$,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(Q$),category:`distance`},Picapt:{...$(e1),category:`distance`},pica:{...$($$/6),category:`distance`},in:{...$($$),category:`distance`},ft:{...$(t1),category:`distance`},yd:{...$(n1),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(r1),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(i1),category:`distance`},ly:{...$(a1),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...Z$,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...Z$,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:{...Z$,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...Z$,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:{...Z$,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...Z$,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...Z$,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":{...Z$,category:`volume`,order:3},"ang^3":{...$(Q$**3),category:`volume`,order:3},"Picapt^3":{...$(e1**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$($$**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":{...$(t1**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(n1**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(r1**3),category:`volume`,order:3},"Nmi^3":{...$(i1**3),category:`volume`,order:3},"ly^3":{...$(a1**3),category:`volume`,order:3},"m^2":{...Z$,category:`area`,order:2},"ang^2":{...$(Q$**2),category:`area`,order:2},"Picapt^2":{...$(e1**2),category:`area`,order:2},"in^2":{...$($$**2),category:`area`,order:2},"ft^2":{...$(t1**2),category:`area`,order:2},"yd^2":{...$(n1**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":{...$(r1**2),category:`area`,order:2},"Nmi^2":{...$(i1**2),category:`area`,order:2},"ly^2":{...$(a1**2),category:`area`,order:2},bit:{...Z$,category:`information`},byte:{...$(8),category:`information`},"m/s":{...Z$,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`}},s1={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`},c1={"":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},l1={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`)},u1=Object.entries(o1).map(([e,t])=>({value:e,label:d1(t.category)}));function d1(e){return l1[e]??``}function f1(e){for(let[t,n]of Object.entries(c1)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=o1[r];if(!i&&s1[r]&&(i=o1[s1[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var p1=l({CONVERT:()=>m1});let m1={description:j(`Converts a numeric value to a different unit of measure.`),args:[B(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),B(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),u1),B(`end_unit (string)`,j(`The unit of measure into which to convert value`),u1)],compute:function(e,t,n){let r=P(e,this.locale),i=F(t),a=F(n),o=f1(i),s=f1(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')`,d1(o.category),d1(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 h1=l({CHAR:()=>y1,CLEAN:()=>b1,CONCATENATE:()=>x1,EXACT:()=>S1,FIND:()=>C1,FORMAT_LARGE_NUMBER:()=>w1,JOIN:()=>T1,LEFT:()=>E1,LEN:()=>D1,LOWER:()=>O1,MID:()=>k1,PROPER:()=>A1,REGEXEXTRACT:()=>M1,REGEXREPLACE:()=>N1,REGEXTEST:()=>j1,REPLACE:()=>P1,RIGHT:()=>F1,SEARCH:()=>I1,SPLIT:()=>L1,SUBSTITUTE:()=>R1,TEXT:()=>U1,TEXTAFTER:()=>G1,TEXTBEFORE:()=>K1,TEXTJOIN:()=>z1,TEXTSPLIT:()=>B1,TRIM:()=>V1,UPPER:()=>H1,VALUE:()=>W1});let g1=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,_1=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],v1=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],y1={description:j(`Gets character associated with number.`),args:[B(`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(P(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},b1={description:j(`Remove non-printable characters from a piece of text.`),args:[B(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=F(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},x1={description:j(`Appends strings to one another.`),args:[B(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ho(e,(e,t)=>e+F(t),``)},isExported:!0},S1={description:j(`Tests whether two strings are identical.`),args:[B(`string1 (string)`,j(`The first string to compare.`)),B(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return F(e)===F(t)},isExported:!0},C1={description:j(`First position of string found in text, case-sensitive.`),args:[B(`search_for (string)`,j(`The string to look for within text_to_search.`)),B(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),B(`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=F(e),i=F(t),a=P(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},w1={description:j(`Apply a large number format`),args:[B(`value (number)`,j(`The number.`)),B(`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:P(e,this.locale),format:Hs(e,t,this.locale)}}},T1={description:j(`Concatenates elements of arrays with delimiter.`),args:[B(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),B(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=F(e);return ho(t,(e,t)=>(e?e+n:``)+F(t),``)}},E1={description:j(`Substring from beginning of specified string.`),args:[B(`text (string)`,j(`The string from which the left portion will be returned.`)),B(`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?P(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):F(e).substring(0,n)},isExported:!0},D1={description:j(`Length of a string.`),args:[B(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return F(e).length},isExported:!0},O1={description:j(`Converts a specified string to lowercase.`),args:[B(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return F(e).toLowerCase()},isExported:!0},k1={description:j(`A segment of a string.`),args:[B(`text (string)`,j(`The string to extract a segment from.`)),B(`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.`)),B(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=F(e),i=P(t,this.locale),a=P(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},A1={description:j(`Capitalizes each word in a specified string.`),args:[B(`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 F(e).replace(g1,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},j1={description:j(`Checks whether a string matches the supplied regular expression.`),args:[B(`text (string)`,j(`The string to test.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`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=F(e),i=F(t),a=P(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},M1={description:j(`Extract text from a string based on the supplied regular expression.`),args:[B(`text (string)`,j(`The string on which you want to extract text.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`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`)}]),B(`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=F(e),a=F(t),o=P(n,this.locale),s=P(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},N1={description:j(`Replace text in a string based on the supplied regular expression.`),args:[B(`text (string)`,j(`The string in which you want to replace text.`)),B(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),B(`replacement (string)`,j(`The text to use as the replacement.`)),B(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),B(`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=F(e),o=F(t),s=F(n),c=P(r,this.locale),l=P(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},P1={description:j(`Replaces part of a text string with different text.`),args:[B(`text (string)`,j(`The text, a part of which will be replaced.`)),B(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),B(`length (number)`,j(`The number of characters in the text to be replaced.`)),B(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=P(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=F(e),o=P(n,this.locale),s=F(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},F1={description:j(`A substring from the end of a specified string.`),args:[B(`text (string)`,j(`The string from which the right portion will be returned.`)),B(`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?P(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=F(e),i=r.length;return r.substring(i-n,i)},isExported:!0},I1={description:j(`First position of string found in text, ignoring case.`),args:[B(`search_for (string)`,j(`The string to look for within text_to_search.`)),B(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),B(`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=F(e).toLowerCase(),i=F(t).toLowerCase(),a=P(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},L1={description:j(`Split text by specific character delimiter(s).`),args:[B(`text (string)`,j(`The text to divide.`)),B(`delimiter (string)`,j(`The character or characters to use to split text.`)),B(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),B(`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=F(e),a=St(F(t)),o=I(n),s=I(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!==``)),xo([l])},isExported:!1},R1={description:j(`Replaces existing text with new text in a string.`),args:[B(`text_to_search (string)`,j(`The text within which to search and replace.`)),B(`search_for (string)`,j(`The string to search for within text_to_search.`)),B(`replace_with (string)`,j(`The string that will replace search_for.`)),B(`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=P(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=F(e),o=F(t);if(o===``)return a;let s=F(n),c=new RegExp(St(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},z1={description:j(`Combines text from multiple strings and/or arrays.`),args:[B(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),B(`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)`)}]),B(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=F(e),i=I(t),a=0;return ho(n,(e,t)=>i&&F(t)===``?e:(a++?e+r:``)+F(t),``)},isExported:!0},B1={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[B(`text (string)`,j(`The text to split.`)),B(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),B(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),B(`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`)}]),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`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 Va){let o=F(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=L(t).flat().map(e=>St(F(e))),c=L(n).flat().map(e=>St(F(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=I(r),u=P(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 xo(d)},isExported:!0},V1={description:j(`Removes space characters.`),args:[B(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return un(F(e))},isExported:!0},H1={description:j(`Converts a specified string to uppercase.`),args:[B(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return F(e).toUpperCase()},isExported:!0},U1={description:j(`Converts a number to text according to a specified format.`),args:[B(`number (number)`,j(`The number, date or time to format.`)),B(`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 z(P(e,this.locale),{format:F(t),locale:this.locale})},isExported:!0},W1={description:j(`Converts a string to a numeric value.`),args:[B(`value (number)`,j(`the string to be converted`))],compute:function(e){return P(e,this.locale)},isExported:!0},G1={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[B(`text (string)`,j(`The source text.`)),B(`delimiter (string)`,j(`The substring after which text will be returned.`)),B(`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.`)),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),v1),B(`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 Va){let o=F(e),s=P(n,this.locale),c=P(r,this.locale),l=P(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=F(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=St(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},K1={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[B(`text (string)`,j(`The source text.`)),B(`delimiter (string)`,j(`The substring after which text will be returned.`)),B(`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.`)),B(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),_1),B(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),v1),B(`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 Va){let o=F(e),s=P(n,this.locale),c=P(r,this.locale),l=P(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=F(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=St(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 q1=l({HYPERLINK:()=>J1});let J1={description:j(`Creates a hyperlink in a cell.`),args:[B(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),B(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=F(e).trim(),r=F(t)||n;return n===``?r:Ft(r,n)},isExported:!0},Y1=[{name:j(`Array`),functions:dK},{name:j(`Database`),functions:gY},{name:j(`Date`),functions:MX},{name:j(`Filter`),functions:gZ},{name:j(`Financial`),functions:SZ},{name:j(`Info`),functions:jQ},{name:j(`Lookup`),functions:o$},{name:j(`Logical`),functions:WQ},{name:j(`Math`),functions:VK},{name:j(`Operator`),functions:A$},{name:j(`Statistical`),functions:rJ},{name:j(`Text`),functions:h1},{name:j(`Engineering`),functions:mZ},{name:j(`Web`),functions:q1},{name:j(`Parser`),functions:p1}];for(let e of Y1){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),bc.add(n,{isExported:!1,...r})}}let X1={},Z1={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},Q1={autoCompleteProviders:Mk,autofillModifiersRegistry:wz,autofillRulesRegistry:Tz,cellMenuRegistry:lI,colMenuRegistry:wI,errorTypes:La,functionRegistry:bc,featurePluginRegistry:wV,iconsOnCellRegistry:iz,statefulUIPluginRegistry:TV,coreViewsPluginRegistry:EV,corePluginRegistry:CV,rowMenuRegistry:jI,sidePanelRegistry:kP,figureRegistry:o_,chartSidePanelComponentRegistry:iA,chartDataSourceSidePanelComponentRegistry:eE,chartComponentRegistry:_g,chartTypeRegistry:ib,chartSubtypeRegistry:ng,chartDataSourceRegistry:rb,topbarMenuRegistry:QV,topbarComponentRegistry:_H,topBarToolBarRegistry:vU,clickableCellRegistry:DV,otRegistry:Yz,inverseCommandRegistry:AV,urlRegistry:nd,cellPopoverRegistry:zC,numberFormatMenuRegistry:JV,repeatLocalCommandTransformRegistry:JB,repeatCommandTransformRegistry:qB,clipboardHandlersRegistries:SL,pivotRegistry:xN,pivotTimeAdapterRegistry:mS,pivotSidePanelRegistry:IN,pivotNormalizationValueRegistry:KS,supportedPivotPositionalFormulaRegistry:tR,pivotToFunctionValueRegistry:qS,migrationStepRegistry:dC,chartJsExtensionRegistry:Wr,onIterationEndEvaluationRegistry:JR,specificRangeTransformRegistry:Xz},$1={arg:B,isEvaluationError:Ja,toBoolean:I,toJsDate:co,toNumber:P,toString:F,toNormalizedPivotValue:HS,toFunctionPivotValue:WS,toXC:E,toZone:Wn,toUnboundedZone:Un,toCartesian:Mn,numberToLetters:Cn,lettersToNumber:wn,UuidGenerator:G,formatValue:z,createCurrencyFormat:Fs,ColorGenerator:Gf,computeTextWidth:Nd,createEmptyWorkbookData:jC,createEmptySheet:AC,createEmptyExcelSheet:MC,doesCellContainFunction:xn,rgbaToHex:_f,colorToRGBA:vf,positionToZone:D,isDefined:w,isMatrix:gt,lazy:Kt,genericRepeat:gH,createAction:xe,createActions:ve,transformRangeData:Nr,deepEquals:T,overlap:ir,union:er,isInside:or,deepCopy:x,expandZoneOnInsertion:Xn,reduceZoneOnDeletion:$n,unquote:Tt,getMaxObjectId:PS,getFirstPivotFunction:EN,getNumberOfPivotFunctions:ON,parseDimension:LS,isDateOrDatetimeField:RS,makeFieldProposal:kN,periodYearToComparable:pS,insertTokenAfterArgSeparator:jN,insertTokenAfterLeftParenthesis:MN,mergeContiguousZones:Ar,getPivotHighlights:vM,pivotTimeAdapter:hS,UNDO_REDO_PIVOT_COMMANDS:xz,createPivotFormula:VS,areDomainArgsFieldsValid:BS,splitReference:Nc,sanitizeSheetName:Dt,getUniqueText:vn,isNumber:Ta,isDateTime:qi,createCustomFields:$S,schemeToColorScale:cC,isDateTimeFormat:Os,jsDateToNumber:sa,numberToJsDate:aa,DateTime:Ni,parseFormat:Qo,isFormula:yn,domainToColRowDomain:KM,collapseHierarchicalDisplayName:aC,getCanonicalSymbolName:Et,fuzzyLookup:jk,replaceSymbolInFormula:fu},e0={isMarkdownLink:Nt,parseMarkdownLink:It,markdownLink:Ft,openLink:sd,urlRepresentation:od},t0={Checkbox:tE,Section:Z,Select:t_,RoundColorPicker:OE,ChartDataSeries:pE,ChartErrorSection:_E,ChartLabelRange:mE,ChartRangeDataSourceComponent:UO,ChartTitle:TE,ChartPanel:cA,ChartFigure:i_,ChartJsComponent:Qm,ClickableCellSortIcon:nR,ZoomableChartJsComponent:lg,Grid:eR,GridOverlay:OL,ScorecardChart:yh,GaugeChartComponent:hg,LineConfigPanel:Uk,BarConfigPanel:yE,PieChartDesignPanel:Kk,GenericChartConfigPanel:vE,ChartWithAxisDesignPanel:FE,GenericZoomableChartDesignPanel:IE,LineChartDesignPanel:Wk,GaugeChartConfigPanel:sk,GaugeChartDesignPanel:Rk,ScorecardChartConfigPanel:Yk,ScorecardChartDesignPanel:Xk,GeoChartDesignPanel:Vk,RadarChartDesignPanel:qk,WaterfallChartDesignPanel:rA,ComboChartDesignPanel:ik,FunnelChartDesignPanel:ok,SunburstChartDesignPanel:Zk,TreeMapChartDesignPanel:nA,ChartTypePicker:oA,FigureComponent:s_,MenuPopover:e_,Popover:Xg,SelectionInput:fE,StandaloneComposer:Lk,ValidationMessages:gE,AddDimensionButton:PM,PivotDimensionGranularity:IM,PivotDimensionOrder:LM,PivotDimension:jM,PivotLayoutConfigurator:VM,PivotHTMLRenderer:iR,PivotDeferUpdate:bM,PivotTitleSection:HM,CogWheelMenu:QT,TextInput:GT,SidePanelCollapsible:xE,RadioSelection:DE,GeoChartRegionSelectSection:zk,ChartDashboardMenu:n_,FullScreenFigure:rR,NumberInput:SE,TopBar:yU,Composer:vk},n0={useDragAndDropListItems:LT,useHighlights:dA,useHighlightsOnHover:uA},r0={Component:k,useExternalListener:mi,EnvPlugin:gi,App:xi},i0={useStoreProvider:Ti,DependencyContainer:Ci,CellPopoverStore:BC,ComposerFocusStore:Ur,CellComposerStore:cL,FindAndReplaceStore:QA,HighlightStore:lE,DelayedHoveredCellStore:c_,HoveredTableStore:TL,ModelStore:Ir,NotificationStore:Nk,RendererStore:Br,SelectionInputStore:dE,SpreadsheetStore:Vr,useStore:A,useLocalStore:Ei,SidePanelStore:jP,PivotSidePanelStore:PN,PivotMeasureDisplayPanelStore:gM,ClientFocusStore:NI,GridRenderer:LL};function a0(e,t){return bc.add(e,t),{addFunction:(e,t)=>a0(e,t)}}let o0={DEFAULT_LOCALE:R,HIGHLIGHT_COLOR:De,PIVOT_STATIC_TABLE_CONFIG:ct,PIVOT_INSERT_TABLE_STYLE_ID:lt,ChartTerms:f_,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:sC,DARK_MODE_FILTER_STRING:kf},s0={...HO,...aR};e.AbstractCellClipboardHandler=LB,e.AbstractChart=$m,e.AbstractFigureClipboardHandler=AG,e.BadExpressionError=Ra,e.CHART_TYPES=sC,e.CellErrorType=M,e.CellValueType=Pu,e.CircularDependencyError=za,e.ClientDisconnectedError=jB,e.ClipboardMIMEType=VC,e.CommandResult=ed,e.CompiledFormula=Du,e.CorePlugin=U_,e.CoreViewPlugin=PP,e.DEFAULT_LOCALE=R,e.DEFAULT_LOCALES=Lo,e.DEFAULT_LOCALE_DIGIT_GROUPING=`[3,0]`,e.DIRECTION=vt,e.DispatchResult=Qu,e.DivisionByZeroError=Wa,e.EvaluationError=N,e.InvalidReferenceError=Ba,e.LocalTransportService=vH,e.Model=DG,e.NEXT_VALUE=u_,e.NotAvailableError=Va,e.NumberTooLargeError=Ga,e.OrderedLayers=Rr,e.PREVIOUS_VALUE=l_,e.PivotRuntimeDefinition=xM,e.Registry=O,e.Revision=AB,e.SPREADSHEET_DIMENSIONS=Z1,e.SplillBlockedError=Ua,e.Spreadsheet=SU,e.SpreadsheetPivotTable=lN,e.UIPlugin=Iz,e.UnknownFunctionError=Ha,e.__info__=X1,e.addFunction=a0,e.addRenderingLayer=zr,e.astToFormula=iL,e.availableConditionalFormatOperators=LA,e.availableDataValidationOperators=YA,e.availableFiltersOperators=CM,e.borderPositions=_t,e.borderStyles=ht,e.canExecuteInReadonly=Zu,e.categories=Y1,e.chartHelpers=s0,e.compatibility=r0,e.components=t0,e.composerFocusTypes=yt,e.constants=o0,e.convertAstNodes=Ol,e.coreTypes=Yu,e.createAutocompleteArgumentsProvider=qG,e.errorTypes=La,e.filterDateCriterionOperators=EM,e.filterNumberCriterionOperators=TM,e.filterTextCriterionOperators=wM,e.findCellInNewZone=_r,e.functionCache=Tu,e.getCaretDownSvg=sy,e.getCaretUpSvg=cy,e.helpers=$1,e.hooks=n0,e.invalidSubtotalFormulasCommands=Ku,e.invalidateBordersCommands=Gu,e.invalidateCFEvaluationCommands=Wu,e.invalidateChartEvaluationCommands=Hu,e.invalidateDependenciesCommands=Uu,e.invalidateEvaluationCommands=Vu,e.isCoreCommand=Xu,e.isHeadersDependant=Iu,e.isMatrix=gt,e.isPositionDependent=zu,e.isRangeDependant=Ru,e.isSheetDependent=Fu,e.isTargetDependent=Lu,e.isZoneDependent=Bu,e.iterateAstNodes=kl,e.links=e0,e.load=gC,e.lockedSheetAllowedCommands=Ju,e.parse=El,e.parseTokens=Dl,e.readonlyAllowedCommands=qu,e.registries=Q1,e.schemeToColorScale=cC,e.setDefaultSheetViewSize=ot,e.setTranslationMethod=Pa,e.stores=i0,e.tokenColors=mt,e.tokenize=Gc,X1.version=`19.4.0-alpha.13`,X1.date=`2026-06-06T09:34:53.140Z`,X1.hash=`af3c199`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);