@odoo/o-spreadsheet 15.2.5 → 15.2.7
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"use strict";function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var o=s(t);let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const s=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>s[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const r=function(e,...t){return n(i(e),...t)},a=function(e,...t){return{toString:function(){return n(i(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=11982760,m=26,v=48,E=63,b=96,S=23,C=15,w=14,y=4,I=200,x=1,T="400",R=10,L="'Roboto', arial",M=["thin","#000"],A="#00f",_=/[ymd:]/,O="#REF",N="START_REVISION",k=a("Invalid expression"),F=["'","*","?","/","\\","[","]"],$=/'|\*|\?|\/|\\|\[|\]/,D=void 0,P="|",U=2e3,V=(new Date).getFullYear(),B=new Date(1899,11,30),H=new Date(0)-B,z=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Z=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,G=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function W(e){let t;const s=(e=e.trim()).match(G);if(s){if(t=function(e){if(e=e.trim(),G.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,r,a,l)}}return null}(s[0]),null===t)return null;e=e.replace(s[0],"").trim()}let o;const i=e.match(z),n=e.match(Z);if(i||n){let t;if(i?(t=i[0],o=q(t,"mdy")):(t=n[0],o=q(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function q(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),o=s?0:1,i=s?1:2,n=s?2:0,r=Number(t[o]),a=Number(t[i]),l=2===t[o].length&&r<10||2===t[i].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return U+t;case 2:return U+(U+t>V+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):V,h=new Date(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h-B;let p=l?`mm${d}dd`:`m${d}d`;return t[n]&&(p=s?p+d+"yyyy":"yyyy"+d+p),{value:Math.round(u/864e5),format:p,jsDate:h}}return null}function j(e){const t=Math.trunc(e);let s=new Date(86400*t*1e3-H),o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function X(e){const t=e.format,s=e.jsDate||j(e.value),o=t.indexOf("h");let i="",n="";return o>0?(i=Y(s,t.substring(0,o-1)),n=K(s,t.substring(o))):0===o?n=K(s,t):o<0&&(i=Y(s,t)),i+(i&&n?" ":"")+n}function Y(e,t){const s=t.match(/\/|-|\s/)[0];return t.split(s).map((s=>{switch(s){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(s)}function K(e,t){let s=t.split(/:|\s/);const o=e.getHours(),i="a"===s[s.length-1];let n=o,r="";return i&&(n=0===n?12:n>12?n-12:n,r=o>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-B)/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}const Q=/(^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?)(?!\w|!)/,J=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function ee(e){return J.test(e.trim())}const te=/,/g;function se(e){let t=Number(e.replace(te,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const oe=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function ie(e){return Number.isInteger(e)?e.toString():oe.format(e)}let ne=[];const re=20;function ae(e,t,s=""){if(e<0)return"-"+ae(-e,t);const o=t>=re?re:t;let i=ne[o];i||(i=new Intl.NumberFormat("en-US",{minimumFractionDigits:o,maximumFractionDigits:o,useGrouping:!1}),ne[o]=i);let n=i.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,o)=>e<0||o<e?`${t}${s}`:t))}return n}function le(e,t){const s=t.split("."),o=1===s.length?0:s[1].match(/0/g).length,i=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=ae(e,o,i);return n?r+"%":r}function ce(e,t){if(!e())throw new Error(t)}const he=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function de(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(ee(e)||""===e)return se(e);const t=W(e);if(t)return t.value;throw new Error(he(e));default:return 0}}function ue(e){if(""===e)throw new Error(he(e));return de(e)}function pe(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ge=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function fe(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(ge(e))}return!1;case"number":return!!e;default:return!1}}function me(e){return j(de(e))}function ve(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function Ee(e,t){ve(e,t,t)}function be(e,t){ve(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(ue(e))}))}function Se(e,t,s,o){let i=o;for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)i=t(i,o[s][n])}else i=s(i,o);return i}function Ce(e,t,s){return Se(e,t,t,s)}function we(e,t,s){return Se(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,ue(s))),s)}function ye(e,t,s){return Se(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?de(s):0):e),((e,s)=>t(e,de(s))),s)}function Ie(e,t){return function(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]))return}else if(!s(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ge(e));return fe(e)}(e))))}function xe(e,t){let s,o,i=e.substring(0,2);"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),ee(o)?o=de(o):"TRUE"!==o&&"FALSE"!==o||(o=fe(o));const n={operator:s,operand:o};return"string"==typeof o&&(t&&(o+="*"),n.regexp=function(e){let t="",s="";for(let o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}(o)),n}function Te(e,t){const{operator:s,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===s)return pe(e)===pe(o);if("<>"===s||"="===s){let i;return i=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===s?i:!i}if(typeof e==typeof o)switch(s){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Re(e,t,s=!1){const o=e.length;if(o%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const i=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==i||o[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=pe(e[t+1]);r.push(xe(l,s))}for(let s=0;s<i;s++)for(let i=0;i<n;i++){let n=!0;for(let t=0;t<o-1;t+=2){if(n=Te(e[t][s][i],r[t/2]),!n)break}n&&t(s,i)}}function Le(e,t){if(void 0===t)return-1;const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t<e[c])return-1;if(typeof e[h]===s&&e[h]<=t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a<=t&&(void 0===o||o<a||o===a&&i<r)&&(o=a,i=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==i?i:-1}class Me{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}remove(e){delete this.content[e]}}const Ae=/(.*?)\((.*?)\)(.*)/,_e=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Oe(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(Ne(e));return s}function Ne(e){let t,s=e.match(Ae),o=s[1].trim(),i=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let o=_e.find((e=>s===e));o?i.push(o):"RANGE<ANY>"===s?i.push("RANGE"):"OPTIONAL"===s?n=!0:"REPEATING"===s?r=!0:"LAZY"===s?a=!0:s.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:o,description:s[3].trim(),type:i};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function ke(e){let t=0,s=0,o=0;for(let i of e.args)t++,i.optional||i.repeating||i.default||s++,i.repeating&&o++;const i=e;return i.minArgRequired=s,i.maxArgPossible=o?1/0:t,i.nbrArgRepeating=o,i.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const s=e-t;return e=>{if(e<=s)return e;return s+((e-s)%t||t)}}(t,o),i}var Fe;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Fe||(Fe={}));const $e=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),De=new Set(["START","ACTIVATE_SHEET","COPY","START_SELECTION","SET_SELECTION","ALTER_SELECTION","START_SELECTION_EXPANSION","PREPARE_SELECTION_EXPANSION","STOP_SELECTION","RESIZE_VIEWPORT","SET_VIEWPORT_OFFSET","SELECT_ALL","SELECT_CELL","SELECT_COLUMN","SELECT_ROW","MOVE_POSITION","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY"]),Pe=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART"]);function Ue(e){return Pe.has(e.type)}class Ve{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Ve}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Be,He,ze,Ze;e.CommandResult=void 0,(Be=e.CommandResult||(e.CommandResult={}))[Be.Success=0]="Success",Be[Be.CancelledForUnknownReason=1]="CancelledForUnknownReason",Be[Be.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Be[Be.MergeIsDestructive=3]="MergeIsDestructive",Be[Be.CellIsMerged=4]="CellIsMerged",Be[Be.InvalidTarget=5]="InvalidTarget",Be[Be.EmptyUndoStack=6]="EmptyUndoStack",Be[Be.EmptyRedoStack=7]="EmptyRedoStack",Be[Be.NotEnoughElements=8]="NotEnoughElements",Be[Be.NotEnoughSheets=9]="NotEnoughSheets",Be[Be.MissingSheetName=10]="MissingSheetName",Be[Be.DuplicatedSheetName=11]="DuplicatedSheetName",Be[Be.DuplicatedSheetId=12]="DuplicatedSheetId",Be[Be.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Be[Be.WrongSheetMove=14]="WrongSheetMove",Be[Be.WrongSheetPosition=15]="WrongSheetPosition",Be[Be.InvalidAnchorZone=16]="InvalidAnchorZone",Be[Be.SelectionOutOfBound=17]="SelectionOutOfBound",Be[Be.TargetOutOfSheet=18]="TargetOutOfSheet",Be[Be.WrongPasteSelection=19]="WrongPasteSelection",Be[Be.EmptyClipboard=20]="EmptyClipboard",Be[Be.EmptyRange=21]="EmptyRange",Be[Be.InvalidRange=22]="InvalidRange",Be[Be.InvalidSheetId=23]="InvalidSheetId",Be[Be.InputAlreadyFocused=24]="InputAlreadyFocused",Be[Be.MaximumRangesReached=25]="MaximumRangesReached",Be[Be.InvalidChartDefinition=26]="InvalidChartDefinition",Be[Be.EmptyDataSet=27]="EmptyDataSet",Be[Be.InvalidDataSet=28]="InvalidDataSet",Be[Be.InvalidLabelRange=29]="InvalidLabelRange",Be[Be.InvalidAutofillSelection=30]="InvalidAutofillSelection",Be[Be.WrongComposerSelection=31]="WrongComposerSelection",Be[Be.MinBiggerThanMax=32]="MinBiggerThanMax",Be[Be.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",Be[Be.MidBiggerThanMax=34]="MidBiggerThanMax",Be[Be.MinBiggerThanMid=35]="MinBiggerThanMid",Be[Be.FirstArgMissing=36]="FirstArgMissing",Be[Be.SecondArgMissing=37]="SecondArgMissing",Be[Be.MinNaN=38]="MinNaN",Be[Be.MidNaN=39]="MidNaN",Be[Be.MaxNaN=40]="MaxNaN",Be[Be.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",Be[Be.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",Be[Be.MinInvalidFormula=43]="MinInvalidFormula",Be[Be.MidInvalidFormula=44]="MidInvalidFormula",Be[Be.MaxInvalidFormula=45]="MaxInvalidFormula",Be[Be.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",Be[Be.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",Be[Be.InvalidSortZone=48]="InvalidSortZone",Be[Be.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",Be[Be.MergeOverlap=50]="MergeOverlap",Be[Be.TooManyHiddenElements=51]="TooManyHiddenElements",Be[Be.Readonly=52]="Readonly",Be[Be.InvalidOffset=53]="InvalidOffset",Be[Be.InvalidViewportSize=54]="InvalidViewportSize",Be[Be.FigureDoesNotExist=55]="FigureDoesNotExist",Be[Be.DuplicatedFigureId=56]="DuplicatedFigureId",Be[Be.DuplicatedChartId=57]="DuplicatedChartId",Be[Be.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(He||(He={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(ze||(ze={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(Ze||(Ze={}));const Ge={description:a("Absolute value of a number."),args:Oe(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(de(e))},isExported:!0},We={description:a("Inverse cosine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},qe={description:a("Inverse hyperbolic cosine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},je={description:a("Inverse cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Xe={description:a("Inverse hyperbolic cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)>1),a("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ye={description:a("Inverse sine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ke={description:a("Inverse hyperbolic sine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(de(e))},isExported:!0},Qe={description:a("Inverse tangent of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(de(e))},isExported:!0},Je={description:a("Angle from the X axis to a point (x,y), in radians."),args:Oe(`\n x (number) ${a("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${a("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=de(e),o=de(t);return ce((()=>0!==s||0!==o),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,s)},isExported:!0},et={description:a("Inverse hyperbolic tangent of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},tt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.ceil(s/o)*o:0},isExported:!0},st={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.ceil(i/o)*o;return 0===de(s)?-Math.floor(Math.abs(i)/o)*o:-Math.ceil(Math.abs(i)/o)*o},isExported:!0},ot={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return st.compute(e,t,0)},isExported:!0},it={description:a("Cosine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(de(e))},isExported:!0},nt={description:a("Hyperbolic cosine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(de(e))},isExported:!0},rt={description:a("Cotangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},at={description:a("Hyperbolic cotangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},lt={description:a("Number of empty values."),args:Oe(`\n value1 (any, range) ${a("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${a("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},ct={description:a("A conditional count across a range."),args:Oe(`\n range (range) ${a("The range that is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0},ht={description:a("Count values depending on multiple criteria."),args:Oe(`\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0};function dt(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ut={description:a("Counts number of unique values in a range."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>dt(t)?e.add(t):e),new Set).size}},pt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=new Set;return Re(t,((t,o)=>{const i=e[t][o];dt(i)&&s.add(i)})),s.size}},gt={description:a("Cosecant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ft={description:a("Hyperbolic cosecant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},mt={description:a("Converts from another base to decimal."),args:Oe(`\n value (string) ${a("The number to convert.")},\n base (number) ${a("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let s=de(t);s=Math.floor(s),ce((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const o=pe(e);if(""===o)return 0;ce((()=>!!o.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",o,s.toString()));const i=parseInt(o,s);return ce((()=>!isNaN(i)),a("The value (%s) must be a valid base %s representation.",o,s.toString())),i},isExported:!0},vt={description:a("Converts an angle value in radians to degrees."),args:Oe(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*de(e)/Math.PI},isExported:!0},Et={description:a("Euler's number, e (~2.718) raised to a power."),args:Oe(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(de(e))},isExported:!0},bt={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.floor(s/o)*o:0},isExported:!0},St={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.floor(i/o)*o;return 0===de(s)?-Math.ceil(Math.abs(i)/o)*o:-Math.floor(Math.abs(i)/o)*o},isExported:!0},Ct={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return St.compute(e,t,0)},isExported:!0},wt={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},yt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return st.compute(e,t,0)},isExported:!0},It={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},xt={description:a("The logarithm of a number, base e (euler's number)."),args:Oe(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Tt={description:a("Modulo (remainder) operator."),args:Oe(`\n dividend (number) ${a("The number to be divided to find the remainder.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);ce((()=>0!==s),a("The divisor must be different from 0."));const o=de(e)%s;return o>0&&s<0||o<0&&s>0?o+s:o},isExported:!0},Rt={description:a("Rounds a number up to the nearest odd integer."),args:Oe(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Lt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Mt={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(e),o=de(t);return ce((()=>s>=0||Number.isInteger(o)),a("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(s,o)},isExported:!0},At={description:a("Result of multiplying a series of numbers together."),args:Oe(`\n factor1 (number, range<number>) ${a("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${a("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(s*=o,t+=1);else null!=o&&(s*=ue(o),t+=1);return 0===t?0:s},isExported:!0},_t={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Ot={description:a("Random integer between two values, inclusive."),args:Oe(`\n low (number) ${a("The low end of the random range.")}\n high (number) ${a("The high end of the random range.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){let s=de(e);Number.isInteger(s)||(s=Math.ceil(s));let o=de(t);return Number.isInteger(o)||(o=Math.floor(o)),ce((()=>s<=o),a("The high (%s) must be greater than or equal to the low (%s).",o.toString(),s.toString())),s+Math.ceil((o-s+1)*Math.random())-1},isExported:!0},Nt={description:a("Rounds a number according to standard rules."),args:Oe(`\n value (number) ${a("The value to round to places number of places.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},kt={description:a("Rounds down a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},Ft={description:a("Rounds up a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},$t={description:a("Secant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(de(e))},isExported:!0},Dt={description:a("Hyperbolic secant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(de(e))},isExported:!0},Pt={description:a("Sine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(de(e))},isExported:!0},Ut={description:a("Hyperbolic sine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(de(e))},isExported:!0},Vt={description:a("Positive square root of a positive number."),args:Oe(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);return ce((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Bt={description:a("Sum of a series of numbers and/or cells."),args:Oe(`\n value1 (number, range<number>) ${a("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${a("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){return we(e,((e,t)=>e+t),0)},isExported:!0},Ht={description:a("A conditional sum across a range."),args:Oe(`\n criteria_range (range) ${a("The range which is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${a("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return Re([e,t],((e,t)=>{const i=s[e][t];"number"==typeof i&&(o+=i)})),o},isExported:!0},zt={description:a("Sums a range depending on multiple criteria."),args:Oe(`\n sum_range (range) ${a("The range to sum.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges to check.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s+=i)})),s},isExported:!0},Zt={description:a("Tangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(de(e))},isExported:!0},Gt={description:a("Hyperbolic tangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(de(e))},isExported:!0},Wt={description:a("Truncates a number."),args:Oe(`\n value (number) ${a("The value to be truncated.")}\n places (number, default=0) ${a("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);return 0===o?Math.trunc(s):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(s*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var qt=Object.freeze({__proto__:null,ABS:Ge,ACOS:We,ACOSH:qe,ACOT:je,ACOTH:Xe,ASIN:Ye,ASINH:Ke,ATAN:Qe,ATAN2:Je,ATANH:et,CEILING:tt,CEILING_MATH:st,CEILING_PRECISE:ot,COS:it,COSH:nt,COT:rt,COTH:at,COUNTBLANK:lt,COUNTIF:ct,COUNTIFS:ht,COUNTUNIQUE:ut,COUNTUNIQUEIFS:pt,CSC:gt,CSCH:ft,DECIMAL:mt,DEGREES:vt,EXP:Et,FLOOR:bt,FLOOR_MATH:St,FLOOR_PRECISE:Ct,ISEVEN:wt,ISO_CEILING:yt,ISODD:It,LN:xt,MOD:Tt,ODD:Rt,PI:Lt,POWER:Mt,PRODUCT:At,RAND:_t,RANDBETWEEN:Ot,ROUND:Nt,ROUNDDOWN:kt,ROUNDUP:Ft,SEC:$t,SECH:Dt,SIN:Pt,SINH:Ut,SQRT:Vt,SUM:Bt,SUMIF:Ht,SUMIFS:zt,TAN:Zt,TANH:Gt,TRUNC:Wt});const jt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Xt(e){return e.toString(16).padStart(6,"0")}let Yt=0;function Kt(){return Yt=++Yt%jt.length,jt[Yt]}function Qt(e){return e.includes("rgb")?function(e){return e.slice(4,-1).split(",").map((e=>parseInt(e,10).toString(16).padStart(2,"0"))).join("").toUpperCase()}(e):(3===(e=e.replace("#","").toUpperCase()).length&&(e=e.split("").reduce(((e,t)=>e+t+t),"")),e)}const Jt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),es=new RegExp(/^\s*('.+'!|[^']+!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7})?$/,"i");function ts(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function ss(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):ss(Math.floor(e/26)-1)+ss(e%26)}function os(e){const t=(e=e.toUpperCase().trim()).match(Jt);if(null!==t){const[s,o,i]=t;if(s===e){const e=function(e){let t=0;const s=e.length;for(let o=0;o<s;o++)t+=(e.charCodeAt(o)-65+(o<s-1?1:0))*26**(s-o-1);return t}(o);return[e,parseInt(i,10)-1]}}throw new Error(`Invalid cell description: ${e}`)}function is(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+ss(e)+(s.rowFixed?"$":"")+String(t+1)}const ns=140,rs=20,as=.035;function ls(e){return rs+(ns-rs)*Math.exp(-as*(e-1))}const cs=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],hs={};for(let e of cs)hs[e.pt]=e.px;function ds(e){return JSON.stringify(e,Object.keys(e).sort())}function us(e){return'"'===e[0]&&'"'===e[e.length-1]?e.slice(1).slice(0,e.length-2):e}function ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const s in e)t[s]=gs(e[s]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function fs(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ms(e,t,s){return e<t?t:e>s?s:e}function vs(e,t,s){const o=s.italic?"italic ":"",i=s.bold?"bold":T,n=s.fontSize||R,r=hs[n];return e.font=`${o}${i} ${r}px ${L}`,e.measureText(t).width}function Es(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function bs(e){return e.reduce(((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ss(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Cs(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function ws(e){return null!==W(e)}const ys=/^\[([^\[]+)\]\((.+)\)$/,Is=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function xs(e){return ys.test(e)}function Ts(e,t){return`[${e}](${t})`}function Rs(e){const t=e.match(ys)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const Ls="o-spreadsheet://";function Ms(e){if(!xs(e))return!1;const{url:t}=Rs(e);return t.startsWith(Ls)}function As(e){if(e.startsWith(Ls))return e.substr(Ls.length);throw new Error(`${e} is not a valid sheet link`)}function _s(e){return void 0!==e}const Os={};function Ns(e,t){for(let[s,o]of Object.entries(t))if(ds(o)===ds(e))return parseInt(s,10);const s=Object.keys(t),o=0===s.length?0:Math.max(...s.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function ks(e){let t,s=!1;const o=()=>(s||(t=e(),s=!0),t);return o.map=e=>ks((()=>e(o()))),o}function Fs(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+b,size:b,name:ss(o)};t.push(e),s=e.end}return t}function $s(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+S,size:S,name:String(o+1),cells:{}};t.push(e),s=e.end}return t}function Ds(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||b,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:ss(n)};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Ps(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||S,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Us(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==b||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}function Vs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==S||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}class Bs{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function Hs(e,t,s){return[zs(e,"cols",Es(t,e.cols.length)),zs(e,"rows",Es(s,e.rows.length))]}function zs(e,t,s){const o=e[t];return s.find((e=>!o[e].isHidden))}function Zs(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function Gs(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,o,i,n,r=os(t[0].trim());if(i=n=r[0],s=o=r[1],2===t.length){let e=os(t[1].trim());n=e[0],o=e[1]}return{top:s,bottom:o,left:i,right:n}}function Ws(e){let{top:t,bottom:s,left:o,right:i}=Gs(e);return i<o&&([i,o]=[o,i]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:o,right:i}}function qs(e){return!(isNaN(e.bottom)||isNaN(e.top)||isNaN(e.left)||isNaN(e.right))&&(!(e.top<0||e.left<0||e.right<0||e.bottom<0)&&(e.bottom>=e.top&&e.right>=e.left))}function js(e){const{top:t,bottom:s,left:o,right:i}=e;return t===s&&o===i?is(o,t):`${is(o,t)}:${is(i,s)}`}function Xs(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ro(e,n,"RESIZE",i):r<e[t]?ro(e,n,"MOVE",i):{...e}}function Ys(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function Ks(e,t){return{top:Math.min(e.top,t.top),left:Math.min(e.left,t.left),bottom:Math.max(e.bottom,t.bottom),right:Math.max(e.right,t.right)}}function Qs(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Js(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function eo(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function to(e,t){const s={};for(let t of e)if(t){const e=Ws(t);for(let t=e.left;t<=e.right;t++)void 0===s[t]&&(s[t]=[]),s[t].push({top:e.top,bottom:e.bottom,remove:!1})}for(let e of t){const t=Ws(e);for(let e=t.left;e<=t.right;e++)void 0===s[e]&&(s[e]=[]),s[e].push({top:t.top,bottom:t.bottom,remove:!0})}const o=[];for(let[e,t]of Object.entries(s))o.push({col:parseInt(e),ranges:so(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let o=[],i=0;for(let e=0;e<=t.length-1;e++){let n=[];if(i+1===t[e].col)for(let s of t[e].ranges){let i=!1;for(let e of o)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),i=!0);i||n.push({top:s.top,bottom:s.bottom,startCol:t[e].col})}else n=t[e].ranges.map((s=>({top:s.top,bottom:s.bottom,startCol:t[e].col})));const r=o.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});i=t[e].col,o=n}for(let e of o)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});return s}(o).map(js)}function so(e){const t=new Set,s=new Set;for(let o of e)for(let e=o.top;e<=o.bottom;e++)o.remove?s.add(e):t.add(e);const o=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),i=[];let n;for(let e of o)n?e===n.bottom+1?n.bottom=e:(i.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&i.push({top:n.top,bottom:n.bottom}),i}function oo(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function io(e){const{width:t,height:s}=oo(e);return 1===t||1===s}function no(e){const t=[],[s,o]=[e.right,e.left].sort(((e,t)=>e-t)),[i,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Es(s,o+1))for(const s of Es(i,n+1))t.push([e,s]);return t}function ro(e,t,s,o){const i="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=o),n[i]+=o,n}function ao(e){return e.reverse().filter(((e,t,s)=>t===s.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}function lo(e){return{top:Math.min(e.top,e.bottom),bottom:Math.max(e.top,e.bottom),left:Math.min(e.left,e.right),right:Math.max(e.left,e.right)}}function co(e,t,s){let o=[],i=[],n=0,r=0;Ee([e],(e=>{o.push(e),n+=1})),Ee([t],(e=>{i.push(e),r+=1})),ce((()=>n===r),a("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),r.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}ce((()=>0!==l&&(!s||1!==l)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let p=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function ho(e,t,s){let o=0,i=0;const n=s?ye:we;i=n(e,((e,t)=>(o+=1,e+t)),0),ce((()=>0!==o&&(!t||1!==o)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=i/o;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(o-(t?1:0))}function uo(e,t,s){const o=de(t);ce((()=>s?0<=o&&o<=1:0<o&&o<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let i,n=[],r=0;Ee(e,(e=>{"number"==typeof e&&(i=Le(n,e),n.splice(i+1,0,e),r++)})),ce((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*o;if(s||(ce((()=>1<=l&&l<=r),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),l--),Number.isInteger(l))return n[l];const c=Math.ceil(l),h=Math.floor(l);return n[c]*(l-h)+n[h]*(c-l)}const po={description:a("Average magnitude of deviations from mean."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return we(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},go={description:a("Numerical average value in a dataset, ignoring text."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},fo=a("[[FUNCTION_NAME]] has mismatched range sizes."),mo=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),vo={description:a("Weighted average."),args:Oe(`\n values (number, range<number>) ${a("Values to average.")}\n weights (number, range<number>) ${a("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${a("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${a("Additional weights.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t,s,o=0,i=0;ce((()=>e.length%2==0),a("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],s=e[n+1],Array.isArray(t)){ce((()=>Array.isArray(s)),fo);let e=t.length,n=t[0].length;ce((()=>e===s.length&&n===s[0].length),fo);for(let r=0;r<e;r++)for(let e=0;e<n;e++){let n=t[r][e],l=s[r][e],c="number"==typeof n,h="number"==typeof l;ce((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(ce((()=>l>=0),mo),o+=n*l,i+=l)}}else s=de(s),t=de(t),ce((()=>s>=0),mo),o+=t*s,i+=s;return ce((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i}},Eo={description:a("Numerical average value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=ye(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},bo={description:a("Average of values depending on criteria."),args:Oe(`\n criteria_range (range) ${a("The range to check against criterion.")}\n criterion (string) ${a("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${a("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,s){null==s&&(s=e);let o=0,i=0;return Re([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(o+=1,i+=r)})),ce((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},So={description:a("Average of values depending on multiple criteria."),args:Oe(`\n average_range (range) ${a("The range to average.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0,o=0;return Re(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(s+=1,o+=n)})),ce((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/s},isExported:!0},Co={description:a("The number of numeric values in dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let s of e)if(Array.isArray(s))for(let e of s)for(let s of e)"number"==typeof s&&(t+=1);else("string"!=typeof s||ee(s)||W(s))&&(t+=1);return t},isExported:!0},wo={description:a("The number of values in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},yo={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!1)},isExported:!0},Io={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!1)},isExported:!0},xo={description:a("The sample covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!0)},isExported:!0},To={description:a("Nth largest element from a data set."),args:Oe(`\n data (any, range) ${a("Array or range containing the dataset to consider.")}\n n (number) ${a("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.shift(),n--))}));const r=i.shift();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ro={description:a("Maximum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Lo={description:a("Maximum numeric value in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Mo={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=-1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s<i?i:s)})),s===-1/0?0:s},isExported:!0},Ao={description:a("Median value in a numeric dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=[];return be(e,(e=>{t.push(e)})),uo(t,.5,!0)},isExported:!0},_o={description:a("Minimum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Oo={description:a("Minimum numeric value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},No={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s>i?i:s)})),s===1/0?0:s},isExported:!0},ko={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return $o.compute(e,t)},isExported:!0},Fo={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],t,!1)},isExported:!0},$o={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],t,!0)},isExported:!0},Do={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return Uo.compute(e,t)},isExported:!0},Po={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],.25*Math.trunc(de(t)),!1)},isExported:!0},Uo={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],.25*Math.trunc(de(t)),!0)},isExported:!0},Vo={description:a("Nth smallest element in a data set."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n n (number) ${a("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.pop(),n--))}));const r=i.pop();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Bo={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(qo.compute(...e))},isExported:!0},Ho={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(jo.compute(...e))},isExported:!0},zo={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xo.compute(...e))},isExported:!0},Zo={description:a("Standard deviation of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yo.compute(...e))},isExported:!0},Go={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ko.compute(...e))},isExported:!0},Wo={description:a("Standard deviation of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Qo.compute(...e))},isExported:!0},qo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!1)},isExported:!0},jo={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!1)},isExported:!0},Xo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!1)},isExported:!0},Yo={description:a("Variance of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!0)},isExported:!0},Ko={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!1)},isExported:!0},Qo={description:a("Variance of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!0)},isExported:!0};var Jo=Object.freeze({__proto__:null,AVEDEV:po,AVERAGE:go,AVERAGE_WEIGHTED:vo,AVERAGEA:Eo,AVERAGEIF:bo,AVERAGEIFS:So,COUNT:Co,COUNTA:wo,COVAR:yo,COVARIANCE_P:Io,COVARIANCE_S:xo,LARGE:To,MAX:Ro,MAXA:Lo,MAXIFS:Mo,MEDIAN:Ao,MIN:_o,MINA:Oo,MINIFS:No,PERCENTILE:ko,PERCENTILE_EXC:Fo,PERCENTILE_INC:$o,QUARTILE:Do,QUARTILE_EXC:Po,QUARTILE_INC:Uo,SMALL:Vo,STDEV:Bo,STDEV_P:Ho,STDEV_S:zo,STDEVA:Zo,STDEVP:Go,STDEVPA:Wo,VAR:qo,VAR_P:jo,VAR_S:Xo,VARA:Yo,VARP:Ko,VARPA:Qo});function ei(e,t,s){var o;const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(pe(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(a("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||n-1<r)throw new Error(a("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),n.toString()))}else{const e=pe(t).toUpperCase();if(r=null!==(o=i.get(e))&&void 0!==o?o:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",pe(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Error(a("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],n=!0;for(let r=0;r<s.length;r++){const a=pe(s[r][0]).toUpperCase(),l=i.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(n){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Re(o,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const ti=Oe(`\n database (range) ${a("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.")}\n field (any) ${a("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${a("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),si={description:a("Average of a set of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return go.compute([o])},isExported:!0},oi={description:a("Counts values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Co.compute([o])},isExported:!0},ii={description:a("Counts values and text from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return wo.compute([o])},isExported:!0},ni={description:a("Single value from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return ce((()=>1===o.length),a("More than one match found in DGET evaluation.")),o[0]},isExported:!0},ri={description:a("Maximum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Ro.compute([o])},isExported:!0},ai={description:a("Minimum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return _o.compute([o])},isExported:!0},li={description:a("Product of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return At.compute([o])},isExported:!0},ci={description:a("Standard deviation of population sample from table."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Bo.compute([o])},isExported:!0},hi={description:a("Standard deviation of entire population from table."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Go.compute([o])},isExported:!0},di={description:a("Sum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Bt.compute([o])},isExported:!0},ui={description:a("Variance of population sample from table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return qo.compute([o])},isExported:!0},pi={description:a("Variance of a population from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Ko.compute([o])},isExported:!0};var gi=Object.freeze({__proto__:null,DAVERAGE:si,DCOUNT:oi,DCOUNTA:ii,DGET:ni,DMAX:ri,DMIN:ai,DPRODUCT:li,DSTDEV:ci,DSTDEVP:hi,DSUM:di,DVAR:ui,DVARP:pi});const fi=new Date(1899,11,30);function mi(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const vi={description:a("Converts year/month/day into a date."),args:Oe(`\n year (number) ${a("The year component of the date.")}\n month (number) ${a("The month component of the date.")}\n day (number) ${a("The day component of the date.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){let o=Math.trunc(de(e));const i=Math.trunc(de(t)),n=Math.trunc(de(s));ce((()=>0<=o&&o<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const r=new Date(o,i-1,n).getTime()-fi.getTime();return ce((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},Ei={description:a("Converts a date string to a date value."),args:Oe(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);return ce((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},bi={description:a("Day of the month that a specific date falls on."),args:Oe(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getDate()},isExported:!0},Si={description:a("Number of days between two dates."),args:Oe(`\n end_date (date) ${a("The end of the date range.")}\n start_date (date) ${a("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=me(e),o=me(t),i=s.getTime()-o.getTime();return Math.round(i/864e5)},isExported:!0},Ci={description:a("Date a number of months before/after another date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new Date(i,n+o,r).getTime()-fi.getTime();return Math.round(a/864e5)},isExported:!0},wi={description:a("Last day of a month before or after a date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=new Date(i,n+o+1,0).getTime()-fi.getTime();return Math.round(r/864e5)},isExported:!0},yi={description:a("Hour component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getHours()},isExported:!0},Ii={description:a("ISO week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e){const t=me(e),s=t.getFullYear();let o=1;for(;4!==new Date(s,0,o).getDay();)o+=1;const i=new Date(s,0,o-3);let n=31;for(;4!==new Date(s,11,n).getDay();)n-=1;const r=new Date(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new Date(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Date(s-1,0,e).getDay();)e+=1;l=new Date(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/864e5;return Math.floor(c/7)+1},isExported:!0},xi={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMinutes()},isExported:!0},Ti={description:a("Month of the year a specific date falls in"),args:Oe(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMonth()+1},isExported:!0},Ri={description:a("Net working days between two provided days."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s){return Mi.compute(e,t,1,s)},isExported:!0};function Li(e){if("string"==typeof e){ce((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),a('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let s=0;s<7;s++)"1"===e[s]&&t.push((s+1)%7);return t}if("number"==typeof e)return ce((()=>1<=e&&e<=7||11<=e&&e<=17),a("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(a("The weekend (%s) must be a number or a string.",e.toString()))}const Mi={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1,o){const i=me(e),n=me(t),r=Li(s);let a=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);a.add(t.getTime())}));const l=i.getTime()>n.getTime(),c=new Date((l?i:n).getTime());let h=new Date((l?n:i).getTime());const d=c.getTime();let u=h.getTime(),p=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(p+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-p:p},isExported:!0},Ai={description:a("Current date and time as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy hh:mm:ss"},compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-fi.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},_i={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getSeconds()},isExported:!0},Oi={description:a("Converts hour/minute/second into a time."),args:Oe(`\n hour (number) ${a("The hour component of the time.")}\n minute (number) ${a("The minute component of the time.")}\n second (number) ${a("The second component of the time.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"hh:mm:ss a"},compute:function(e,t,s){let o=Math.trunc(de(e)),i=Math.trunc(de(t)),n=Math.trunc(de(s));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,ce((()=>o>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+i/1440+n/86400},isExported:!0},Ni={description:a("Converts a time string into its serial number representation."),args:Oe(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);ce((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},ki={description:a("Current date as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-fi.getTime();return Math.round(t/864e5)},isExported:!0},Fi={description:a("Day of the week of the date provided (as number)."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t)),i=s.getDay();return ce((()=>[1,2,3].includes(o)),a("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?i+1:2===o?0===i?7:i:0===i?6:i-1},isExported:!0},$i={description:a("Week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t));if(ce((()=>1===o||2===o||11<=o&&o<=17||21===o),a("The type (%s) is out of range.",o.toString())),21===o)return Ii.compute(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,l=new Date(n,0,r);for(;l.getDay()!==i;)r+=1,l=new Date(n,0,r);const c=(s.getTime()-l.getTime())/864e5;return c<0?1:Math.floor(c/7)+(1===r?1:2)},isExported:!0},Di={description:a("Number of working days from start date."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){return Pi.compute(e,t,1,s)},isExported:!0},Pi={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s=1,o){let i=me(e),n=Math.trunc(de(t));"string"==typeof s&&ce((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=Li(s);let l=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);l.add(t.getTime())}));let c=new Date(i.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),r.includes(c.getDay())||l.has(h)||(u-=1);const p=h-fi.getTime();return Math.round(p/864e5)},isExported:!0},Ui={description:a("Year specified by a given date."),args:Oe(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getFullYear()},isExported:!0},Vi={description:a("Exact number of years between two dates."),args:Oe(`\n start_date (date) ${a("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.")}\n end_date (date) ${a("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.")}\n day_count_convention (number, default=0) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s=0){let o=Math.trunc(de(e)),i=Math.trunc(de(t));const n=Math.trunc(de(s));if(ce((()=>o>=0),a("The start_date (%s) must be positive or null.",o.toString())),ce((()=>i>=0),a("The end_date (%s) must be positive or null.",i.toString())),ce((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),o===i)return 0;if(o>i){const e=i;i=o,o=e}const r=me(o),l=me(i);let c=r.getDate(),h=l.getDate();const d=r.getMonth(),u=l.getMonth(),p=r.getFullYear(),g=l.getFullYear();let f=0,m=0;switch(n){case 0:31===c&&(c=30),30===c&&31===h&&(h=30),1===d&&c===(mi(p)?29:28)&&(c=30,1===u&&h===(mi(g)?29:28)&&(h=30)),f=p+(30*d+c)/360,m=g+(30*u+h)/360;break;case 1:let e=365;const t=p===g;if(!t&&!(p+1===g)||!t&&d<u||!t&&d===u&&c<h){let t=0,s=0;for(let e=p;e<=g;e++)t++,s+=mi(e)?366:365;e=s/t}else t?mi(p)&&(e=366):(mi(p)&&d<2&&(e=366),mi(g)&&(u>1||1===u&&29===h)&&(e=366));f=o/e,m=i/e;break;case 2:f=o/360,m=i/360;break;case 3:f=o/365,m=i/365;break;case 4:31===c&&(c=30),31===h&&(h=30),f=p+(30*d+c)/360,m=g+(30*u+h)/360}return m-f}};var Bi=Object.freeze({__proto__:null,DATE:vi,DATEVALUE:Ei,DAY:bi,DAYS:Si,EDATE:Ci,EOMONTH:wi,HOUR:yi,ISOWEEKNUM:Ii,MINUTE:xi,MONTH:Ti,NETWORKDAYS:Ri,NETWORKDAYS_INTL:Mi,NOW:Ai,SECOND:_i,TIME:Oi,TIMEVALUE:Ni,TODAY:ki,WEEKDAY:Fi,WEEKNUM:$i,WORKDAY:Di,WORKDAY_INTL:Pi,YEAR:Ui,YEARFRAC:Vi});const Hi={description:a("Compare two numeric values, returning 1 if they're equal."),args:Oe(`\n number1 (number) ${a("The first number to compare.")}\n number2 (number, default=0) ${a("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return de(e)===de(t)?1:0},isExported:!0};var zi=Object.freeze({__proto__:null,DELTA:Hi});function Zi(e,t,s,o,i=1e-10){let n,r,l,c=s,h=!1,d=0;do{l=e(c),n=c-l/t(c),r=Math.abs(n-c),c=n,h=r<i||Math.abs(l)<i,ce((()=>d<o),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Gi={description:a("Depreciation via declining balance method."),args:Oe(`\n cost (number) ${a("The initial cost of the asset.")}\n salvage (number) ${a("The value of the asset at the end of depreciation.")}\n life (number) ${a("The number of periods over which the asset is depreciated.")}\n period (number) ${a("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${a("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o,...i){const n=de(e),r=de(t),l=de(s),c=Math.trunc(de(o)),h=i.length?Math.trunc(de(i[0])):12,d=l+(12===h?0:1);ce((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),ce((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),ce((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),ce((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),ce((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ce((()=>c<=d),a("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let p=1-Math.pow(r/n,1/l);p=Math.round(1e3*p)/1e3;let g=n,f=n*(1-p*u);for(let e=1;e<c;e++)g=f,f=g*(1-p),e===l&&(f=g*(1-p*(1-u)));return g-f}},Wi={description:a("Number of periods for an investment to reach a value."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=de(s),h=de(o),d=Math.trunc(de(i)),u=Math.trunc(de(n));ce((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),ce((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),ce((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Vi.compute(r,l,u),g=p-Math.trunc(p)||1/d,f=Math.ceil(p*d),m=c/d,v=h/d;let E=0,b=0;for(let e=1;e<=f;e++){const t=(m+(e===f?1:0))/(1+v)**e;b+=(g+(e-1)/d)*t,E+=t}return 0===E?0:b/E}},qi={description:a("Future value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n present_value (number, default=0) ${a("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},ji={description:a("Internal rate of return given periodic cashflows."),args:Oe(`\n cashflow_amounts (number, range<number>) ${a("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${a("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"0%"},compute:function(e,t=.1){const s=de(t);ce((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let o=!1,i=!1,n=[];be([e],(e=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)})),ce((()=>o&&i),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Zi((function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*e**(o-i))),t*e**o)}(e,r,n)}),(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*(o-i)*e**(o-i-1))),t*o*e**(o-1))}(e,r,n)}),s+1,20,1e-5)-1}},Xi={description:a("Modified Macaulay duration."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){return Wi.compute(e,t,s,o,i,n)/(1+de(o)/Math.trunc(de(i)))}};const Yi={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Oe(`\n discount (number) ${a("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${a("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${a("Additional future cash flows.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,...t){const s=de(e);return ce((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let o=0;return we(s,((t,s)=>(o++,t+s/(1+e)**o)),t)}(s,0,t)}},Ki={description:a("Computes the number of periods needed for an investment to reach a value."),args:Oe(`\n rate (number) ${a("The rate at which the investment grows each period.")}\n present_value (number) ${a("The investment's current value.")}\n future_value (number) ${a("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,s){const o=de(e),i=de(t),n=de(s);return ce((()=>o>0),a("The rate (%s) must be strictly positive.",o.toString())),ce((()=>i>0),a("The present_value (%s) must be strictly positive.",i.toString())),ce((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(i))/Math.log(1+o)}},Qi={description:a("Present value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n future_value (number, default=0) ${a("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},Ji={description:a("Price of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=Vi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=1+d/p,b=100*h/p;if(1===m)return(b+u)/(v*d/p+1)-b*(1-v);let S=0;for(let e=1;e<=m;e++)S+=b/E**(e-1+v);return u/E**(m-1+v)+S-b*(1-v)}},en={description:a("Annual yield of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought per 100 face value.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=Vi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=100*h/p;if(1===m){const e=d+E*(1-v);return(u+E-e)*p*(1/v)/e}const b=Zi((function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},tn={description:a("Annual yield of a security paying interest at maturity."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${a("The date the security was initially issued.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=Math.trunc(de(s)),h=de(o),d=de(i),u=Math.trunc(de(n));ce((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),ce((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Vi.compute(c,l,u),g=Vi.compute(c,r,u),f=Vi.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var sn=Object.freeze({__proto__:null,DB:Gi,DURATION:Wi,FV:qi,IRR:ji,MDURATION:Xi,NPV:Yi,PDURATION:Ki,PV:Qi,PRICE:Ji,YIELD:en,YIELDMAT:tn});const on={description:a("Whether a value is an error."),args:Oe(`value (any, lazy) ${a("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},nn={description:a("Whether a value is `true` or `false`."),args:Oe(`value (any) ${a("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){return"boolean"==typeof e},isExported:!0},rn={description:a("Whether a value is non-textual."),args:Oe(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},an={description:a("Whether a value is a number."),args:Oe(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},ln={description:a("Whether a value is text."),args:Oe(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var cn=Object.freeze({__proto__:null,ISERROR:on,ISLOGICAL:nn,ISNONTEXT:rn,ISNUMBER:an,ISTEXT:ln});const hn={description:a("Logical `and` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!0;return Ie(e,(e=>(t=!0,s=s&&e,s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},dn={description:a("Returns value depending on logical expression."),args:Oe(`\n logical_expression (boolean) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${a("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${a("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,s=(()=>!1)){const o=fe(e)?t():s();return null==o?"":o},isExported:!0},un={description:a("Value if it is not an error, otherwise 2nd argument."),args:Oe(`\n value (any, lazy) ${a("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${a("An empty value")}) ${a("The value the function returns if value is an error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let s;try{s=e()}catch(e){s=t()}return null==s?"":s},isExported:!0},pn={description:a("Returns a value depending on multiple logical expressions."),args:Oe(`\n condition1 (boolean, lazy) ${a("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${a("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${a("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${a("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){ce((()=>e.length%2==0),a("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(fe(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},gn={description:a("Returns opposite of provided logical value."),args:Oe(`logical_expression (boolean) ${a("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!fe(e)},isExported:!0},fn={description:a("Logical `or` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s||e,!s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},mn={description:a("Logical `xor` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s?!e:e,!0))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var vn=Object.freeze({__proto__:null,AND:hn,IF:dn,IFERROR:un,IFS:pn,NOT:gn,OR:fn,XOR:mn});function En(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const bn={description:a("Column number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered")}) ${a("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Ws(e).left+1},isExported:!0},Sn={description:a("Number of columns in a specified array or range."),args:Oe(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Ws(e);return t.right-t.left+1},isExported:!0},Cn={description:a("Horizontal lookup"),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${a("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${a("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t.map((e=>e[0]));let l;return l=n?Le(r,e):En(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[l][i-1]},isExported:!0},wn={description:a("Look up a value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${a("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.")}\n result_range (range, optional) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s){let o=t.length,i=t[0].length;const n=i>=o,r=Le(n?t[0]:t.map((e=>e[0])),e);return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),void 0===s?n?t[o-1][r]:t[r][i-1]:(o=s.length,i=s[0].length,ce((()=>1===o||1===i),a("The result_range must be a single row or a single column.")),o>1?(ce((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(ce((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},yn={description:a("Position of item in range that matches value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${a("The search method. 1 (default) 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.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){let o=de(s);const i=t.length,n=t[0].length;ce((()=>1===i||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(o=Math.sign(o),o){case 1:r=Le(l,e);break;case 0:r=En(l,e);break;case-1:r=function(e,t){const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t>e[c])return-1;if(typeof e[h]===s&&e[h]>t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a>=t&&(void 0===o||o>a||o===a&&i>r)&&(o=a,i=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==i?i:-1}(l,e)}return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),r+1},isExported:!0},In={description:a("Row number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered by default")}) ${a("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Ws(e).top+1},isExported:!0},xn={description:a("Number of rows in a specified array or range."),args:Oe(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Ws(e);return t.bottom-t.top+1},isExported:!0},Tn={description:a("Vertical lookup."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${a("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t[0];let l;return l=n?Le(r,e):En(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[i-1][l]},isExported:!0};var Rn=Object.freeze({__proto__:null,COLUMN:bn,COLUMNS:Sn,HLOOKUP:Cn,LOOKUP:wn,MATCH:yn,ROW:In,ROWS:xn,VLOOKUP:Tn});const Ln={description:a("Sum of two numbers."),args:Oe(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)+de(t)}},Mn={description:a("Concatenation of two values."),args:Oe(`\n value1 (string) ${a("The value to which value2 will be appended.")}\n value2 (string) ${a("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return pe(e)+pe(t)},isExported:!0},An={description:a("One number divided by another."),args:Oe(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);return ce((()=>0!==s),a("The divisor must be different from zero.")),de(e)/s}};function _n(e){return null==e}const On={number:0,string:"",boolean:!1},Nn={description:a("Equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=_n(e)?On[typeof t]:e,t=_n(t)?On[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function kn(e,t,s){e=_n(e)?On[typeof t]:e,t=_n(t)?On[typeof e]:t,"number"!=typeof e&&(e=pe(e).toUpperCase()),"number"!=typeof t&&(t=pe(t).toUpperCase());const o=typeof e,i=typeof t;return"string"===o&&"number"===i||("string"!==i||"number"!==o)&&s(e,t)}const Fn={description:a("Strictly greater than."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return kn(e,t,((e,t)=>e>t))}},$n={description:a("Greater than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return kn(e,t,((e,t)=>e>=t))}},Dn={description:a("Less than."),args:Oe(`\n value1 (any) ${a("The value to test as being less than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!$n.compute(e,t)}},Pn={description:a("Less than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being less than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Fn.compute(e,t)}},Un={description:a("Difference of two numbers."),args:Oe(`\n value1 (number) ${a("The minuend, or number to be subtracted from.")}\n value2 (number) ${a("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)-de(t)}},Vn={description:a("Product of two numbers"),args:Oe(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)*de(t)}},Bn={description:a("Not equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Nn.compute(e,t)}},Hn={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Mt.compute(e,t)}},zn={description:a("A number with the sign reversed."),args:Oe(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:He.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-de(e)}},Zn={description:a("Value interpreted as a percentage."),args:Oe(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return de(e)/100}},Gn={description:a("A specified number, unchanged."),args:Oe(`\n value (any) ${a("The number to return.")}\n `),returnFormat:He.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var Wn=Object.freeze({__proto__:null,ADD:Ln,CONCAT:Mn,DIVIDE:An,EQ:Nn,GT:Fn,GTE:$n,LT:Dn,LTE:Pn,MINUS:Un,MULTIPLY:Vn,NE:Bn,POW:Hn,UMINUS:zn,UNARY_PERCENT:Zn,UPLUS:Gn});const qn={description:a("Gets character associated with number."),args:Oe(`\n table_number (number) ${a("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(de(e));return ce((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},jn={description:a("Appends strings to one another."),args:Oe(`\n string1 (string, range<string>) ${a("The initial string.")}\n string2 (string, range<string>, repeating) ${a("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return Ce(e,((e,t)=>e+pe(t)),"")},isExported:!0},Xn={description:a("Tests whether two strings are identical."),args:Oe(`\n string1 (string) ${a("The first string to compare.")}\n string2 (string) ${a("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return pe(e)===pe(t)},isExported:!0},Yn={description:a("First position of string found in text, case-sensitive."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e),i=pe(t),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),i)),r+1},isExported:!0},Kn={description:a("Concatenates elements of arrays with delimiter."),args:Oe(`\n delimiter (string) ${a("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${a("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${a("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const s=pe(e);return Ce(t,((e,t)=>(e?e+s:"")+pe(t)),"")}},Qn={description:a("Substring from beginning of specified string."),args:Oe(`\n text (string) ${a("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;return ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),pe(e).substring(0,s)},isExported:!0},Jn={description:a("Length of a string."),args:Oe(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return pe(e).length},isExported:!0},er={description:a("Converts a specified string to lowercase."),args:Oe(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toLowerCase()},isExported:!0},tr={description:a("Replaces part of a text string with different text."),args:Oe(`\n text (string) ${a("The text, a part of which will be replaced.")}\n position (number) ${a("The position where the replacement will begin (starting from 1).")}\n length (number) ${a("The number of characters in the text to be replaced.")}\n new_text (string) ${a("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,s,o){const i=de(t);ce((()=>i>=1),a("The position (%s) must be greater than or equal to 1.",i.toString()));const n=pe(e),r=de(s),l=pe(o);return n.substring(0,i-1)+l+n.substring(i-1+r)},isExported:!0},sr={description:a("A substring from the end of a specified string."),args:Oe(`\n text (string) ${a("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const o=pe(e),i=o.length;return o.substring(i-s,i)},isExported:!0},or={description:a("First position of string found in text, ignoring case."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e).toLowerCase(),i=pe(t).toLowerCase(),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)),r+1},isExported:!0},ir={description:a("Replaces existing text with new text in a string."),args:Oe(`\n text_to_search (string) ${a("The text within which to search and replace.")}\n search_for (string) ${a("The string to search for within text_to_search.")}\n replace_with (string) ${a("The string that will replace search_for.")}\n occurrence_number (number, optional) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o){const i=de(o);ce((()=>i>=0),a("The occurrenceNumber (%s) must be positive or null.",i.toString()));const n=pe(e),r=pe(t);if(""===r)return n;const l=pe(s),c=new RegExp(ps(r),"g");if(0===i)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===i?l:e))},isExported:!0},nr={description:a("Combines text from multiple strings and/or arrays."),args:Oe(`\n delimiter (string) ${a(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${a("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${a("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${a("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...s){const o=pe(e),i=fe(t);let n=0;return Ce(s,((e,t)=>i&&""===pe(t)?e:(n++?e+o:"")+pe(t)),"")},isExported:!0},rr={description:a("Removes space characters."),args:Oe(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return pe(e).trim()},isExported:!0},ar={description:a("Converts a specified string to uppercase."),args:Oe(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toUpperCase()},isExported:!0};const lr={database:gi,date:Bi,financial:sn,info:cn,lookup:Rn,logical:vn,math:qt,operators:Wn,statistical:Jo,text:Object.freeze({__proto__:null,CHAR:qn,CONCATENATE:jn,EXACT:Xn,FIND:Yn,JOIN:Kn,LEFT:Qn,LEN:Jn,LOWER:er,REPLACE:tr,RIGHT:sr,SEARCH:or,SUBSTITUTE:ir,TEXTJOIN:nr,TRIM:rr,UPPER:ar}),engineering:zi};const cr=new class extends Me{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=ke(t);return function(e){let t=!1,s=!1,o=!1;for(let i of e){if(i.type.includes("META")&&i.type.length>1)throw new Error(a("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!i.repeating)throw new Error(a("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=s||t||o,n=!(i.optional||i.repeating||i.default);if(e&&n)throw new Error(a("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=i.repeating,s=i.optional,o=i.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in lr){const t=lr[e];for(let s in t){const o=t[s];o.category=e,cr.add(s,{isExported:!1,...o})}}const hr=cr.content,dr="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function ur(e){const t=e.split(""),s=[];for(;t.length;){let e=yr(t)||fr(t)||vr(t)||br(t)||pr(t)||Ir(t)||Er(t)||Cr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function pr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const gr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function fr(e){if(e[0]in gr){const t=e.shift();return{type:gr[t],value:t}}return null}function mr(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function vr(e){for(let t of dr)if(mr(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function Er(e){const t=function(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}(e).match(Q);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function br(e){if('"'===e[0]){const t=e.shift();let s=t;for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e[0]&&(s+=e.shift()),{type:"STRING",value:s}}return null}const Sr=/\w|\.|!|\$/;function Cr(e){let t="";if("'"===e[0]){let s=e.shift();for(t+=s;e[0];)if(s=e.shift(),t+=s,"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Sr);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in hr)return{type:"FUNCTION",value:e};return e.match(es)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const wr=/\s/;function yr(e){let t=0;for(;e[0]&&e[0].match(wr);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Ir(e){return mr(e,O)?(e.splice(0,O.length),{type:"INVALID_REFERENCE",value:O}):null}const xr=["-","+"],Tr=["*","+","&"],Rr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Lr=6;function Mr(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return Rr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function Ar(e,t,s){if("OPERATOR"===t.type){const o=_r(s,Mr(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}throw new Error(k)}function _r(e,t){const s=e.shift();if(!s)throw new Error(k);let o=function(e,t){var s,o,i;switch(e.type){case"DEBUGGER":const n=_r(t,1e3);return n.debug=!0,n;case"NUMBER":return{type:"NUMBER",value:se(e.value)};case"STRING":return{type:"STRING",value:us(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const o=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?o.push({type:"UNKNOWN",value:""}):o.push(_r(t,Lr));"COMMA"===(null===(s=t[0])||void 0===s?void 0:s.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){o.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?o.push({type:"UNKNOWN",value:""}):o.push(_r(t,Lr))}const i=t.shift();if(!i||"RIGHT_PAREN"!==i.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:o}}case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"REFERENCE":if(":"===(null===(o=t[0])||void 0===o?void 0:o.value)&&"REFERENCE"===(null===(i=t[1])||void 0===i?void 0:i.type)){t.shift();const s=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==s?void 0:s.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value)throw new Error(a("Invalid formula"));return{type:"STRING",value:e.value};case"LEFT_PAREN":const r=_r(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),r;default:if("OPERATOR"===e.type&&xr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:_r(t,Rr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&Mr(e[0])>t;)o=Ar(o,e.shift(),e);return o}function Or(e){return Nr(ur(e))}function Nr(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=_r(e,0);if(e.length)throw new Error(k);return t}function kr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>kr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:kr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:kr(e.right,t,s),left:kr(e.left,t,s)};default:return e}}function Fr(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Fr(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+$r(e);case"BIN_OPERATION":return function(e){const t=e.value,s=e.left,o=s.value;return"BIN_OPERATION"===s.type&&Rr[o]<Rr[t]?`(${Fr(s)})`:Fr(s)}(e)+e.value+$r(e)}}function $r(e){const t=e.value,s=e.right,o=Rr[s.value],i=Rr[t];let n=!1;return"BIN_OPERATION"!==s.type?n=!1:o<i?n=!0:o!==i||Tr.includes(t)||(n=!0),n?`(${Fr(s)})`:Fr(s)}function Dr(e,t=!1){let s,o,i,n;const r=()=>{n=void 0,o=void 0,s=void 0,i=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(o){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"REFERENCE"===l.type)i=a;else if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n,s),a=n+1,r()}else"REFERENCE"===l.type?(n=a,o=a,s=void 0):r()}else"REFERENCE"===l.type?(o=a,s=i=void 0):r();else["SPACE","REFERENCE"].includes(l.type)?(n=a,o="REFERENCE"===l.type?a:void 0,s=i=void 0):r()}const a=e.length-1;if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a+1).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n+1,s)}return e}function Pr(e){return Dr(ur(e),!0)}const Ur=cr.content,Vr={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Br={"-":"UMINUS","+":"UPLUS"};function Hr(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const zr={};function Zr(e){const t=Pr(e),{dependencies:s,constantValues:o}=function(e){const t={numbers:[],strings:[]},s=[];for(const o of e)switch(o.type){case"REFERENCE":s.push(o.value);break;case"STRING":const e=us(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=se(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:s,constantValues:t}}(t),i=function(e,t,s){return e.map((e=>{switch(e.type){case"STRING":const o=us(e.value);return`|S${s.strings.indexOf(o)}|`;case"NUMBER":return`|N${s.numbers.indexOf(se(e.value))}|`;case"REFERENCE":return`|${t.indexOf(e.value)}|`;default:return e.value}})).join("")}(t,s,o);if(!zr[i]){const n=Nr([...t]);let r=1;if("BIN_OPERATION"===n.type&&":"===n.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===n.type)throw new Error(a("Invalid formula"));const l=u(n),c=Hr([`// ${i}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","sheetId","ref","range","ctx",c);function d(e){const t=Ur[e.value.toUpperCase()],s=e.args,o=s.length;if(o<t.minArgRequired)throw new Error(a("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new Error(a("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const i=t.nbrArgRepeating;if(i>1){const s=t.args.length-i;if((o-s)%i!=0)throw new Error(a("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),s.toString(),i.toString()))}let n=[];for(let i=0;i<o;i++){const o=t.getArgToFocus(i+1)-1;if(0<=o&&o<t.args.length){const r=s[i],l=t.args[o],c=l.type||[],h=c.includes("META"),d=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"REFERENCE"!==r.type)throw new Error(a("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(i+1).toString(),r.type.toLowerCase()));const f=u(r,d,h,p,{functionName:e.value.toUpperCase(),paramIndex:i+1});n.push(f)}}return n}function u(e,t=!1,i=!1,n=!1,l={}){const c=[];let h,p,g;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&i)throw new Error(a("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`${e.value}`,code:""};h=r++,g=`${e.value}`;break;case"NUMBER":h=r++,g=`this.constantValues.numbers[${o.numbers.indexOf(e.value)}]`;break;case"STRING":h=r++,g=`this.constantValues.strings[${o.strings.indexOf(e.value)}]`;break;case"REFERENCE":const a=s.indexOf(e.value);h=r++,g=n?`range(${a}, deps, sheetId)`:`ref(${a}, deps, sheetId, ${i?"true":"false"}, "${l.functionName||Vr["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=r++;const f=d(e);c.push(f.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${f.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=r++,p=Br[e.value];const t=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}']( ${t.id})`;break}case"BIN_OPERATION":{h=r++,p=Vr[e.value];const t=u(e.left,!1,!1,!1,{functionName:p}),s=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(s.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${t.id}, ${s.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=r++,g="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${Hr(c).join("\n\t")}\n\treturn ${g};\n}`}}return c.push(`let _${h} = ${g};`),{id:`_${h}`,code:c.join("\n")}}function p(e){let t;switch(e.type){case"REFERENCE":return[s.indexOf(e.value)];case"FUNCALL":if(t=Ur[e.value.toUpperCase()],t.returnFormat){if("FormatFromArgument"!==t.returnFormat)return[t.returnFormat.specificFormat];if(e.args.length>0){const s=0;if(!t.args[s].type.includes("META"))return p(e.args[s])}}break;case"UNARY_OPERATION":return p(e.right);case"BIN_OPERATION":if(t=Ur[Vr[e.value]],t.returnFormat){if("FormatFromArgument"===t.returnFormat){const t=p(e.left);if("string"==typeof t[t.length-1])return t;const s=p(e.right);return t.concat(s)}return[t.returnFormat.specificFormat]}}return[]}zr[i]={execute:h,dependenciesFormat:p(n)}}return{dependenciesFormat:zr[i].dependenciesFormat,execute:zr[i].execute,dependencies:s,constantValues:o,tokens:t}}function Gr(e){return function(e){let t=[],s="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"FUNCTION":s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0}),s="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e}))}(function(e){let t=1;const s=[];return e.map((e=>("LEFT_PAREN"===e.type?(s.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=s.pop()),e)))}(function(e){let t=0;return e.map((e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o}))}(Dr(ur(e)))))}const Wr=new Me;function qr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(_))?X({value:e,format:t}):t?function(e,t){const s=t.split(";"),o=s.length;return e<0?o>1?le(-e,s[1]):"-"+le(-e,s[0]):le(e,s[3===o&&0===e?2:0])}(e,t):ie(e);case"object":return"0"}}function jr(e){return""===e?"":ee(e)?se(e):Cs(e)?"TRUE"===e.toUpperCase():ws(e)?W(e).value:e}class Xr{constructor(e,t,s){this.id=e,this.evaluated=t,this.style=s.style,this.format=s.format}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get formattedValue(){return qr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case Fe.number:return"right";case Fe.boolean:case Fe.error:return"center";case Fe.text:case Fe.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case Fe.empty:case Fe.text:return!0;case Fe.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(_));case Fe.error:case Fe.boolean:return!1}}}class Yr extends Xr{constructor(e,t={}){super(e,{value:"",type:Fe.empty},t),this.content=""}isEmpty(){return!0}}class Kr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.number},s),this.content=ie(this.evaluated.value)}}class Qr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class Jr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.text},s),this.content=this.evaluated.value}}class ea extends Kr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return qr(this.evaluated.value,this.format)}}class ta extends Xr{constructor(e,t,s={}){var o;const i=Rs(t);s={...s,style:{...s.style,textColor:(null===(o=s.style)||void 0===o?void 0:o.textColor)||A,underline:!0}},super(e,{value:i.label,type:Fe.text},s),this.link=i,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class sa extends ta{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=Ts(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class oa extends ta{constructor(e,t,s={},o){super(e,t,s),this.sheetName=o,this.sheetId=As(this.link.url),this.isUrlEditable=!1}action(e){e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||a("Invalid sheet")}}class ia extends Xr{constructor(e,t,s,o,i,n){super(t,{value:"Loading...",type:Fe.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=o,this.dependencies=i}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:Fe.number};break;case"boolean":this.evaluated={value:e,type:Fe.boolean};break;case"string":this.evaluated={value:e,type:Fe.text};break;case"object":case"undefined":this.evaluated={value:e,type:Fe.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:Fe.error}}}class na extends Xr{constructor(e,t,s,o){super(e,{value:"#BAD_EXPR",type:Fe.error,error:s},o),this.content=t}}function ra(e){const t=Pr(e);let s=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Jt.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${P}${s.indexOf(t)}${P}`}return e.value}))),dependencies:s}}Wr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,o,i)=>{const n=Zr(t),r=n.dependencies.map((e=>i.getRangeFromSheetXC(o,e))),a=s.format||i.inferFormulaFormat(n,r);return new ia((e=>i.buildFormulaContent(o,e)),e,t,n,r,{...s,format:a})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new Yr(e,s)}).add("Number",{sequence:30,match:e=>ee(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new Kr(e,se(t),s))}).add("Boolean",{sequence:40,match:e=>Cs(e),createCell:(e,t,s)=>new Qr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>ws(e),createCell:(e,t,s)=>{const o=W(t),i=s.format||o.format;return new ea(e,o.value,{...s,format:i})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ms(e),createCell:(e,t,s,o,i)=>new oa(e,t,s,(e=>i.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>xs(e),createCell:(e,t,s)=>new sa(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Is.test(t);var t},createCell:(e,t,s)=>new sa(e,Ts(t,t),s)});const aa=11,la="Sheet1";function ca(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<aa&&(e=function(e){for(let t=ha.findIndex((t=>t.from===e.version));t<ha.length;t++)e=ha[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new Bs;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(ga(),e,{version:aa}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(pa(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(pa(la,"Sheet1"));return e}(e),e}(e),e):ga()}const ha=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=ra(s.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(let e of s)if(e.labelCell){const t=Ws(e.dataRange),s=e.labelCell+":"+is(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],o=new RegExp($,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,n=e.replace(o,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;i.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),o=t;for(;o!==s;)o=s,s=o.replace(e,a);return o};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),s=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const s of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[s])||void 0===t?void 0:t.type)&&(e.rule[s].value=l(e.rule[s].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=g,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stackedBar=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(let[s,o]of Object.entries(t)){const t=`\\${P}${s}\\${P}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let s of e.sheets||[])for(let e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=Ns(o.format,t))}return e.formats=t,e}}];function da(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:la};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=ua(t,"SORT_CELLS"),t=ua(t,"SET_DECIMAL")}function ua(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter((e=>e.type!==t))}):s.push(o);return s}function pa(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function ga(e="Sheet1"){return{version:aa,sheets:[pa(la,e)],entities:{},styles:{},formats:{},borders:{},revisionId:N,uniqueFigureIds:!0}}class fa{constructor(e,t,s){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.currentMode=s.mode}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}fa.getters=[],fa.modes=["headless","normal"];class ma extends fa{constructor(e,t,s,o,i,n){super(t,o,i),this.dispatch=o,this.range=s,s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}exportForExcel(e){}adaptRanges(e,t){}}class va extends ma{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const s=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,s)}break;case"DELETE_SHEET":const s={...this.borders};delete s[e.sheetId],this.history.update("borders",s);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=this.getters.getSheet(e.sheetId),s=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(t,s,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,o)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,o)}getCellBorder(e,t,s){var o,i,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(i=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===i?void 0:i[s])||void 0===n?void 0:n.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[s+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[s])||void 0===d?void 0:d.vertical,right:null===(g=null===(p=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===p?void 0:p[s])||void 0===g?void 0:g.vertical};return f.bottom||f.left||f.right||f.top?f:null}ensureColumnBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.rows.length;i++){const n=this.getCellBorder(e.id,t,i),r=this.getCellBorder(e.id,s,i);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,s,i,t)}}}ensureRowBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.cols.length;i++){const n=this.getCellBorder(e.id,i,t),r=this.getCellBorder(e.id,i,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,i,s,t)}}}getCommonSides(e,t){const s={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(s[o]=e[o]);return s}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){if(!this.borders[e])return[];return Es(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfColumn(e,t,s,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfColumn(e,i,s,"vertical"),this.moveBordersOfColumn(e,i,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfRow(e,t,s,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfRow(e,i,s,"horizontal"),this.moveBordersOfRow(e,i,s,"vertical")})))}moveBordersOfRow(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[r])||void 0===a?void 0:a[t+s])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+s,o,i?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[t+s])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+s,r,o,i?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,s,o){this.history.update("borders",e,t,s,{vertical:null==o?void 0:o.left,horizontal:null==o?void 0:o.top}),this.history.update("borders",e,t+1,s,"vertical",null==o?void 0:o.right),this.history.update("borders",e,t,s+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let s of t){for(let t=s.top;t<=s.bottom;t++){this.history.update("borders",e,s.right+1,t,"vertical",void 0);for(let o=s.left;o<=s.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=s.left;t<=s.right;t++)this.history.update("borders",e,t,s.bottom+1,"horizontal",void 0)}}addBorder(e,t,s,o){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...o})}setBorders(e,t,s){const o=e.id;if("clear"===s)return this.clearBorders(o,t);for(let e of t){if("h"===s||"hv"===s||"all"===s)for(let t=e.top+1;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++)this.addBorder(o,s,t,{top:M});if("v"===s||"hv"===s||"all"===s)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left+1;s<=e.right;s++)this.addBorder(o,s,t,{left:M});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.left,t,{left:M});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.right+1,t,{left:M});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.top,{top:M});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.bottom+1,{top:M})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:o,right:i,top:n,bottom:r}=t,a=this.getCellBorder(s.id,o,n),l=this.getCellBorder(s.id,i,r);this.clearBorders(e,[t]),(null==a?void 0:a.top)&&this.setBorders(s,[{...t,bottom:n}],"top"),(null==a?void 0:a.left)&&this.setBorders(s,[{...t,right:o}],"left"),((null==l?void 0:l.bottom)||(null==a?void 0:a.bottom))&&this.setBorders(s,[{...t,top:r}],"bottom"),((null==l?void 0:l.right)||(null==a?void 0:a.right))&&this.setBorders(s,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const i=e.borders[o.border],[n,r]=os(s);this.setBorder(t.id,n,r,i)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Ws(e))}export(e){let t=0;const s={};function o(e){for(let[t,o]of Object.entries(s))if(ds(o)===ds(e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let s=0;s<t.rowNumber;s++){const i=this.getCellBorder(t.id,e,s);if(i){const n=is(e,s),r=t.cells[n],a=o(i);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}va.getters=["getCellBorder"];const Ea=new RegExp(String.fromCharCode(160),"g");class ba extends ma{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=Wr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,o,i,n){const r=t.find((e=>e.match(o)));if(!r)return new Jr(s,o,i);try{return r.createCell(s,o,i,n,e)}catch(e){return new na(s,o,e.message||k,i)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const o of Object.values(this.cells[s]||{}))if(o.isFormula())for(const i of o.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",s,o.id,"dependencies",o.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearStyles(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(this.getters.getSheet(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:""})}}setFormatter(e,t,s){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let o,i;"before"===e.position?(o=Es(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Es(e.base+1,e.base+e.quantity+1),i=e.base),t(s,i,o)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let o in t.cells){const i=t.cells[o],[n,r]=os(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(s,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}}export(e){const t={},s={};for(let o of e.sheets){const e={},i=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:n,row:r}of i){const i=this.getters.getCell(o.id,n,r);e[is(n,r)]={style:i.style?Ns(i.style,t):void 0,format:i.format?Ns(i.format,s):void 0,content:i.content}}o.cells=e}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=t.style&&s[t.style]||void 0,n=t.format&&o[t.format]||void 0,r=this.uuidGenerator.uuidv4(),a={format:n,style:i};return this.createCell(r,(null==t?void 0:t.content)||"",a,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,o]=os(e),i=this.getters.getCell(t.id,s,o),n=t.cells[e];n.value=i.evaluated.value,n.isFormula=i.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t of Object.values(this.cells))if(t[e])return t[e]}inferFormulaFormat(e,t){const s=e.dependenciesFormat;for(let e of s)switch(typeof e){case"string":return e;case"number":const s=t[e];if(this.getters.tryGetSheet(s.sheetId)){const e=this.getters.getCell(s.sheetId,s.zone.left,s.zone.top);if(e&&e.format)return e.format}}return D}buildFormulaContent(e,t,s){const o=s||[...t.dependencies];return t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.shift();return this.getters.getRangeString(t,e)}return t.value})).join("")}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return e&&e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=is((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=is(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCell(e,t.left,t.top),r=this.getters.getMainCell(e,t.right,t.bottom),a=n[0]==r[0]&&n[1]==r[1];return o==i||a?o:o+":"+i}setStyle(e,t,s){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell(e,t,i);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...null==o?void 0:o.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<e.rows.length;o++){const i=this.getFormat(e.id,t,o);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<e.cols.length;o++){const i=this.getFormat(e.id,o,t);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:o,row:t,...i})}}getFormat(e,t,s){const o={},[i,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,i,n);return r&&(r.style&&(o.style=r.style),r.format&&(o.format=r.format)),o}updateCell(e,t,s,o){var i;const n=this.getters.getCell(e.id,t,s),r="content"in o||"formula"in o,a=r?(null===(i=o.content)||void 0===i?void 0:i.replace(Ea,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==o.style?o.style||void 0:n?n.style:void 0;let c=("format"in o?o.format:n&&n.format)||D;if((r&&!a&&!o.formula||!r&&(!n||n.isEmpty()))&&!l&&!c)return void(n&&(this.history.update("cells",e.id,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e.id})));const h=(null==n?void 0:n.id)||this.uuidGenerator.uuidv4(),d=r,u={format:c,style:l},p=this.createCell(h,a,u,e.id);n&&!d&&p.isFormula()&&(p.assignValue(n.evaluated.value),n.evaluated.type===Fe.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const o=this.getters.tryGetSheet(e);if(!o)return 23;return eo(t,s,{top:0,left:0,bottom:o.rows.length-1,right:o.cols.length-1})?0:18}}ba.getters=["zoneToXC","getCells","getFormulaCellContent","inferFormulaFormat","getCellStyle","buildFormulaContent","getCellById"];class Sa extends ma{constructor(){super(...arguments),this.chartFigures={}}adaptRanges(e){for(let[t,s]of Object.entries(this.chartFigures))s&&(this.adaptDataSetRanges(s,t,e),this.adaptLabelRanges(s,t,e))}adaptDataSetRanges(e,t,s){for(let o of e.dataSets){if(o.labelCell){const i=s(o.labelCell);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",i.range)}}const i=s(o.dataRange);switch(i.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(i.range,i.range.sheetId)!==O)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"dataRange",i.range);else{const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const o=s(e.labelRange);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",o.range)}}}allowDispatch(e){switch(e.type){case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartExists),this.checkLabelRange);case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartDuplicate),this.checkLabelRange);default:return 0}}handle(e){var t,s;switch(e.type){case"CREATE_CHART":const o=e.position?e.position.x:0,i=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:o,y:i,height:335,width:536,tag:"chart"});break;case"UPDATE_CHART":this.updateChartDefinition(e.id,e.definition);break;case"DUPLICATE_SHEET":{const s=this.getters.getFigures(e.sheetId);for(const o of s)if("chart"===o.tag){const s=o.id.split("??").pop(),i=`${e.sheetIdTo}??${s}`,n={...gs(this.chartFigures[o.id]),id:i};n.sheetId=e.sheetIdTo,n.dataSets.forEach((t=>{var s;t.dataRange.sheetId===e.sheetId&&(t.dataRange.sheetId=e.sheetIdTo),(null===(s=t.labelCell)||void 0===s?void 0:s.sheetId)===e.sheetId&&(t.labelCell.sheetId=e.sheetIdTo)})),(null===(t=n.labelRange)||void 0===t?void 0:t.sheetId)===e.sheetId&&(n.labelRange.sheetId=e.sheetIdTo);const r={id:i,x:o.x,y:o.y,height:o.height,width:o.width,tag:"chart"};this.addChartFigure(e.sheetIdTo,n,r)}break}case"DELETE_FIGURE":this.history.update("chartFigures",e.id,void 0);break;case"DELETE_SHEET":for(let t of Object.keys(this.chartFigures))(null===(s=this.chartFigures[t])||void 0===s?void 0:s.sheetId)===e.sheetId&&this.history.update("chartFigures",t,void 0)}}getChartDefinition(e){return this.chartFigures[e]}getChartsIdBySheet(e){return Object.entries(this.chartFigures).filter((t=>t[1].sheetId===e)).map((e=>e[0]))}getChartDefinitionUI(e,t){const s=this.chartFigures[t];if(!s)return;const o=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:o,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===o.length)&&Boolean(s.dataSets[0].labelCell),background:s.background,verticalAxisPosition:s.verticalAxisPosition,legendPosition:s.legendPosition,stackedBar:s.stackedBar}}getChartDefinitionExcel(e,t){const s=this.chartFigures[t],o=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!o)return;const i=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...o,backgroundColor:s.background,dataSets:i}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let o=e.dataRange.zone;if(s){const{height:e,width:t}=oo(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i={...e.dataRange,zone:o};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(i,"forceSheetReference")}}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)if("chart"===e.tag){const s={...e.data};this.chartFigures[e.id]=this.createChartDefinition(s,t.id),delete e.data}}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionUI(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.figures=s}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionExcel(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.charts=s}}createChartDefinition(e,t){return{...e,dataSets:this.createDataSets(e.dataSets,t,e.dataSetsHaveTitle),labelRange:e.labelRange?this.getters.getRangeFromSheetXC(t,e.labelRange):void 0,sheetId:t}}updateChartDefinition(e,t){const s=this.chartFigures[e];if(!s)throw new Error(`There is no chart with the given id: ${e}`);if(void 0!==t.title&&this.history.update("chartFigures",e,"title",t.title),t.type&&this.history.update("chartFigures",e,"type",t.type),t.dataSets){const o=!!t.dataSetsHaveTitle,i=this.createDataSets(t.dataSets,s.sheetId,o);this.history.update("chartFigures",e,"dataSets",i)}if(void 0!==t.labelRange){const o=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",o)}t.background&&this.history.update("chartFigures",e,"background",t.background),t.verticalAxisPosition&&this.history.update("chartFigures",e,"verticalAxisPosition",t.verticalAxisPosition),t.legendPosition&&this.history.update("chartFigures",e,"legendPosition",t.legendPosition),void 0!==t.stackedBar&&this.history.update("chartFigures",e,"stackedBar",t.stackedBar)}createDataSets(e,t,s){const o=[];for(const i of e){const e=this.getters.getRangeFromSheetXC(t,i),{zone:n,sheetId:r,invalidSheetName:a}=e;if(!a)if(n.left!==n.right&&n.top!==n.bottom)for(let e=n.left;e<=n.right;e++){const t={left:e,right:e,top:n.top,bottom:n.bottom};o.push(this.createDataSet(r,t,s?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0))}else n.left===n.right&&n.top===n.bottom?s||o.push(this.createDataSet(r,n,void 0)):o.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return o}addChartFigure(e,t,s){this.dispatch("CREATE_FIGURE",{sheetId:e,figure:s}),this.history.update("chartFigures",s.id,t)}createDataSet(e,t,s){if(t.left!==t.right&&t.top!==t.bottom)throw new Error(`Zone should be a single column or row: ${js(t)}`);if(s){const o=js(t),i=js(s);return{labelCell:this.getters.getRangeFromSheetXC(e,i),dataRange:this.getters.getRangeFromSheetXC(e,o)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,js(t))}}checkEmptyDataset(e){return e.definition.dataSets&&0===e.definition.dataSets.length?27:0}checkDataset(e){if(!e.definition.dataSets)return 0;const t=void 0!==e.definition.dataSets.find((e=>!es.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!es.test(e.definition.labelRange||"")?29:0}checkChartDuplicate(e){for(const t of this.getters.getSheets())if(this.getters.getFigure(t.id,e.id))return 57;return 0}checkChartExists(e){return this.getters.getFigure(e.sheetId,e.id)?0:58}}function Ca(e){return""===e?NaN:Number(e)}Sa.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class wa extends ma{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){return"ADD_CONDITIONAL_FORMAT"===e.type?this.checkValidations(e,this.checkCFRule,this.checkEmptyRange):0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.target.map(js)};this.addConditionalFormatting(s,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e].map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const s=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{s.add(e)}))})),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const o=[];for(let i of this.cfRules[e])for(let e of i.ranges)eo(t,s,e.zone)&&o.push(i);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const s={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return s}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkEmptyRange(e){return e.target.length?0:21}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));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)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return s=>{if(t.includes(s.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(s.values[0])&&t.push(36),e>=2&&o(s.values[1])&&t.push(37),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 38;case"max":return 40;case"mid":return 39;case"upperInflectionPoint":return 41;case"lowerInflectionPoint":return 42}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Zr(e.value||"")}catch(e){switch(t){case"min":return 43;case"max":return 45;case"mid":return 44;case"upperInflectionPoint":return 46;case"lowerInflectionPoint":return 47}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?33:0}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Ca(t)>=Ca(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Ca(s)>=Ca(o)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Ca(s)>=Ca(o)?35:0}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}}wa.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class ya extends ma{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:s,...o}=e,i=o;this.updateFigure(s,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,o]of Object.entries(t))switch(s){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,s,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,s,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var s;return void 0===(null===(s=this.figures[e])||void 0===s?void 0:s[t])?55:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?56:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(_s)}getFigure(e,t){var s;return null===(s=this.figures[e])||void 0===s?void 0:s[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var s;return void 0!==(null===(s=this.figures[t])||void 0===s?void 0:s[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){this.export(e)}}ya.getters=["getFigures","getFigure","getFigureSheetId"];class Ia extends ma{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?0:this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;const s=this.getters.getSheet(e.sheetIdTo);for(const e of Object.values(t).filter(_s))this.addMerge(s,e.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(this.getters.getSheet(e.sheetId),t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.merges);for(const t of s)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(_s)}getMerge(e,t,s){var o;const i=this.mergeCellMap[e],n=i?t in i&&(null===(o=i[t])||void 0===o?void 0:o[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:o,top:i,bottom:n}=t;for(let t=i;t<=n;t++)for(let i=s;i<=o;i++)if(this.getMerge(e,i,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<o.rows.length;e++)if(this.isInSameMerge(o.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<=o.cols.length;e++)if(this.isInSameMerge(o.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:o,top:i,bottom:n}=t,r={left:s,right:o,top:i,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&Js(s,r)&&(r=Ks(s,r))}return Qs(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge(e,t,s),r=this.getMerge(e,o,i);return!(!n||!r)&&Qs(n,r)}isInMerge(e,t,s){var o;const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(null===(o=i[t])||void 0===o?void 0:o[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const o=this.getMerge(e,t,s).topLeft;return[o.col,o.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:o,left:i}=this.getMerge(e,t,s);return[i,o]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge(e,t.left,t.top);if(s)return Qs(t,s);const{width:o,height:i}=oo(t);return 1===o&&1===i}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell(e.id,n,t);if(s&&!s.isEmpty())return!0}return!1}getMergeById(e,t){var s;const o=null===(s=this.merges[e])||void 0===s?void 0:s[t];return void 0!==o?Ta(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){const s=this.getters.tryGetSheet(e);if(!s)return 0;return t.some((e=>this.isMergeDestructive(s,e)))?3:0}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&Js(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:o,content:i}=e;if(void 0===i)return 0;const[n,r]=this.getMainCell(o,t,s);return n===t&&r===s?0:4}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge(t,s,o);if(void 0===i||!Qs(e,i))return 5}return 0}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);if(is(s,i)===is(o,n))return;const r=this.getters.getCell(e.id,s,i);let a=this.nextId++;this.history.update("merges",e.id,a,this.getters.getRangeFromSheetXC(e.id,js({left:s,top:i,right:o,bottom:n})));let l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const o=this.getMerge(e.id,n,t);o&&l.add(o.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o=this.getMerge(e.id,s,t);o&&o.id===a||(this.history.update("mergeCellMap",e.id,s,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:t}))}this.history.update("merges",e.id,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge(e,s,o);if(void 0!==r&&Qs(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{width:t,height:i}=oo(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const[s,o]of no(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const 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){const s=this.getters.getSheet(e);for(let e of t)this.addMerge(s,Ws(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...xa(e))}}exportForExcel(e){this.export(e)}}function xa(e){return Object.entries(e).map((([e,t])=>t?Ta(parseInt(e,10),t):void 0)).filter(_s).map((e=>is(e.left,e.top)+":"+is(e.right,e.bottom)))}function Ta(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}Ia.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class Ra extends ma{constructor(){super(...arguments),this.sheetIds={},this.visibleSheets=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":const t=this.visibleSheets.findIndex((t=>t===e.sheetId));return"left"===e.direction&&0===t||"right"===e.direction&&t===this.visibleSheets.length-1?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.visibleSheets.length>1?0:9;case"REMOVE_COLUMNS_ROWS":const s=this.getSheet(e.sheetId);return("COL"===e.dimension?s.cols.length:s.rows.length)>e.elements.length?0:8;case"HIDE_COLUMNS_ROWS":{const t=this.sheets[e.sheetId],s="COL"===e.dimension?t.hiddenColsGroups:t.hiddenRowsGroups,o="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<o.length?0:51}default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIds",t.name,t.id);break;case"RESIZE_COLUMNS_ROWS":const s="COL"===e.dimension?"cols":"rows";for(let t of e.elements)this.setHeaderSize(this.getSheet(e.sheetId),s,t,e.size);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.direction);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],e.elements):this.removeRows(this.sheets[e.sheetId],e.elements);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","hide"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","hide");break;case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","show"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","show");break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e)}}import(e){for(let t of e.sheets)this.sheetIds[t.name]=t.id;for(let t of e.sheets){const e=t.name||r("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,cols:Ds(t.cols||{},s),rows:Ps(t.rows||{},o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(i.id),this.sheets[i.id]=i,this.updateHiddenElementsGroups(i.id,"cols"),this.updateHiddenElementsGroups(i.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(_s).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:Vs(s.rows,t),cols:Us(s.cols,t),merges:[],cells:{},conditionalFormats:[],figures:[],areGridLinesVisible:void 0===s.areGridLinesVisible||s.areGridLinesVisible}}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e,!0)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return no(t).map((([t,s])=>this.getCell(e,t,s)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const s=((t=e).startsWith("'")&&(t=t.slice(1,-1).replace(/''/g,"'")),t);for(const e in this.sheetIds)if(e.toUpperCase()===s.toUpperCase())return this.sheetIds[e]}var t}getSheets(){const{visibleSheets:e,sheets:t}=this;return e.map((e=>t[e])).filter(_s)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}tryGetCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getCol(e,t){const s=this.getSheet(e).cols[t];if(!s)throw new Error(`Col ${s} not found.`);return s}tryGetRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getRow(e,t){const s=this.getSheet(e).rows[t];if(!s)throw new Error(`Row ${s} not found.`);return s}getCell(e,t,s){var o;const i=this.tryGetSheet(e),n=null===(o=null==i?void 0:i.rows[s])||void 0===o?void 0:o.cells[t];if(void 0!==n)return this.getters.getCellById(n)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(_s).map((e=>this.getters.getCellById(e))).filter(_s)}getColsZone(e,t,s){return{top:0,bottom:this.getSheet(e).rows.length-1,left:t,right:s}}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).cols.length-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getHiddenColsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenColsGroups)||[]}getHiddenRowsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenRowsGroups)||[]}getNumberCols(e){return this.getSheet(e).cols.length}getNumberRows(e){return this.getSheet(e).rows.length}getNextSheetName(e="Sheet"){let t=1;const s=this.getSheets().map((e=>e.name));let o=`${e}${t}`;for(;s.includes(o);)o=`${e}${t}`,t++;return o}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,o){let i,n;const r=e[t],a=r[s],l=o-a.size;this.history.update("sheets",e.id,t,s,"size",o),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),i=a.end;for(let o=s+1;o<r.length;o++){const s=r[o];n=s.isHidden?i:i+s.size,this.history.update("sheets",e.id,t,o,"start",i),this.history.update("sheets",e.id,t,o,"end",n),i=n}}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){var o;const i=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[s].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,s,o,i){const n={id:e,name:t,cols:Fs(s),rows:$s(o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("visibleSheets",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.visibleSheets.slice(),o=s.findIndex((t=>t===e)),i=s.splice(o,1);s.splice(o+("left"===t?-1:1),0,i[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=s[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:$.test(o)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIds);o[t]=e.id,delete o[s],this.history.update("sheetIds",o)}duplicateSheet(e,t){const s=this.getSheet(e),o=this.getDuplicateSheetName(s.name),i=JSON.parse(JSON.stringify(s));i.id=t,i.name=o;for(let e=0;e<=i.cols.length;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,i.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[i.name]=i.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),o=a("Copy of %s",e);let i=o.toString();for(;s.includes(i);)i=`${o} (${t})`,t++;return i}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.visibleSheets.slice(),i=o.findIndex((t=>t===e.id));o.splice(i,1),this.history.update("visibleSheets",o);const n=Object.assign({},this.sheetIds);delete n[t],this.history.update("sheetIds",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let s of t)this.moveCellOnColumnsDeletion(e,s);this.updateColumnsStructureOnDeletion(e,t)}removeRows(e,t){t.sort(((e,t)=>t-e));for(let s of bs(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,o){this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"columns"),this.updateColumnsStructureOnAddition(e,t,o)}addRows(e,t,s,o){this.addEmptyRows(e,o),this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"rows"),this.updateRowsStructureOnAddition(e,t,o)}moveCellOnColumnsDeletion(e,t){for(let[s,o]of Object.entries(e.rows)){const i=parseInt(s,10);for(let s in o.cells){const n=parseInt(s,10),r=o.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:i}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:i}))}}}moveCellsOnAddition(e,t,s,o){const i=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==o||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===o||l>=t)&&i.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:a+("rows"===o?s:0)})}}for(let e of i.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const o=s-t+1;for(let[i,n]of Object.entries(e.rows)){const r=parseInt(i,10);if(r>=t&&r<=s)for(let t in n.cells){const s=parseInt(t,10);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:r})}if(r>s)for(let t in n.cells){const s=parseInt(t,10),i=n.cells[t];i&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:i,col:s,row:r-o})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let o=0,i=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?o:o+r;s.push({name:ss(i),size:r,start:o,end:l,isHidden:a}),o=l,i++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const o=[];let i=0,n=0;for(let r in e.cols){if(parseInt(r,10)===t){const{size:t}=e.cols[n];for(let e=0;e<s;e++)o.push({name:ss(n),size:t,start:i,end:i+t}),i+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?i:i+a;o.push({name:ss(n),size:a,start:i,end:c,isHidden:l}),i=c,n++}this.history.update("sheets",e.id,"cols",o),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let o=0,i=0;const n=t.rows.map((e=>e.cells));for(let r in t.rows){const a=t.rows[r],{size:l,isHidden:c}=a,h=c?o:o+l;parseInt(r,10)!==e&&(i++,s.push({start:o,end:h,size:l,cells:n.shift(),name:String(i),isHidden:c}),o=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const o=[];let i=0,n=0,r=0;const a=e.rows.map((e=>e.cells));for(let l in e.rows){const{size:c,isHidden:h}=e.rows[r],d=h?i:i+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,o.push({start:i,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),i=d}this.history.update("sheets",e.id,"rows",o),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,o=e.rows.slice();for(let e=0;e<t;e++)o.push({start:s,end:s,size:0,name:(o.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(os);return{rowNumber:Math.max(e.rowNumber,...new Set(t.map((([e,t])=>t+1)))),colNumber:Math.max(e.colNumber,...new Set(t.map((([e,t])=>e+1))))}}setElementsVisibility(e,t,s,o){let i=0;const n="hide"===o;for(let o=0;o<e[s].length;o++){const{size:r,isHidden:a}=e[s][o],l=t.includes(o)?n:a||!1,c=l?i:i+r;this.history.update("sheets",e.id,s,o,"start",i),this.history.update("sheets",e.id,s,o,"end",c),this.history.update("sheets",e.id,s,o,"isHidden",l),i=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const o="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",i=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const o=e[e.length-1];return o&&o[o.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,o,i)}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?23:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),!t.every(qs))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),o={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Qs(Ks(t=o,e),t);var t}))?0:18}return 0}}Ra.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","tryGetCol","getCol","tryGetRow","getRow","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const La=new Me;La.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const o=e.current.toString(),i=qr(e.current,null===(s=t.cell)||void 0===s?void 0:s.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var o,i;const n=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:null===(i=t.cell)||void 0===i?void 0:i.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case 0:i=0,n=-e.current;break;case 1:i=0,n=e.current;break;case 2:i=-e.current,n=0;break;case 3:i=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies,i,n,r),l=s.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const Ma=new Me;Ma.add("simple_value_copy",{condition:(e,t)=>{var s;return 1===t.length&&!e.isFormula()&&!(null===(s=e.format)||void 0===s?void 0:s.match(_))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===Fe.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_number",{condition:e=>e.evaluated.type===Fe.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],o=!1;for(let i of t)if(i===e&&(o=!0),(null==i?void 0:i.evaluated.type)===Fe.number)s.push(i.evaluated.value);else{if(o)return s;s=[]}return s}(e,t);let o=1;return 2==s.length?o=2*(s[1]-s[0]):s.length>2&&(o=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===Fe.number?e.evaluated.value:0}},sequence:40});const Aa=new Me,_a=(new Me).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],s=[...e.elements].sort(((e,t)=>e-t));for(let o of bs(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Pe.values())_a.contains(e)||_a.add(e,Oa);function Oa(e){return[e]}const Na=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function ka(e,t){return Object.assign({},Na(e),t)}class Fa extends Me{add(e,t){return this.content[e]=ka(e,t),this}addChild(e,t,s){const o=t.splice(0,1)[0];let i=this.content[o];if(!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t)if(i="function"==typeof i.children?void 0:i.children.find((t=>t.id===e)),!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);return i.children.push(ka(e,s)),this}getChildren(e,t){return"function"==typeof e.children?e.children(t).sort(((e,t)=>e.sequence-t.sequence)):e.children.sort(((e,t)=>e.sequence-t.sequence))}getName(e,t){return"function"==typeof e.name?e.name(t):e.name}getShortCut(e){return e.shortCut?e.shortCut:""}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const $a=[Fe.number,Fe.error,Fe.text,Fe.boolean];function Da(e,t){return{index:t,type:e?e.evaluated.type:Fe.empty,value:e?e.evaluated.value:""}}function Pa(e,t,s,o,i){let n=Ve.Success,r=o.right>o.left;if(e.getters.doesIntersectMerge(t,o)){let s;r=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){let o=e.getters.getMerge(t,n,i);o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){r=!0;break}}}const[l,c]=s;if(r)n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i});else{const s=e.getters.getContiguousZone(t,o);Qs(s,o)?n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i}):e.askConfirmation(a("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=s,n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}),(()=>{n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}))}n.isCancelledBecause(48)&&(e.dispatch("SET_SELECTION",{anchor:s,zones:[o],anchorZone:o}),e.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}function Ua(e,t){t.isSuccessful||(t.reasons.includes(19)&&e.notifyUser(a("This operation is not allowed with multiple selections.")),t.reasons.includes(2)&&e.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again.")))}function Va(e,t,s){const o=e.dispatch("PASTE",{target:t,pasteOption:s});Ua(e,o)}function Ba(e){const t=e.getters.getActiveCols();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.right-t.left+1}}function Ha(e){const t=e.getters.getActiveRows();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const Ga=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Wa=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},qa=async e=>{const t=e.getters.getClipboardContent();let s;try{s=await e.clipboard.readText()}catch(e){console.warn("The OS clipboard could not be read."),console.error(e)}const o=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:o,text:s}):Va(e,o)},ja=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Xa=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Ya=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),Ka=e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},Qa=e=>{let t=[...e.getters.getActiveRows()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Ja=e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Delete column %s",ss(t)):a("Delete columns %s - %s",ss(t),ss(s))},el=e=>{let t=[...e.getters.getActiveCols()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},tl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Ua(e,s)},sl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Ua(e,s)},ol=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Ua(e,s)},il=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Ua(e,s)},nl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:o,dimension:"ROW"})},rl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:o,dimension:"ROW"})},al=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:o})},ll=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:o})},cl=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},hl=e=>{e.openLinkEditor()},dl=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Pa(e,o,t,s[0],"ascending")},ul=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Pa(e,o,t,s[0],"descending")},pl=e=>1===e.getters.getSelectedZones().length,gl=new Fa;gl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa,isVisible:pl}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:pl}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:pl,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).add("add_row_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:nl,isVisible:pl}).add("add_column_before",{name:e=>{const t=Ba(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:al,isVisible:pl}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:pl,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:tl}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:sl}).add("delete_row",{name:Ka,sequence:110,action:Qa,isVisible:pl}).add("delete_column",{name:Ja,sequence:120,action:el,isVisible:pl}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:pl}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:ol}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:il}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Ya,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:hl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:cl,separator:!0});const fl=new Fa;fl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:pl,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).add("add_column_before",{name:e=>{const t=Ba(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:al}).add("add_column_after",{name:e=>{const t=Ba(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:ll}).add("delete_column",{name:Ja,sequence:90,action:el}).add("clear_column",{name:e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Clear column %s",ss(t)):a("Clear columns %s - %s",ss(t),ss(s))},sequence:100,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveCols()].map((s=>e.getters.getColsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.getters.getElementsFromSelection("COL");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide column %s",ss(s).toString()):o-s+1===t.length?a("Hide columns %s - %s",ss(s).toString(),ss(o).toString()):a("Hide columns")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenColsGroups(t.id).flat();return t.cols.length>s.length+e.getters.getElementsFromSelection("COL").length},separator:!0}).add("unhide_columns",{name:"Unhide columns",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:110,action:cl});const ml=new Fa;ml.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>ka(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${Ls}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const vl=new Fa;function El(e,t,s){const o=e.getters.getSheetName(t),i=a("Rename Sheet")+(s?" - "+s:"");e.editText(i,o,(s=>{if(null===s||s===o)return;""===s&&El(e,t,a("The sheet name cannot be empty."));const i=e.dispatch("RENAME_SHEET",{sheetId:t,name:s});i.isSuccessful||(i.reasons.includes(11)&&El(e,t,a("A sheet with the name %s already exists. Please select another name.",s)),i.reasons.includes(13)&&El(e,t,a("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",F.join(" "))))}))}vl.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("add_row_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:nl}).add("add_row_after",{name:e=>{const t=Ha(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:rl}).add("delete_row",{name:Ka,sequence:70,action:Qa}).add("clear_row",{name:e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Clear row %s",(t+1).toString()):a("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},sequence:80,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveRows()].map((s=>e.getters.getRowsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.getters.getElementsFromSelection("ROW");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):o-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):a("Hide rows")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenRowsGroups(t.id).flat();return t.rows.length>s.length+e.getters.getElementsFromSelection("ROW").length},separator:!0}).add("unhide_rows",{name:"Unhide rows",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:90,action:cl});const bl=new Fa;bl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{e.dispatch("DELETE_SHEET",{sheetId:e.getters.getActiveSheetId()})}))}).add("duplicate",{name:a("Duplicate"),sequence:20,action:e=>{const t=e.getters.getActiveSheetId(),s=e.uuidGenerator.uuidv4();e.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:s})}}).add("rename",{name:a("Rename"),sequence:30,action:e=>El(e,e.getters.getActiveSheetId())}).add("move_right",{name:a("Move right"),sequence:40,isVisible:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getSheets();return s.findIndex((e=>e.id===t))!==s.length-1},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:a("Move left"),sequence:50,isVisible:e=>{const t=e.getters.getActiveSheetId();return 0!==e.getters.getSheets().findIndex((e=>e.id===t))},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"left"})});const Sl=new Fa;Sl.add("file",{name:a("File"),sequence:10}).add("edit",{name:a("Edit"),sequence:20}).add("view",{name:a("View"),sequence:30}).add("insert",{name:a("Insert"),sequence:40}).add("format",{name:a("Format"),sequence:50}).add("data",{name:a("Data"),sequence:60}).addChild("save",["file"],{name:a("Save"),shortCut:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:a("Undo"),shortCut:"Ctrl+Z",sequence:10,action:e=>e.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:a("Redo"),shortCut:"Ctrl+Y",sequence:20,action:e=>e.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:a("Copy"),shortCut:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Ga}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:Wa}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:qa}).addChild("paste_special",["edit"],{name:a("Paste special"),sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:pl,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).addChild("find_and_replace",["edit"],{name:a("Find and replace"),shortCut:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:a("Delete values"),sequence:70,action:Ya}).addChild("edit_delete_row",["edit"],{name:Ka,sequence:80,action:Qa}).addChild("edit_delete_column",["edit"],{name:Ja,sequence:90,action:el}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:ol}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:il}).addChild("edit_unhide_columns",["edit"],{name:a("Unhide all columns"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"COL",elements:Array.from(Array(t.cols.length).keys())})},isVisible:e=>e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:a("Unhide all rows"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"ROW",elements:Array.from(Array(t.rows.length).keys())})},isVisible:e=>e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:nl,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:rl,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Ba(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:al,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Ba(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:ll,isVisible:e=>0===e.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:a("Insert cells and shift down"),sequence:43,action:tl}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:sl,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const o=e.getters.getSelectedZone();let i=o;const n=e.uuidGenerator.uuidv4();let r;o.left!==o.right&&(i={...o,left:o.left+1});const a=[js(i)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.tryGetCol(l,o.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.tryGetRow(l,o.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=i.left;t<=i.right;t++){const s=e.getters.getCell(l,t,o.top);if(s&&s.evaluated.type!==Fe.number){h=!0;break}}o.left!==o.right&&(r=js({...o,right:o.left,top:h?o.top+1:o.top})),e.dispatch("CREATE_CHART",{sheetId:l,id:n,position:c,definition:{title:"",dataSets:a,labelRange:r,type:"bar",stackedBar:!1,dataSetsHaveTitle:h,background:g,verticalAxisPosition:"left",legendPosition:"top"}});const d=e.getters.getFigure(l,n);e.openSidePanel("ChartPanel",{figure:d})}}).addChild("insert_link",["insert"],{name:a("Link"),separator:!0,sequence:60,action:hl}).addChild("insert_sheet",["insert"],{name:a("New sheet"),sequence:70,action:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getVisibleSheets().findIndex((e=>e===t))+1,o=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:o,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("view_gridlines",["view"],{name:e=>e.getters.getGridLinesVisibility(e.getters.getActiveSheetId())?a("Hide gridlines"):a("Show gridlines"),action:e=>{const t=e.getters.getActiveSheetId();e.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.getters.getGridLinesVisibility(t)})},sequence:5,separator:!0}).addChild("view_formulas",["view"],{name:e=>e.getters.shouldShowFormulas()?a("Hide formulas"):a("Show formulas"),action:e=>e.dispatch("SET_FORMULA_VISIBILITY",{show:!e.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:10}).addChild("format_number",["format"],{name:a("Numbers"),sequence:10,separator:!0}).addChild("format_number_general",["format","format_number"],{name:a("General"),sequence:10,separator:!0,action:e=>za(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>za(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>za(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>za(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>za(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:a("Date time (9/26/2008 22:43:00)"),sequence:60,action:e=>za(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:a("Duration (27:51:38)"),sequence:70,separator:!0,action:e=>za(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Za(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Za(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Za(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Za(e,{strikethrough:!e.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:a("Font size"),sequence:60,separator:!0}).addChild("format_cf",["format"],{name:a("Conditional formatting"),sequence:70,action:cl,separator:!0});for(let e of cs)Sl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Za(t,{fontSize:e.pt})});const Cl=new class extends Me{addTransformation(e,t,s){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:wl,xml:yl}=t.tags,Il=[["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff"],["#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff"],["#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc"],["#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd"],["#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0"],["#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79"],["#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47"],["#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"]],xl=24*Math.max(...Il.map((e=>e.length)))+12;class Tl extends t.Component{constructor(){super(...arguments),this.COLORS=Il}onColorClick(e){const t=e.target.dataset.color;t&&this.props.onColorPicked(t)}}Tl.template=yl`
|
|
1
|
+
!function(e,t){"use strict";function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var o=s(t);let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const s=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>s[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const r=function(e,...t){return n(i(e),...t)},a=function(e,...t){return{toString:function(){return n(i(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=11982760,m=26,v=48,E=63,b=96,S=23,C=15,w=14,y=4,I=200,x=1,T="400",R=10,L="'Roboto', arial",M=["thin","#000"],A="#00f",_=/[ymd:]/,O="#REF",N="START_REVISION",k=a("Invalid expression"),F=["'","*","?","/","\\","[","]"],$=/'|\*|\?|\/|\\|\[|\]/,D=void 0,P="|",U=2e3,V=(new Date).getFullYear(),B=new Date(1899,11,30),H=new Date(0)-B,z=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Z=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,G=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function W(e){let t;const s=(e=e.trim()).match(G);if(s){if(t=function(e){if(e=e.trim(),G.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,r,a,l)}}return null}(s[0]),null===t)return null;e=e.replace(s[0],"").trim()}let o;const i=e.match(z),n=e.match(Z);if(i||n){let t;if(i?(t=i[0],o=q(t,"mdy")):(t=n[0],o=q(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function q(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),o=s?0:1,i=s?1:2,n=s?2:0,r=Number(t[o]),a=Number(t[i]),l=2===t[o].length&&r<10||2===t[i].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return U+t;case 2:return U+(U+t>V+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):V,h=new Date(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h-B;let p=l?`mm${d}dd`:`m${d}d`;return t[n]&&(p=s?p+d+"yyyy":"yyyy"+d+p),{value:Math.round(u/864e5),format:p,jsDate:h}}return null}function j(e){const t=Math.trunc(e);let s=new Date(86400*t*1e3-H),o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function X(e){const t=e.format,s=e.jsDate||j(e.value),o=t.indexOf("h");let i="",n="";return o>0?(i=Y(s,t.substring(0,o-1)),n=K(s,t.substring(o))):0===o?n=K(s,t):o<0&&(i=Y(s,t)),i+(i&&n?" ":"")+n}function Y(e,t){const s=t.match(/\/|-|\s/)[0];return t.split(s).map((s=>{switch(s){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(s)}function K(e,t){let s=t.split(/:|\s/);const o=e.getHours(),i="a"===s[s.length-1];let n=o,r="";return i&&(n=0===n?12:n>12?n-12:n,r=o>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-B)/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}const Q=/(^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?)(?!\w|!)/,J=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function ee(e){return J.test(e.trim())}const te=/,/g;function se(e){let t=Number(e.replace(te,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const oe=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function ie(e){return Number.isInteger(e)?e.toString():oe.format(e)}let ne=[];const re=20;function ae(e,t,s=""){if(e<0)return"-"+ae(-e,t);const o=t>=re?re:t;let i=ne[o];i||(i=new Intl.NumberFormat("en-US",{minimumFractionDigits:o,maximumFractionDigits:o,useGrouping:!1}),ne[o]=i);let n=i.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,o)=>e<0||o<e?`${t}${s}`:t))}return n}function le(e,t){const s=t.split("."),o=1===s.length?0:s[1].match(/0/g).length,i=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=ae(e,o,i);return n?r+"%":r}function ce(e,t){if(!e())throw new Error(t)}const he=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function de(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(ee(e)||""===e)return se(e);const t=W(e);if(t)return t.value;throw new Error(he(e));default:return 0}}function ue(e){if(""===e)throw new Error(he(e));return de(e)}function pe(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ge=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function fe(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(ge(e))}return!1;case"number":return!!e;default:return!1}}function me(e){return j(de(e))}function ve(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function Ee(e,t){ve(e,t,t)}function be(e,t){ve(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(ue(e))}))}function Se(e,t,s,o){let i=o;for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)i=t(i,o[s][n])}else i=s(i,o);return i}function Ce(e,t,s){return Se(e,t,t,s)}function we(e,t,s){return Se(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,ue(s))),s)}function ye(e,t,s){return Se(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?de(s):0):e),((e,s)=>t(e,de(s))),s)}function Ie(e,t){return function(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]))return}else if(!s(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ge(e));return fe(e)}(e))))}function xe(e,t){let s,o,i=e.substring(0,2);"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),ee(o)?o=de(o):"TRUE"!==o&&"FALSE"!==o||(o=fe(o));const n={operator:s,operand:o};return"string"==typeof o&&(t&&(o+="*"),n.regexp=function(e){let t="",s="";for(let o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}(o)),n}function Te(e,t){const{operator:s,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===s)return pe(e)===pe(o);if("<>"===s||"="===s){let i;return i=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===s?i:!i}if(typeof e==typeof o)switch(s){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Re(e,t,s=!1){const o=e.length;if(o%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const i=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==i||o[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=pe(e[t+1]);r.push(xe(l,s))}for(let s=0;s<i;s++)for(let i=0;i<n;i++){let n=!0;for(let t=0;t<o-1;t+=2){if(n=Te(e[t][s][i],r[t/2]),!n)break}n&&t(s,i)}}function Le(e,t){if(void 0===t)return-1;const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t<e[c])return-1;if(typeof e[h]===s&&e[h]<=t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a<=t&&(void 0===o||o<a||o===a&&i<r)&&(o=a,i=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==i?i:-1}class Me{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}remove(e){delete this.content[e]}}const Ae=/(.*?)\((.*?)\)(.*)/,_e=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Oe(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(Ne(e));return s}function Ne(e){let t,s=e.match(Ae),o=s[1].trim(),i=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let o=_e.find((e=>s===e));o?i.push(o):"RANGE<ANY>"===s?i.push("RANGE"):"OPTIONAL"===s?n=!0:"REPEATING"===s?r=!0:"LAZY"===s?a=!0:s.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:o,description:s[3].trim(),type:i};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function ke(e){let t=0,s=0,o=0;for(let i of e.args)t++,i.optional||i.repeating||i.default||s++,i.repeating&&o++;const i=e;return i.minArgRequired=s,i.maxArgPossible=o?1/0:t,i.nbrArgRepeating=o,i.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const s=e-t;return e=>{if(e<=s)return e;return s+((e-s)%t||t)}}(t,o),i}var Fe;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Fe||(Fe={}));const $e=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),De=new Set(["START","ACTIVATE_SHEET","COPY","START_SELECTION","SET_SELECTION","ALTER_SELECTION","START_SELECTION_EXPANSION","PREPARE_SELECTION_EXPANSION","STOP_SELECTION","RESIZE_VIEWPORT","SET_VIEWPORT_OFFSET","SELECT_ALL","SELECT_CELL","SELECT_COLUMN","SELECT_ROW","MOVE_POSITION","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY"]),Pe=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART"]);function Ue(e){return Pe.has(e.type)}class Ve{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Ve}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Be,He,ze,Ze;e.CommandResult=void 0,(Be=e.CommandResult||(e.CommandResult={}))[Be.Success=0]="Success",Be[Be.CancelledForUnknownReason=1]="CancelledForUnknownReason",Be[Be.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Be[Be.MergeIsDestructive=3]="MergeIsDestructive",Be[Be.CellIsMerged=4]="CellIsMerged",Be[Be.InvalidTarget=5]="InvalidTarget",Be[Be.EmptyUndoStack=6]="EmptyUndoStack",Be[Be.EmptyRedoStack=7]="EmptyRedoStack",Be[Be.NotEnoughElements=8]="NotEnoughElements",Be[Be.NotEnoughSheets=9]="NotEnoughSheets",Be[Be.MissingSheetName=10]="MissingSheetName",Be[Be.DuplicatedSheetName=11]="DuplicatedSheetName",Be[Be.DuplicatedSheetId=12]="DuplicatedSheetId",Be[Be.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Be[Be.WrongSheetMove=14]="WrongSheetMove",Be[Be.WrongSheetPosition=15]="WrongSheetPosition",Be[Be.InvalidAnchorZone=16]="InvalidAnchorZone",Be[Be.SelectionOutOfBound=17]="SelectionOutOfBound",Be[Be.TargetOutOfSheet=18]="TargetOutOfSheet",Be[Be.WrongPasteSelection=19]="WrongPasteSelection",Be[Be.EmptyClipboard=20]="EmptyClipboard",Be[Be.EmptyRange=21]="EmptyRange",Be[Be.InvalidRange=22]="InvalidRange",Be[Be.InvalidSheetId=23]="InvalidSheetId",Be[Be.InputAlreadyFocused=24]="InputAlreadyFocused",Be[Be.MaximumRangesReached=25]="MaximumRangesReached",Be[Be.InvalidChartDefinition=26]="InvalidChartDefinition",Be[Be.EmptyDataSet=27]="EmptyDataSet",Be[Be.InvalidDataSet=28]="InvalidDataSet",Be[Be.InvalidLabelRange=29]="InvalidLabelRange",Be[Be.InvalidAutofillSelection=30]="InvalidAutofillSelection",Be[Be.WrongComposerSelection=31]="WrongComposerSelection",Be[Be.MinBiggerThanMax=32]="MinBiggerThanMax",Be[Be.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",Be[Be.MidBiggerThanMax=34]="MidBiggerThanMax",Be[Be.MinBiggerThanMid=35]="MinBiggerThanMid",Be[Be.FirstArgMissing=36]="FirstArgMissing",Be[Be.SecondArgMissing=37]="SecondArgMissing",Be[Be.MinNaN=38]="MinNaN",Be[Be.MidNaN=39]="MidNaN",Be[Be.MaxNaN=40]="MaxNaN",Be[Be.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",Be[Be.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",Be[Be.MinInvalidFormula=43]="MinInvalidFormula",Be[Be.MidInvalidFormula=44]="MidInvalidFormula",Be[Be.MaxInvalidFormula=45]="MaxInvalidFormula",Be[Be.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",Be[Be.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",Be[Be.InvalidSortZone=48]="InvalidSortZone",Be[Be.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",Be[Be.MergeOverlap=50]="MergeOverlap",Be[Be.TooManyHiddenElements=51]="TooManyHiddenElements",Be[Be.Readonly=52]="Readonly",Be[Be.InvalidOffset=53]="InvalidOffset",Be[Be.InvalidViewportSize=54]="InvalidViewportSize",Be[Be.FigureDoesNotExist=55]="FigureDoesNotExist",Be[Be.DuplicatedFigureId=56]="DuplicatedFigureId",Be[Be.DuplicatedChartId=57]="DuplicatedChartId",Be[Be.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(He||(He={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(ze||(ze={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(Ze||(Ze={}));const Ge={description:a("Absolute value of a number."),args:Oe(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(de(e))},isExported:!0},We={description:a("Inverse cosine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},qe={description:a("Inverse hyperbolic cosine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},je={description:a("Inverse cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Xe={description:a("Inverse hyperbolic cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)>1),a("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ye={description:a("Inverse sine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ke={description:a("Inverse hyperbolic sine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(de(e))},isExported:!0},Qe={description:a("Inverse tangent of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(de(e))},isExported:!0},Je={description:a("Angle from the X axis to a point (x,y), in radians."),args:Oe(`\n x (number) ${a("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${a("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=de(e),o=de(t);return ce((()=>0!==s||0!==o),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,s)},isExported:!0},et={description:a("Inverse hyperbolic tangent of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},tt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.ceil(s/o)*o:0},isExported:!0},st={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.ceil(i/o)*o;return 0===de(s)?-Math.floor(Math.abs(i)/o)*o:-Math.ceil(Math.abs(i)/o)*o},isExported:!0},ot={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return st.compute(e,t,0)},isExported:!0},it={description:a("Cosine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(de(e))},isExported:!0},nt={description:a("Hyperbolic cosine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(de(e))},isExported:!0},rt={description:a("Cotangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},at={description:a("Hyperbolic cotangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},lt={description:a("Number of empty values."),args:Oe(`\n value1 (any, range) ${a("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${a("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},ct={description:a("A conditional count across a range."),args:Oe(`\n range (range) ${a("The range that is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0},ht={description:a("Count values depending on multiple criteria."),args:Oe(`\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0};function dt(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ut={description:a("Counts number of unique values in a range."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>dt(t)?e.add(t):e),new Set).size}},pt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=new Set;return Re(t,((t,o)=>{const i=e[t][o];dt(i)&&s.add(i)})),s.size}},gt={description:a("Cosecant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ft={description:a("Hyperbolic cosecant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},mt={description:a("Converts from another base to decimal."),args:Oe(`\n value (string) ${a("The number to convert.")},\n base (number) ${a("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let s=de(t);s=Math.floor(s),ce((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const o=pe(e);if(""===o)return 0;ce((()=>!!o.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",o,s.toString()));const i=parseInt(o,s);return ce((()=>!isNaN(i)),a("The value (%s) must be a valid base %s representation.",o,s.toString())),i},isExported:!0},vt={description:a("Converts an angle value in radians to degrees."),args:Oe(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*de(e)/Math.PI},isExported:!0},Et={description:a("Euler's number, e (~2.718) raised to a power."),args:Oe(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(de(e))},isExported:!0},bt={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.floor(s/o)*o:0},isExported:!0},St={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.floor(i/o)*o;return 0===de(s)?-Math.ceil(Math.abs(i)/o)*o:-Math.floor(Math.abs(i)/o)*o},isExported:!0},Ct={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return St.compute(e,t,0)},isExported:!0},wt={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},yt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return st.compute(e,t,0)},isExported:!0},It={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},xt={description:a("The logarithm of a number, base e (euler's number)."),args:Oe(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Tt={description:a("Modulo (remainder) operator."),args:Oe(`\n dividend (number) ${a("The number to be divided to find the remainder.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);ce((()=>0!==s),a("The divisor must be different from 0."));const o=de(e)%s;return o>0&&s<0||o<0&&s>0?o+s:o},isExported:!0},Rt={description:a("Rounds a number up to the nearest odd integer."),args:Oe(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Lt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Mt={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(e),o=de(t);return ce((()=>s>=0||Number.isInteger(o)),a("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(s,o)},isExported:!0},At={description:a("Result of multiplying a series of numbers together."),args:Oe(`\n factor1 (number, range<number>) ${a("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${a("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(s*=o,t+=1);else null!=o&&(s*=ue(o),t+=1);return 0===t?0:s},isExported:!0},_t={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Ot={description:a("Random integer between two values, inclusive."),args:Oe(`\n low (number) ${a("The low end of the random range.")}\n high (number) ${a("The high end of the random range.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){let s=de(e);Number.isInteger(s)||(s=Math.ceil(s));let o=de(t);return Number.isInteger(o)||(o=Math.floor(o)),ce((()=>s<=o),a("The high (%s) must be greater than or equal to the low (%s).",o.toString(),s.toString())),s+Math.ceil((o-s+1)*Math.random())-1},isExported:!0},Nt={description:a("Rounds a number according to standard rules."),args:Oe(`\n value (number) ${a("The value to round to places number of places.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},kt={description:a("Rounds down a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},Ft={description:a("Rounds up a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},$t={description:a("Secant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(de(e))},isExported:!0},Dt={description:a("Hyperbolic secant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(de(e))},isExported:!0},Pt={description:a("Sine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(de(e))},isExported:!0},Ut={description:a("Hyperbolic sine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(de(e))},isExported:!0},Vt={description:a("Positive square root of a positive number."),args:Oe(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);return ce((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Bt={description:a("Sum of a series of numbers and/or cells."),args:Oe(`\n value1 (number, range<number>) ${a("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${a("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){return we(e,((e,t)=>e+t),0)},isExported:!0},Ht={description:a("A conditional sum across a range."),args:Oe(`\n criteria_range (range) ${a("The range which is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${a("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return Re([e,t],((e,t)=>{const i=s[e][t];"number"==typeof i&&(o+=i)})),o},isExported:!0},zt={description:a("Sums a range depending on multiple criteria."),args:Oe(`\n sum_range (range) ${a("The range to sum.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges to check.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s+=i)})),s},isExported:!0},Zt={description:a("Tangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(de(e))},isExported:!0},Gt={description:a("Hyperbolic tangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(de(e))},isExported:!0},Wt={description:a("Truncates a number."),args:Oe(`\n value (number) ${a("The value to be truncated.")}\n places (number, default=0) ${a("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);return 0===o?Math.trunc(s):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(s*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var qt=Object.freeze({__proto__:null,ABS:Ge,ACOS:We,ACOSH:qe,ACOT:je,ACOTH:Xe,ASIN:Ye,ASINH:Ke,ATAN:Qe,ATAN2:Je,ATANH:et,CEILING:tt,CEILING_MATH:st,CEILING_PRECISE:ot,COS:it,COSH:nt,COT:rt,COTH:at,COUNTBLANK:lt,COUNTIF:ct,COUNTIFS:ht,COUNTUNIQUE:ut,COUNTUNIQUEIFS:pt,CSC:gt,CSCH:ft,DECIMAL:mt,DEGREES:vt,EXP:Et,FLOOR:bt,FLOOR_MATH:St,FLOOR_PRECISE:Ct,ISEVEN:wt,ISO_CEILING:yt,ISODD:It,LN:xt,MOD:Tt,ODD:Rt,PI:Lt,POWER:Mt,PRODUCT:At,RAND:_t,RANDBETWEEN:Ot,ROUND:Nt,ROUNDDOWN:kt,ROUNDUP:Ft,SEC:$t,SECH:Dt,SIN:Pt,SINH:Ut,SQRT:Vt,SUM:Bt,SUMIF:Ht,SUMIFS:zt,TAN:Zt,TANH:Gt,TRUNC:Wt});const jt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Xt(e){return e.toString(16).padStart(6,"0")}let Yt=0;function Kt(){return Yt=++Yt%jt.length,jt[Yt]}function Qt(e){return e.includes("rgb")?function(e){return e.slice(4,-1).split(",").map((e=>parseInt(e,10).toString(16).padStart(2,"0"))).join("").toUpperCase()}(e):(3===(e=e.replace("#","").toUpperCase()).length&&(e=e.split("").reduce(((e,t)=>e+t+t),"")),e)}const Jt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),es=new RegExp(/^\s*('.+'!|[^']+!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7})?$/,"i");function ts(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function ss(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):ss(Math.floor(e/26)-1)+ss(e%26)}function os(e){const t=(e=e.toUpperCase().trim()).match(Jt);if(null!==t){const[s,o,i]=t;if(s===e){const e=function(e){let t=0;const s=e.length;for(let o=0;o<s;o++)t+=(e.charCodeAt(o)-65+(o<s-1?1:0))*26**(s-o-1);return t}(o);return[e,parseInt(i,10)-1]}}throw new Error(`Invalid cell description: ${e}`)}function is(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+ss(e)+(s.rowFixed?"$":"")+String(t+1)}const ns=140,rs=20,as=.035;function ls(e){return rs+(ns-rs)*Math.exp(-as*(e-1))}const cs=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],hs={};for(let e of cs)hs[e.pt]=e.px;function ds(e){return JSON.stringify(e,Object.keys(e).sort())}function us(e){return'"'===e[0]&&'"'===e[e.length-1]?e.slice(1).slice(0,e.length-2):e}function ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const s in e)t[s]=gs(e[s]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function fs(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ms(e,t,s){return e<t?t:e>s?s:e}function vs(e,t,s){const o=s.italic?"italic ":"",i=s.bold?"bold":T,n=s.fontSize||R,r=hs[n];return e.font=`${o}${i} ${r}px ${L}`,e.measureText(t).width}function Es(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function bs(e){return e.reduce(((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ss(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Cs(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function ws(e){return null!==W(e)}const ys=/^\[([^\[]+)\]\((.+)\)$/,Is=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function xs(e){return ys.test(e)}function Ts(e,t){return`[${e}](${t})`}function Rs(e){const t=e.match(ys)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const Ls="o-spreadsheet://";function Ms(e){if(!xs(e))return!1;const{url:t}=Rs(e);return t.startsWith(Ls)}function As(e){if(e.startsWith(Ls))return e.substr(Ls.length);throw new Error(`${e} is not a valid sheet link`)}function _s(e){return void 0!==e}const Os={};function Ns(e,t){for(let[s,o]of Object.entries(t))if(ds(o)===ds(e))return parseInt(s,10);const s=Object.keys(t),o=0===s.length?0:Math.max(...s.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function ks(e){let t,s=!1;const o=()=>(s||(t=e(),s=!0),t);return o.map=e=>ks((()=>e(o()))),o}function Fs(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+b,size:b,name:ss(o)};t.push(e),s=e.end}return t}function $s(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+S,size:S,name:String(o+1),cells:{}};t.push(e),s=e.end}return t}function Ds(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||b,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:ss(n)};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Ps(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||S,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Us(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==b||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}function Vs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==S||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}class Bs{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function Hs(e,t,s){return[zs(e,"cols",Es(t,e.cols.length)),zs(e,"rows",Es(s,e.rows.length))]}function zs(e,t,s){const o=e[t];return s.find((e=>!o[e].isHidden))}function Zs(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function Gs(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,o,i,n,r=os(t[0].trim());if(i=n=r[0],s=o=r[1],2===t.length){let e=os(t[1].trim());n=e[0],o=e[1]}return{top:s,bottom:o,left:i,right:n}}function Ws(e){let{top:t,bottom:s,left:o,right:i}=Gs(e);return i<o&&([i,o]=[o,i]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:o,right:i}}function qs(e){return!(isNaN(e.bottom)||isNaN(e.top)||isNaN(e.left)||isNaN(e.right))&&(!(e.top<0||e.left<0||e.right<0||e.bottom<0)&&(e.bottom>=e.top&&e.right>=e.left))}function js(e){const{top:t,bottom:s,left:o,right:i}=e;return t===s&&o===i?is(o,t):`${is(o,t)}:${is(i,s)}`}function Xs(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ro(e,n,"RESIZE",i):r<e[t]?ro(e,n,"MOVE",i):{...e}}function Ys(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function Ks(e,t){return{top:Math.min(e.top,t.top),left:Math.min(e.left,t.left),bottom:Math.max(e.bottom,t.bottom),right:Math.max(e.right,t.right)}}function Qs(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Js(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function eo(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function to(e,t){const s={};for(let t of e)if(t){const e=Ws(t);for(let t=e.left;t<=e.right;t++)void 0===s[t]&&(s[t]=[]),s[t].push({top:e.top,bottom:e.bottom,remove:!1})}for(let e of t){const t=Ws(e);for(let e=t.left;e<=t.right;e++)void 0===s[e]&&(s[e]=[]),s[e].push({top:t.top,bottom:t.bottom,remove:!0})}const o=[];for(let[e,t]of Object.entries(s))o.push({col:parseInt(e),ranges:so(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let o=[],i=0;for(let e=0;e<=t.length-1;e++){let n=[];if(i+1===t[e].col)for(let s of t[e].ranges){let i=!1;for(let e of o)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),i=!0);i||n.push({top:s.top,bottom:s.bottom,startCol:t[e].col})}else n=t[e].ranges.map((s=>({top:s.top,bottom:s.bottom,startCol:t[e].col})));const r=o.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});i=t[e].col,o=n}for(let e of o)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});return s}(o).map(js)}function so(e){const t=new Set,s=new Set;for(let o of e)for(let e=o.top;e<=o.bottom;e++)o.remove?s.add(e):t.add(e);const o=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),i=[];let n;for(let e of o)n?e===n.bottom+1?n.bottom=e:(i.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&i.push({top:n.top,bottom:n.bottom}),i}function oo(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function io(e){const{width:t,height:s}=oo(e);return 1===t||1===s}function no(e){const t=[],[s,o]=[e.right,e.left].sort(((e,t)=>e-t)),[i,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Es(s,o+1))for(const s of Es(i,n+1))t.push([e,s]);return t}function ro(e,t,s,o){const i="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=o),n[i]+=o,n}function ao(e){return e.reverse().filter(((e,t,s)=>t===s.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}function lo(e){return{top:Math.min(e.top,e.bottom),bottom:Math.max(e.top,e.bottom),left:Math.min(e.left,e.right),right:Math.max(e.left,e.right)}}function co(e,t,s){let o=[],i=[],n=0,r=0;Ee([e],(e=>{o.push(e),n+=1})),Ee([t],(e=>{i.push(e),r+=1})),ce((()=>n===r),a("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),r.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}ce((()=>0!==l&&(!s||1!==l)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let p=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function ho(e,t,s){let o=0,i=0;const n=s?ye:we;i=n(e,((e,t)=>(o+=1,e+t)),0),ce((()=>0!==o&&(!t||1!==o)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=i/o;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(o-(t?1:0))}function uo(e,t,s){const o=de(t);ce((()=>s?0<=o&&o<=1:0<o&&o<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let i,n=[],r=0;Ee(e,(e=>{"number"==typeof e&&(i=Le(n,e),n.splice(i+1,0,e),r++)})),ce((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*o;if(s||(ce((()=>1<=l&&l<=r),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),l--),Number.isInteger(l))return n[l];const c=Math.ceil(l),h=Math.floor(l);return n[c]*(l-h)+n[h]*(c-l)}const po={description:a("Average magnitude of deviations from mean."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return we(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},go={description:a("Numerical average value in a dataset, ignoring text."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},fo=a("[[FUNCTION_NAME]] has mismatched range sizes."),mo=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),vo={description:a("Weighted average."),args:Oe(`\n values (number, range<number>) ${a("Values to average.")}\n weights (number, range<number>) ${a("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${a("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${a("Additional weights.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t,s,o=0,i=0;ce((()=>e.length%2==0),a("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],s=e[n+1],Array.isArray(t)){ce((()=>Array.isArray(s)),fo);let e=t.length,n=t[0].length;ce((()=>e===s.length&&n===s[0].length),fo);for(let r=0;r<e;r++)for(let e=0;e<n;e++){let n=t[r][e],l=s[r][e],c="number"==typeof n,h="number"==typeof l;ce((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(ce((()=>l>=0),mo),o+=n*l,i+=l)}}else s=de(s),t=de(t),ce((()=>s>=0),mo),o+=t*s,i+=s;return ce((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i}},Eo={description:a("Numerical average value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=ye(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},bo={description:a("Average of values depending on criteria."),args:Oe(`\n criteria_range (range) ${a("The range to check against criterion.")}\n criterion (string) ${a("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${a("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,s){null==s&&(s=e);let o=0,i=0;return Re([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(o+=1,i+=r)})),ce((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},So={description:a("Average of values depending on multiple criteria."),args:Oe(`\n average_range (range) ${a("The range to average.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0,o=0;return Re(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(s+=1,o+=n)})),ce((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/s},isExported:!0},Co={description:a("The number of numeric values in dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let s of e)if(Array.isArray(s))for(let e of s)for(let s of e)"number"==typeof s&&(t+=1);else("string"!=typeof s||ee(s)||W(s))&&(t+=1);return t},isExported:!0},wo={description:a("The number of values in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},yo={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!1)},isExported:!0},Io={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!1)},isExported:!0},xo={description:a("The sample covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return co(e,t,!0)},isExported:!0},To={description:a("Nth largest element from a data set."),args:Oe(`\n data (any, range) ${a("Array or range containing the dataset to consider.")}\n n (number) ${a("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.shift(),n--))}));const r=i.shift();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ro={description:a("Maximum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Lo={description:a("Maximum numeric value in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Mo={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=-1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s<i?i:s)})),s===-1/0?0:s},isExported:!0},Ao={description:a("Median value in a numeric dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=[];return be(e,(e=>{t.push(e)})),uo(t,.5,!0)},isExported:!0},_o={description:a("Minimum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Oo={description:a("Minimum numeric value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},No={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s>i?i:s)})),s===1/0?0:s},isExported:!0},ko={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return $o.compute(e,t)},isExported:!0},Fo={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],t,!1)},isExported:!0},$o={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],t,!0)},isExported:!0},Do={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return Uo.compute(e,t)},isExported:!0},Po={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],.25*Math.trunc(de(t)),!1)},isExported:!0},Uo={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return uo([e],.25*Math.trunc(de(t)),!0)},isExported:!0},Vo={description:a("Nth smallest element in a data set."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n n (number) ${a("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.pop(),n--))}));const r=i.pop();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Bo={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(qo.compute(...e))},isExported:!0},Ho={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(jo.compute(...e))},isExported:!0},zo={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xo.compute(...e))},isExported:!0},Zo={description:a("Standard deviation of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yo.compute(...e))},isExported:!0},Go={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ko.compute(...e))},isExported:!0},Wo={description:a("Standard deviation of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Qo.compute(...e))},isExported:!0},qo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!1)},isExported:!0},jo={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!1)},isExported:!0},Xo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!1)},isExported:!0},Yo={description:a("Variance of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!0,!0)},isExported:!0},Ko={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!1)},isExported:!0},Qo={description:a("Variance of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ho(e,!1,!0)},isExported:!0};var Jo=Object.freeze({__proto__:null,AVEDEV:po,AVERAGE:go,AVERAGE_WEIGHTED:vo,AVERAGEA:Eo,AVERAGEIF:bo,AVERAGEIFS:So,COUNT:Co,COUNTA:wo,COVAR:yo,COVARIANCE_P:Io,COVARIANCE_S:xo,LARGE:To,MAX:Ro,MAXA:Lo,MAXIFS:Mo,MEDIAN:Ao,MIN:_o,MINA:Oo,MINIFS:No,PERCENTILE:ko,PERCENTILE_EXC:Fo,PERCENTILE_INC:$o,QUARTILE:Do,QUARTILE_EXC:Po,QUARTILE_INC:Uo,SMALL:Vo,STDEV:Bo,STDEV_P:Ho,STDEV_S:zo,STDEVA:Zo,STDEVP:Go,STDEVPA:Wo,VAR:qo,VAR_P:jo,VAR_S:Xo,VARA:Yo,VARP:Ko,VARPA:Qo});function ei(e,t,s){var o;const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(pe(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(a("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||n-1<r)throw new Error(a("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),n.toString()))}else{const e=pe(t).toUpperCase();if(r=null!==(o=i.get(e))&&void 0!==o?o:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",pe(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Error(a("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],n=!0;for(let r=0;r<s.length;r++){const a=pe(s[r][0]).toUpperCase(),l=i.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(n){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Re(o,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const ti=Oe(`\n database (range) ${a("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.")}\n field (any) ${a("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${a("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),si={description:a("Average of a set of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return go.compute([o])},isExported:!0},oi={description:a("Counts values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Co.compute([o])},isExported:!0},ii={description:a("Counts values and text from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return wo.compute([o])},isExported:!0},ni={description:a("Single value from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return ce((()=>1===o.length),a("More than one match found in DGET evaluation.")),o[0]},isExported:!0},ri={description:a("Maximum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Ro.compute([o])},isExported:!0},ai={description:a("Minimum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return _o.compute([o])},isExported:!0},li={description:a("Product of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return At.compute([o])},isExported:!0},ci={description:a("Standard deviation of population sample from table."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Bo.compute([o])},isExported:!0},hi={description:a("Standard deviation of entire population from table."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Go.compute([o])},isExported:!0},di={description:a("Sum of values from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Bt.compute([o])},isExported:!0},ui={description:a("Variance of population sample from table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return qo.compute([o])},isExported:!0},pi={description:a("Variance of a population from a table-like range."),args:ti,returns:["NUMBER"],compute:function(e,t,s){const o=ei(e,t,s);return Ko.compute([o])},isExported:!0};var gi=Object.freeze({__proto__:null,DAVERAGE:si,DCOUNT:oi,DCOUNTA:ii,DGET:ni,DMAX:ri,DMIN:ai,DPRODUCT:li,DSTDEV:ci,DSTDEVP:hi,DSUM:di,DVAR:ui,DVARP:pi});const fi=new Date(1899,11,30);function mi(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const vi={description:a("Converts year/month/day into a date."),args:Oe(`\n year (number) ${a("The year component of the date.")}\n month (number) ${a("The month component of the date.")}\n day (number) ${a("The day component of the date.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){let o=Math.trunc(de(e));const i=Math.trunc(de(t)),n=Math.trunc(de(s));ce((()=>0<=o&&o<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const r=new Date(o,i-1,n).getTime()-fi.getTime();return ce((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},Ei={description:a("Converts a date string to a date value."),args:Oe(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);return ce((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},bi={description:a("Day of the month that a specific date falls on."),args:Oe(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getDate()},isExported:!0},Si={description:a("Number of days between two dates."),args:Oe(`\n end_date (date) ${a("The end of the date range.")}\n start_date (date) ${a("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=me(e),o=me(t),i=s.getTime()-o.getTime();return Math.round(i/864e5)},isExported:!0},Ci={description:a("Date a number of months before/after another date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new Date(i,n+o,r).getTime()-fi.getTime();return Math.round(a/864e5)},isExported:!0},wi={description:a("Last day of a month before or after a date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=new Date(i,n+o+1,0).getTime()-fi.getTime();return Math.round(r/864e5)},isExported:!0},yi={description:a("Hour component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getHours()},isExported:!0},Ii={description:a("ISO week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e){const t=me(e),s=t.getFullYear();let o=1;for(;4!==new Date(s,0,o).getDay();)o+=1;const i=new Date(s,0,o-3);let n=31;for(;4!==new Date(s,11,n).getDay();)n-=1;const r=new Date(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new Date(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Date(s-1,0,e).getDay();)e+=1;l=new Date(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/864e5;return Math.floor(c/7)+1},isExported:!0},xi={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMinutes()},isExported:!0},Ti={description:a("Month of the year a specific date falls in"),args:Oe(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMonth()+1},isExported:!0},Ri={description:a("Net working days between two provided days."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s){return Mi.compute(e,t,1,s)},isExported:!0};function Li(e){if("string"==typeof e){ce((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),a('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let s=0;s<7;s++)"1"===e[s]&&t.push((s+1)%7);return t}if("number"==typeof e)return ce((()=>1<=e&&e<=7||11<=e&&e<=17),a("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(a("The weekend (%s) must be a number or a string.",e.toString()))}const Mi={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1,o){const i=me(e),n=me(t),r=Li(s);let a=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);a.add(t.getTime())}));const l=i.getTime()>n.getTime(),c=new Date((l?i:n).getTime());let h=new Date((l?n:i).getTime());const d=c.getTime();let u=h.getTime(),p=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(p+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-p:p},isExported:!0},Ai={description:a("Current date and time as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy hh:mm:ss"},compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-fi.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},_i={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getSeconds()},isExported:!0},Oi={description:a("Converts hour/minute/second into a time."),args:Oe(`\n hour (number) ${a("The hour component of the time.")}\n minute (number) ${a("The minute component of the time.")}\n second (number) ${a("The second component of the time.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"hh:mm:ss a"},compute:function(e,t,s){let o=Math.trunc(de(e)),i=Math.trunc(de(t)),n=Math.trunc(de(s));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,ce((()=>o>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+i/1440+n/86400},isExported:!0},Ni={description:a("Converts a time string into its serial number representation."),args:Oe(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);ce((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},ki={description:a("Current date as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-fi.getTime();return Math.round(t/864e5)},isExported:!0},Fi={description:a("Day of the week of the date provided (as number)."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t)),i=s.getDay();return ce((()=>[1,2,3].includes(o)),a("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?i+1:2===o?0===i?7:i:0===i?6:i-1},isExported:!0},$i={description:a("Week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t));if(ce((()=>1===o||2===o||11<=o&&o<=17||21===o),a("The type (%s) is out of range.",o.toString())),21===o)return Ii.compute(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,l=new Date(n,0,r);for(;l.getDay()!==i;)r+=1,l=new Date(n,0,r);const c=(s.getTime()-l.getTime())/864e5;return c<0?1:Math.floor(c/7)+(1===r?1:2)},isExported:!0},Di={description:a("Number of working days from start date."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){return Pi.compute(e,t,1,s)},isExported:!0},Pi={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s=1,o){let i=me(e),n=Math.trunc(de(t));"string"==typeof s&&ce((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=Li(s);let l=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);l.add(t.getTime())}));let c=new Date(i.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),r.includes(c.getDay())||l.has(h)||(u-=1);const p=h-fi.getTime();return Math.round(p/864e5)},isExported:!0},Ui={description:a("Year specified by a given date."),args:Oe(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getFullYear()},isExported:!0},Vi={description:a("Exact number of years between two dates."),args:Oe(`\n start_date (date) ${a("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.")}\n end_date (date) ${a("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.")}\n day_count_convention (number, default=0) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s=0){let o=Math.trunc(de(e)),i=Math.trunc(de(t));const n=Math.trunc(de(s));if(ce((()=>o>=0),a("The start_date (%s) must be positive or null.",o.toString())),ce((()=>i>=0),a("The end_date (%s) must be positive or null.",i.toString())),ce((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),o===i)return 0;if(o>i){const e=i;i=o,o=e}const r=me(o),l=me(i);let c=r.getDate(),h=l.getDate();const d=r.getMonth(),u=l.getMonth(),p=r.getFullYear(),g=l.getFullYear();let f=0,m=0;switch(n){case 0:31===c&&(c=30),30===c&&31===h&&(h=30),1===d&&c===(mi(p)?29:28)&&(c=30,1===u&&h===(mi(g)?29:28)&&(h=30)),f=p+(30*d+c)/360,m=g+(30*u+h)/360;break;case 1:let e=365;const t=p===g;if(!t&&!(p+1===g)||!t&&d<u||!t&&d===u&&c<h){let t=0,s=0;for(let e=p;e<=g;e++)t++,s+=mi(e)?366:365;e=s/t}else t?mi(p)&&(e=366):(mi(p)&&d<2&&(e=366),mi(g)&&(u>1||1===u&&29===h)&&(e=366));f=o/e,m=i/e;break;case 2:f=o/360,m=i/360;break;case 3:f=o/365,m=i/365;break;case 4:31===c&&(c=30),31===h&&(h=30),f=p+(30*d+c)/360,m=g+(30*u+h)/360}return m-f}};var Bi=Object.freeze({__proto__:null,DATE:vi,DATEVALUE:Ei,DAY:bi,DAYS:Si,EDATE:Ci,EOMONTH:wi,HOUR:yi,ISOWEEKNUM:Ii,MINUTE:xi,MONTH:Ti,NETWORKDAYS:Ri,NETWORKDAYS_INTL:Mi,NOW:Ai,SECOND:_i,TIME:Oi,TIMEVALUE:Ni,TODAY:ki,WEEKDAY:Fi,WEEKNUM:$i,WORKDAY:Di,WORKDAY_INTL:Pi,YEAR:Ui,YEARFRAC:Vi});const Hi={description:a("Compare two numeric values, returning 1 if they're equal."),args:Oe(`\n number1 (number) ${a("The first number to compare.")}\n number2 (number, default=0) ${a("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return de(e)===de(t)?1:0},isExported:!0};var zi=Object.freeze({__proto__:null,DELTA:Hi});function Zi(e,t,s,o,i=1e-10){let n,r,l,c=s,h=!1,d=0;do{l=e(c),n=c-l/t(c),r=Math.abs(n-c),c=n,h=r<i||Math.abs(l)<i,ce((()=>d<o),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Gi={description:a("Depreciation via declining balance method."),args:Oe(`\n cost (number) ${a("The initial cost of the asset.")}\n salvage (number) ${a("The value of the asset at the end of depreciation.")}\n life (number) ${a("The number of periods over which the asset is depreciated.")}\n period (number) ${a("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${a("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o,...i){const n=de(e),r=de(t),l=de(s),c=Math.trunc(de(o)),h=i.length?Math.trunc(de(i[0])):12,d=l+(12===h?0:1);ce((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),ce((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),ce((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),ce((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),ce((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ce((()=>c<=d),a("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let p=1-Math.pow(r/n,1/l);p=Math.round(1e3*p)/1e3;let g=n,f=n*(1-p*u);for(let e=1;e<c;e++)g=f,f=g*(1-p),e===l&&(f=g*(1-p*(1-u)));return g-f}},Wi={description:a("Number of periods for an investment to reach a value."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=de(s),h=de(o),d=Math.trunc(de(i)),u=Math.trunc(de(n));ce((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),ce((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),ce((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Vi.compute(r,l,u),g=p-Math.trunc(p)||1/d,f=Math.ceil(p*d),m=c/d,v=h/d;let E=0,b=0;for(let e=1;e<=f;e++){const t=(m+(e===f?1:0))/(1+v)**e;b+=(g+(e-1)/d)*t,E+=t}return 0===E?0:b/E}},qi={description:a("Future value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n present_value (number, default=0) ${a("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},ji={description:a("Internal rate of return given periodic cashflows."),args:Oe(`\n cashflow_amounts (number, range<number>) ${a("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${a("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"0%"},compute:function(e,t=.1){const s=de(t);ce((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let o=!1,i=!1,n=[];be([e],(e=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)})),ce((()=>o&&i),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Zi((function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*e**(o-i))),t*e**o)}(e,r,n)}),(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*(o-i)*e**(o-i-1))),t*o*e**(o-1))}(e,r,n)}),s+1,20,1e-5)-1}},Xi={description:a("Modified Macaulay duration."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){return Wi.compute(e,t,s,o,i,n)/(1+de(o)/Math.trunc(de(i)))}};const Yi={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Oe(`\n discount (number) ${a("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${a("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${a("Additional future cash flows.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,...t){const s=de(e);return ce((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let o=0;return we(s,((t,s)=>(o++,t+s/(1+e)**o)),t)}(s,0,t)}},Ki={description:a("Computes the number of periods needed for an investment to reach a value."),args:Oe(`\n rate (number) ${a("The rate at which the investment grows each period.")}\n present_value (number) ${a("The investment's current value.")}\n future_value (number) ${a("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,s){const o=de(e),i=de(t),n=de(s);return ce((()=>o>0),a("The rate (%s) must be strictly positive.",o.toString())),ce((()=>i>0),a("The present_value (%s) must be strictly positive.",i.toString())),ce((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(i))/Math.log(1+o)}},Qi={description:a("Present value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n future_value (number, default=0) ${a("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},Ji={description:a("Price of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=Vi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=1+d/p,b=100*h/p;if(1===m)return(b+u)/(v*d/p+1)-b*(1-v);let S=0;for(let e=1;e<=m;e++)S+=b/E**(e-1+v);return u/E**(m-1+v)+S-b*(1-v)}},en={description:a("Annual yield of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought per 100 face value.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=Vi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=100*h/p;if(1===m){const e=d+E*(1-v);return(u+E-e)*p*(1/v)/e}const b=Zi((function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},tn={description:a("Annual yield of a security paying interest at maturity."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${a("The date the security was initially issued.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=Math.trunc(de(s)),h=de(o),d=de(i),u=Math.trunc(de(n));ce((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),ce((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Vi.compute(c,l,u),g=Vi.compute(c,r,u),f=Vi.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var sn=Object.freeze({__proto__:null,DB:Gi,DURATION:Wi,FV:qi,IRR:ji,MDURATION:Xi,NPV:Yi,PDURATION:Ki,PV:Qi,PRICE:Ji,YIELD:en,YIELDMAT:tn});const on={description:a("Whether a value is an error."),args:Oe(`value (any, lazy) ${a("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},nn={description:a("Whether a value is `true` or `false`."),args:Oe(`value (any) ${a("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){return"boolean"==typeof e},isExported:!0},rn={description:a("Whether a value is non-textual."),args:Oe(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},an={description:a("Whether a value is a number."),args:Oe(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},ln={description:a("Whether a value is text."),args:Oe(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var cn=Object.freeze({__proto__:null,ISERROR:on,ISLOGICAL:nn,ISNONTEXT:rn,ISNUMBER:an,ISTEXT:ln});const hn={description:a("Logical `and` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!0;return Ie(e,(e=>(t=!0,s=s&&e,s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},dn={description:a("Returns value depending on logical expression."),args:Oe(`\n logical_expression (boolean) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${a("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${a("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,s=(()=>!1)){const o=fe(e)?t():s();return null==o?"":o},isExported:!0},un={description:a("Value if it is not an error, otherwise 2nd argument."),args:Oe(`\n value (any, lazy) ${a("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${a("An empty value")}) ${a("The value the function returns if value is an error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let s;try{s=e()}catch(e){s=t()}return null==s?"":s},isExported:!0},pn={description:a("Returns a value depending on multiple logical expressions."),args:Oe(`\n condition1 (boolean, lazy) ${a("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${a("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${a("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${a("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){ce((()=>e.length%2==0),a("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(fe(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},gn={description:a("Returns opposite of provided logical value."),args:Oe(`logical_expression (boolean) ${a("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!fe(e)},isExported:!0},fn={description:a("Logical `or` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s||e,!s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},mn={description:a("Logical `xor` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s?!e:e,!0))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var vn=Object.freeze({__proto__:null,AND:hn,IF:dn,IFERROR:un,IFS:pn,NOT:gn,OR:fn,XOR:mn});function En(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const bn={description:a("Column number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered")}) ${a("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Ws(e).left+1},isExported:!0},Sn={description:a("Number of columns in a specified array or range."),args:Oe(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Ws(e);return t.right-t.left+1},isExported:!0},Cn={description:a("Horizontal lookup"),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${a("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${a("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t.map((e=>e[0]));let l;return l=n?Le(r,e):En(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[l][i-1]},isExported:!0},wn={description:a("Look up a value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${a("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.")}\n result_range (range, optional) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s){let o=t.length,i=t[0].length;const n=i>=o,r=Le(n?t[0]:t.map((e=>e[0])),e);return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),void 0===s?n?t[o-1][r]:t[r][i-1]:(o=s.length,i=s[0].length,ce((()=>1===o||1===i),a("The result_range must be a single row or a single column.")),o>1?(ce((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(ce((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},yn={description:a("Position of item in range that matches value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${a("The search method. 1 (default) 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.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){let o=de(s);const i=t.length,n=t[0].length;ce((()=>1===i||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(o=Math.sign(o),o){case 1:r=Le(l,e);break;case 0:r=En(l,e);break;case-1:r=function(e,t){const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t>e[c])return-1;if(typeof e[h]===s&&e[h]>t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a>=t&&(void 0===o||o>a||o===a&&i>r)&&(o=a,i=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==i?i:-1}(l,e)}return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),r+1},isExported:!0},In={description:a("Row number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered by default")}) ${a("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Ws(e).top+1},isExported:!0},xn={description:a("Number of rows in a specified array or range."),args:Oe(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Ws(e);return t.bottom-t.top+1},isExported:!0},Tn={description:a("Vertical lookup."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${a("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("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.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t[0];let l;return l=n?Le(r,e):En(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[i-1][l]},isExported:!0};var Rn=Object.freeze({__proto__:null,COLUMN:bn,COLUMNS:Sn,HLOOKUP:Cn,LOOKUP:wn,MATCH:yn,ROW:In,ROWS:xn,VLOOKUP:Tn});const Ln={description:a("Sum of two numbers."),args:Oe(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)+de(t)}},Mn={description:a("Concatenation of two values."),args:Oe(`\n value1 (string) ${a("The value to which value2 will be appended.")}\n value2 (string) ${a("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return pe(e)+pe(t)},isExported:!0},An={description:a("One number divided by another."),args:Oe(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);return ce((()=>0!==s),a("The divisor must be different from zero.")),de(e)/s}};function _n(e){return null==e}const On={number:0,string:"",boolean:!1},Nn={description:a("Equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=_n(e)?On[typeof t]:e,t=_n(t)?On[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function kn(e,t,s){e=_n(e)?On[typeof t]:e,t=_n(t)?On[typeof e]:t,"number"!=typeof e&&(e=pe(e).toUpperCase()),"number"!=typeof t&&(t=pe(t).toUpperCase());const o=typeof e,i=typeof t;return"string"===o&&"number"===i||("string"!==i||"number"!==o)&&s(e,t)}const Fn={description:a("Strictly greater than."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return kn(e,t,((e,t)=>e>t))}},$n={description:a("Greater than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return kn(e,t,((e,t)=>e>=t))}},Dn={description:a("Less than."),args:Oe(`\n value1 (any) ${a("The value to test as being less than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!$n.compute(e,t)}},Pn={description:a("Less than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being less than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Fn.compute(e,t)}},Un={description:a("Difference of two numbers."),args:Oe(`\n value1 (number) ${a("The minuend, or number to be subtracted from.")}\n value2 (number) ${a("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)-de(t)}},Vn={description:a("Product of two numbers"),args:Oe(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)*de(t)}},Bn={description:a("Not equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Nn.compute(e,t)}},Hn={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return Mt.compute(e,t)}},zn={description:a("A number with the sign reversed."),args:Oe(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:He.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-de(e)}},Zn={description:a("Value interpreted as a percentage."),args:Oe(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return de(e)/100}},Gn={description:a("A specified number, unchanged."),args:Oe(`\n value (any) ${a("The number to return.")}\n `),returnFormat:He.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var Wn=Object.freeze({__proto__:null,ADD:Ln,CONCAT:Mn,DIVIDE:An,EQ:Nn,GT:Fn,GTE:$n,LT:Dn,LTE:Pn,MINUS:Un,MULTIPLY:Vn,NE:Bn,POW:Hn,UMINUS:zn,UNARY_PERCENT:Zn,UPLUS:Gn});const qn={description:a("Gets character associated with number."),args:Oe(`\n table_number (number) ${a("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(de(e));return ce((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},jn={description:a("Appends strings to one another."),args:Oe(`\n string1 (string, range<string>) ${a("The initial string.")}\n string2 (string, range<string>, repeating) ${a("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return Ce(e,((e,t)=>e+pe(t)),"")},isExported:!0},Xn={description:a("Tests whether two strings are identical."),args:Oe(`\n string1 (string) ${a("The first string to compare.")}\n string2 (string) ${a("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return pe(e)===pe(t)},isExported:!0},Yn={description:a("First position of string found in text, case-sensitive."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e),i=pe(t),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),i)),r+1},isExported:!0},Kn={description:a("Concatenates elements of arrays with delimiter."),args:Oe(`\n delimiter (string) ${a("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${a("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${a("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const s=pe(e);return Ce(t,((e,t)=>(e?e+s:"")+pe(t)),"")}},Qn={description:a("Substring from beginning of specified string."),args:Oe(`\n text (string) ${a("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;return ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),pe(e).substring(0,s)},isExported:!0},Jn={description:a("Length of a string."),args:Oe(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return pe(e).length},isExported:!0},er={description:a("Converts a specified string to lowercase."),args:Oe(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toLowerCase()},isExported:!0},tr={description:a("Replaces part of a text string with different text."),args:Oe(`\n text (string) ${a("The text, a part of which will be replaced.")}\n position (number) ${a("The position where the replacement will begin (starting from 1).")}\n length (number) ${a("The number of characters in the text to be replaced.")}\n new_text (string) ${a("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,s,o){const i=de(t);ce((()=>i>=1),a("The position (%s) must be greater than or equal to 1.",i.toString()));const n=pe(e),r=de(s),l=pe(o);return n.substring(0,i-1)+l+n.substring(i-1+r)},isExported:!0},sr={description:a("A substring from the end of a specified string."),args:Oe(`\n text (string) ${a("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const o=pe(e),i=o.length;return o.substring(i-s,i)},isExported:!0},or={description:a("First position of string found in text, ignoring case."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e).toLowerCase(),i=pe(t).toLowerCase(),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)),r+1},isExported:!0},ir={description:a("Replaces existing text with new text in a string."),args:Oe(`\n text_to_search (string) ${a("The text within which to search and replace.")}\n search_for (string) ${a("The string to search for within text_to_search.")}\n replace_with (string) ${a("The string that will replace search_for.")}\n occurrence_number (number, optional) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o){const i=de(o);ce((()=>i>=0),a("The occurrenceNumber (%s) must be positive or null.",i.toString()));const n=pe(e),r=pe(t);if(""===r)return n;const l=pe(s),c=new RegExp(ps(r),"g");if(0===i)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===i?l:e))},isExported:!0},nr={description:a("Combines text from multiple strings and/or arrays."),args:Oe(`\n delimiter (string) ${a(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${a("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${a("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${a("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...s){const o=pe(e),i=fe(t);let n=0;return Ce(s,((e,t)=>i&&""===pe(t)?e:(n++?e+o:"")+pe(t)),"")},isExported:!0},rr={description:a("Removes space characters."),args:Oe(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return pe(e).trim()},isExported:!0},ar={description:a("Converts a specified string to uppercase."),args:Oe(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toUpperCase()},isExported:!0};const lr={database:gi,date:Bi,financial:sn,info:cn,lookup:Rn,logical:vn,math:qt,operators:Wn,statistical:Jo,text:Object.freeze({__proto__:null,CHAR:qn,CONCATENATE:jn,EXACT:Xn,FIND:Yn,JOIN:Kn,LEFT:Qn,LEN:Jn,LOWER:er,REPLACE:tr,RIGHT:sr,SEARCH:or,SUBSTITUTE:ir,TEXTJOIN:nr,TRIM:rr,UPPER:ar}),engineering:zi};const cr=new class extends Me{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=ke(t);return function(e){let t=!1,s=!1,o=!1;for(let i of e){if(i.type.includes("META")&&i.type.length>1)throw new Error(a("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!i.repeating)throw new Error(a("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=s||t||o,n=!(i.optional||i.repeating||i.default);if(e&&n)throw new Error(a("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=i.repeating,s=i.optional,o=i.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in lr){const t=lr[e];for(let s in t){const o=t[s];o.category=e,cr.add(s,{isExported:!1,...o})}}const hr=cr.content,dr="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function ur(e){const t=e.split(""),s=[];for(;t.length;){let e=yr(t)||fr(t)||vr(t)||br(t)||pr(t)||Ir(t)||Er(t)||Cr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function pr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const gr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function fr(e){if(e[0]in gr){const t=e.shift();return{type:gr[t],value:t}}return null}function mr(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function vr(e){for(let t of dr)if(mr(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function Er(e){const t=function(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}(e).match(Q);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function br(e){if('"'===e[0]){const t=e.shift();let s=t;for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e[0]&&(s+=e.shift()),{type:"STRING",value:s}}return null}const Sr=/\w|\.|!|\$/;function Cr(e){let t="";if("'"===e[0]){let s=e.shift();for(t+=s;e[0];)if(s=e.shift(),t+=s,"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Sr);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in hr)return{type:"FUNCTION",value:e};return e.match(es)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const wr=/\s/;function yr(e){let t=0;for(;e[0]&&e[0].match(wr);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Ir(e){return mr(e,O)?(e.splice(0,O.length),{type:"INVALID_REFERENCE",value:O}):null}const xr=["-","+"],Tr=["*","+","&"],Rr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Lr=6;function Mr(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return Rr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function Ar(e,t,s){if("OPERATOR"===t.type){const o=_r(s,Mr(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}throw new Error(k)}function _r(e,t){const s=e.shift();if(!s)throw new Error(k);let o=function(e,t){var s,o,i;switch(e.type){case"DEBUGGER":const n=_r(t,1e3);return n.debug=!0,n;case"NUMBER":return{type:"NUMBER",value:se(e.value)};case"STRING":return{type:"STRING",value:us(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const o=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?o.push({type:"UNKNOWN",value:""}):o.push(_r(t,Lr));"COMMA"===(null===(s=t[0])||void 0===s?void 0:s.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){o.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?o.push({type:"UNKNOWN",value:""}):o.push(_r(t,Lr))}const i=t.shift();if(!i||"RIGHT_PAREN"!==i.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:o}}case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"REFERENCE":if(":"===(null===(o=t[0])||void 0===o?void 0:o.value)&&"REFERENCE"===(null===(i=t[1])||void 0===i?void 0:i.type)){t.shift();const s=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==s?void 0:s.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value)throw new Error(a("Invalid formula"));return{type:"STRING",value:e.value};case"LEFT_PAREN":const r=_r(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),r;default:if("OPERATOR"===e.type&&xr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:_r(t,Rr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&Mr(e[0])>t;)o=Ar(o,e.shift(),e);return o}function Or(e){return Nr(ur(e))}function Nr(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=_r(e,0);if(e.length)throw new Error(k);return t}function kr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>kr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:kr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:kr(e.right,t,s),left:kr(e.left,t,s)};default:return e}}function Fr(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Fr(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+$r(e);case"BIN_OPERATION":return function(e){const t=e.value,s=e.left,o=s.value;return"BIN_OPERATION"===s.type&&Rr[o]<Rr[t]?`(${Fr(s)})`:Fr(s)}(e)+e.value+$r(e)}}function $r(e){const t=e.value,s=e.right,o=Rr[s.value],i=Rr[t];let n=!1;return"BIN_OPERATION"!==s.type?n=!1:o<i?n=!0:o!==i||Tr.includes(t)||(n=!0),n?`(${Fr(s)})`:Fr(s)}function Dr(e,t=!1){let s,o,i,n;const r=()=>{n=void 0,o=void 0,s=void 0,i=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(o){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"REFERENCE"===l.type)i=a;else if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n,s),a=n+1,r()}else"REFERENCE"===l.type?(n=a,o=a,s=void 0):r()}else"REFERENCE"===l.type?(o=a,s=i=void 0):r();else["SPACE","REFERENCE"].includes(l.type)?(n=a,o="REFERENCE"===l.type?a:void 0,s=i=void 0):r()}const a=e.length-1;if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a+1).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n+1,s)}return e}function Pr(e){return Dr(ur(e),!0)}const Ur=cr.content,Vr={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Br={"-":"UMINUS","+":"UPLUS"};function Hr(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const zr={};function Zr(e){const t=Pr(e),{dependencies:s,constantValues:o}=function(e){const t={numbers:[],strings:[]},s=[];for(const o of e)switch(o.type){case"REFERENCE":s.push(o.value);break;case"STRING":const e=us(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=se(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:s,constantValues:t}}(t),i=function(e,t,s){return e.map((e=>{switch(e.type){case"STRING":const o=us(e.value);return`|S${s.strings.indexOf(o)}|`;case"NUMBER":return`|N${s.numbers.indexOf(se(e.value))}|`;case"REFERENCE":return`|${t.indexOf(e.value)}|`;default:return e.value}})).join("")}(t,s,o);if(!zr[i]){const n=Nr([...t]);let r=1;if("BIN_OPERATION"===n.type&&":"===n.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===n.type)throw new Error(a("Invalid formula"));const l=u(n),c=Hr([`// ${i}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","sheetId","ref","range","ctx",c);function d(e){const t=Ur[e.value.toUpperCase()],s=e.args,o=s.length;if(o<t.minArgRequired)throw new Error(a("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new Error(a("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const i=t.nbrArgRepeating;if(i>1){const s=t.args.length-i;if((o-s)%i!=0)throw new Error(a("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),s.toString(),i.toString()))}let n=[];for(let i=0;i<o;i++){const o=t.getArgToFocus(i+1)-1;if(0<=o&&o<t.args.length){const r=s[i],l=t.args[o],c=l.type||[],h=c.includes("META"),d=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"REFERENCE"!==r.type)throw new Error(a("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(i+1).toString(),r.type.toLowerCase()));const f=u(r,d,h,p,{functionName:e.value.toUpperCase(),paramIndex:i+1});n.push(f)}}return n}function u(e,t=!1,i=!1,n=!1,l={}){const c=[];let h,p,g;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&i)throw new Error(a("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`${e.value}`,code:""};h=r++,g=`${e.value}`;break;case"NUMBER":h=r++,g=`this.constantValues.numbers[${o.numbers.indexOf(e.value)}]`;break;case"STRING":h=r++,g=`this.constantValues.strings[${o.strings.indexOf(e.value)}]`;break;case"REFERENCE":const a=s.indexOf(e.value);h=r++,g=n?`range(${a}, deps, sheetId)`:`ref(${a}, deps, sheetId, ${i?"true":"false"}, "${l.functionName||Vr["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=r++;const f=d(e);c.push(f.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${f.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=r++,p=Br[e.value];const t=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}']( ${t.id})`;break}case"BIN_OPERATION":{h=r++,p=Vr[e.value];const t=u(e.left,!1,!1,!1,{functionName:p}),s=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(s.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${t.id}, ${s.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=r++,g="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${Hr(c).join("\n\t")}\n\treturn ${g};\n}`}}return c.push(`let _${h} = ${g};`),{id:`_${h}`,code:c.join("\n")}}function p(e){let t;switch(e.type){case"REFERENCE":return[s.indexOf(e.value)];case"FUNCALL":if(t=Ur[e.value.toUpperCase()],t.returnFormat){if("FormatFromArgument"!==t.returnFormat)return[t.returnFormat.specificFormat];if(e.args.length>0){const s=0;if(!t.args[s].type.includes("META"))return p(e.args[s])}}break;case"UNARY_OPERATION":return p(e.right);case"BIN_OPERATION":if(t=Ur[Vr[e.value]],t.returnFormat){if("FormatFromArgument"===t.returnFormat){const t=p(e.left);if("string"==typeof t[t.length-1])return t;const s=p(e.right);return t.concat(s)}return[t.returnFormat.specificFormat]}}return[]}zr[i]={execute:h,dependenciesFormat:p(n)}}return{dependenciesFormat:zr[i].dependenciesFormat,execute:zr[i].execute,dependencies:s,constantValues:o,tokens:t}}function Gr(e){return function(e){let t=[],s="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"FUNCTION":s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0}),s="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e}))}(function(e){let t=1;const s=[];return e.map((e=>("LEFT_PAREN"===e.type?(s.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=s.pop()),e)))}(function(e){let t=0;return e.map((e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o}))}(Dr(ur(e)))))}const Wr=new Me;function qr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(_))?X({value:e,format:t}):t?function(e,t){const s=t.split(";"),o=s.length;return e<0?o>1?le(-e,s[1]):"-"+le(-e,s[0]):le(e,s[3===o&&0===e?2:0])}(e,t):ie(e);case"object":return"0"}}function jr(e){return""===e?"":ee(e)?se(e):Cs(e)?"TRUE"===e.toUpperCase():ws(e)?W(e).value:e}class Xr{constructor(e,t,s){this.id=e,this.evaluated=t,this.style=s.style,this.format=s.format}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get formattedValue(){return qr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case Fe.number:return"right";case Fe.boolean:case Fe.error:return"center";case Fe.text:case Fe.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case Fe.empty:case Fe.text:return!0;case Fe.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(_));case Fe.error:case Fe.boolean:return!1}}}class Yr extends Xr{constructor(e,t={}){super(e,{value:"",type:Fe.empty},t),this.content=""}isEmpty(){return!0}}class Kr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.number},s),this.content=ie(this.evaluated.value)}}class Qr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class Jr extends Xr{constructor(e,t,s={}){super(e,{value:t,type:Fe.text},s),this.content=this.evaluated.value}}class ea extends Kr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return qr(this.evaluated.value,this.format)}}class ta extends Xr{constructor(e,t,s={}){var o;const i=Rs(t);s={...s,style:{...s.style,textColor:(null===(o=s.style)||void 0===o?void 0:o.textColor)||A,underline:!0}},super(e,{value:i.label,type:Fe.text},s),this.link=i,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class sa extends ta{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=Ts(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class oa extends ta{constructor(e,t,s={},o){super(e,t,s),this.sheetName=o,this.sheetId=As(this.link.url),this.isUrlEditable=!1}action(e){e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||a("Invalid sheet")}}class ia extends Xr{constructor(e,t,s,o,i,n){super(t,{value:"Loading...",type:Fe.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=o,this.dependencies=i}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:Fe.number};break;case"boolean":this.evaluated={value:e,type:Fe.boolean};break;case"string":this.evaluated={value:e,type:Fe.text};break;case"object":case"undefined":this.evaluated={value:e,type:Fe.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:Fe.error}}}class na extends Xr{constructor(e,t,s,o){super(e,{value:"#BAD_EXPR",type:Fe.error,error:s},o),this.content=t}}function ra(e){const t=Pr(e);let s=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Jt.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${P}${s.indexOf(t)}${P}`}return e.value}))),dependencies:s}}Wr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,o,i)=>{const n=Zr(t),r=n.dependencies.map((e=>i.getRangeFromSheetXC(o,e))),a=s.format||i.inferFormulaFormat(n,r);return new ia((e=>i.buildFormulaContent(o,e)),e,t,n,r,{...s,format:a})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new Yr(e,s)}).add("Number",{sequence:30,match:e=>ee(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new Kr(e,se(t),s))}).add("Boolean",{sequence:40,match:e=>Cs(e),createCell:(e,t,s)=>new Qr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>ws(e),createCell:(e,t,s)=>{const o=W(t),i=s.format||o.format;return new ea(e,o.value,{...s,format:i})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ms(e),createCell:(e,t,s,o,i)=>new oa(e,t,s,(e=>i.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>xs(e),createCell:(e,t,s)=>new sa(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Is.test(t);var t},createCell:(e,t,s)=>new sa(e,Ts(t,t),s)});const aa=11,la="Sheet1";function ca(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<aa&&(e=function(e){for(let t=ha.findIndex((t=>t.from===e.version));t<ha.length;t++)e=ha[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new Bs;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(ga(),e,{version:aa}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(pa(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(pa(la,"Sheet1"));return e}(e),e}(e),e):ga()}const ha=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=ra(s.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(let e of s)if(e.labelCell){const t=Ws(e.dataRange),s=e.labelCell+":"+is(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],o=new RegExp($,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,n=e.replace(o,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;i.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),o=t;for(;o!==s;)o=s,s=o.replace(e,a);return o};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),s=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const s of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[s])||void 0===t?void 0:t.type)&&(e.rule[s].value=l(e.rule[s].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=g,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stackedBar=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(let[s,o]of Object.entries(t)){const t=`\\${P}${s}\\${P}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let s of e.sheets||[])for(let e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=Ns(o.format,t))}return e.formats=t,e}}];function da(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:la};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=ua(t,"SORT_CELLS"),t=ua(t,"SET_DECIMAL")}function ua(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter((e=>e.type!==t))}):s.push(o);return s}function pa(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function ga(e="Sheet1"){return{version:aa,sheets:[pa(la,e)],entities:{},styles:{},formats:{},borders:{},revisionId:N,uniqueFigureIds:!0}}class fa{constructor(e,t,s){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.currentMode=s.mode}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}fa.getters=[],fa.modes=["headless","normal"];class ma extends fa{constructor(e,t,s,o,i,n){super(t,o,i),this.dispatch=o,this.range=s,s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}exportForExcel(e){}adaptRanges(e,t){}}class va extends ma{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const s=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,s)}break;case"DELETE_SHEET":const s={...this.borders};delete s[e.sheetId],this.history.update("borders",s);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=this.getters.getSheet(e.sheetId),s=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(t,s,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,o)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,o)}getCellBorder(e,t,s){var o,i,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(i=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===i?void 0:i[s])||void 0===n?void 0:n.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[s+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[s])||void 0===d?void 0:d.vertical,right:null===(g=null===(p=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===p?void 0:p[s])||void 0===g?void 0:g.vertical};return f.bottom||f.left||f.right||f.top?f:null}ensureColumnBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.rows.length;i++){const n=this.getCellBorder(e.id,t,i),r=this.getCellBorder(e.id,s,i);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,s,i,t)}}}ensureRowBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.cols.length;i++){const n=this.getCellBorder(e.id,i,t),r=this.getCellBorder(e.id,i,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,i,s,t)}}}getCommonSides(e,t){const s={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(s[o]=e[o]);return s}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){if(!this.borders[e])return[];return Es(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfColumn(e,t,s,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfColumn(e,i,s,"vertical"),this.moveBordersOfColumn(e,i,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfRow(e,t,s,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfRow(e,i,s,"horizontal"),this.moveBordersOfRow(e,i,s,"vertical")})))}moveBordersOfRow(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[r])||void 0===a?void 0:a[t+s])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+s,o,i?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[t+s])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+s,r,o,i?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,s,o){this.history.update("borders",e,t,s,{vertical:null==o?void 0:o.left,horizontal:null==o?void 0:o.top}),this.history.update("borders",e,t+1,s,"vertical",null==o?void 0:o.right),this.history.update("borders",e,t,s+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let s of t){for(let t=s.top;t<=s.bottom;t++){this.history.update("borders",e,s.right+1,t,"vertical",void 0);for(let o=s.left;o<=s.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=s.left;t<=s.right;t++)this.history.update("borders",e,t,s.bottom+1,"horizontal",void 0)}}addBorder(e,t,s,o){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...o})}setBorders(e,t,s){const o=e.id;if("clear"===s)return this.clearBorders(o,t);for(let e of t){if("h"===s||"hv"===s||"all"===s)for(let t=e.top+1;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++)this.addBorder(o,s,t,{top:M});if("v"===s||"hv"===s||"all"===s)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left+1;s<=e.right;s++)this.addBorder(o,s,t,{left:M});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.left,t,{left:M});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.right+1,t,{left:M});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.top,{top:M});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.bottom+1,{top:M})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:o,right:i,top:n,bottom:r}=t,a=this.getCellBorder(s.id,o,n),l=this.getCellBorder(s.id,i,r);this.clearBorders(e,[t]),(null==a?void 0:a.top)&&this.setBorders(s,[{...t,bottom:n}],"top"),(null==a?void 0:a.left)&&this.setBorders(s,[{...t,right:o}],"left"),((null==l?void 0:l.bottom)||(null==a?void 0:a.bottom))&&this.setBorders(s,[{...t,top:r}],"bottom"),((null==l?void 0:l.right)||(null==a?void 0:a.right))&&this.setBorders(s,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const i=e.borders[o.border],[n,r]=os(s);this.setBorder(t.id,n,r,i)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Ws(e))}export(e){let t=0;const s={};function o(e){for(let[t,o]of Object.entries(s))if(ds(o)===ds(e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let s=0;s<t.rowNumber;s++){const i=this.getCellBorder(t.id,e,s);if(i){const n=is(e,s),r=t.cells[n],a=o(i);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}va.getters=["getCellBorder"];const Ea=new RegExp(String.fromCharCode(160),"g");class ba extends ma{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=Wr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,o,i,n){const r=t.find((e=>e.match(o)));if(!r)return new Jr(s,o,i);try{return r.createCell(s,o,i,n,e)}catch(e){return new na(s,o,e.message||k,i)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const o of Object.values(this.cells[s]||{}))if(o.isFormula())for(const i of o.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",s,o.id,"dependencies",o.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearStyles(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(this.getters.getSheet(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:""})}}setFormatter(e,t,s){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let o,i;"before"===e.position?(o=Es(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Es(e.base+1,e.base+e.quantity+1),i=e.base),t(s,i,o)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let o in t.cells){const i=t.cells[o],[n,r]=os(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(s,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}}export(e){const t={},s={};for(let o of e.sheets){const e={},i=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:n,row:r}of i){const i=this.getters.getCell(o.id,n,r);e[is(n,r)]={style:i.style?Ns(i.style,t):void 0,format:i.format?Ns(i.format,s):void 0,content:i.content}}o.cells=e}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=t.style&&s[t.style]||void 0,n=t.format&&o[t.format]||void 0,r=this.uuidGenerator.uuidv4(),a={format:n,style:i};return this.createCell(r,(null==t?void 0:t.content)||"",a,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,o]=os(e),i=this.getters.getCell(t.id,s,o),n=t.cells[e];n.value=i.evaluated.value,n.isFormula=i.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t of Object.values(this.cells))if(t[e])return t[e]}inferFormulaFormat(e,t){const s=e.dependenciesFormat;for(let e of s)switch(typeof e){case"string":return e;case"number":const s=t[e];if(this.getters.tryGetSheet(s.sheetId)){const e=this.getters.getCell(s.sheetId,s.zone.left,s.zone.top);if(e&&e.format)return e.format}}return D}buildFormulaContent(e,t,s){const o=s||[...t.dependencies];return t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.shift();return this.getters.getRangeString(t,e)}return t.value})).join("")}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return e&&e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=is((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=is(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCell(e,t.left,t.top),r=this.getters.getMainCell(e,t.right,t.bottom),a=n[0]==r[0]&&n[1]==r[1];return o==i||a?o:o+":"+i}setStyle(e,t,s){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell(e,t,i);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...null==o?void 0:o.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<e.rows.length;o++){const i=this.getFormat(e.id,t,o);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<e.cols.length;o++){const i=this.getFormat(e.id,o,t);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:o,row:t,...i})}}getFormat(e,t,s){const o={},[i,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,i,n);return r&&(r.style&&(o.style=r.style),r.format&&(o.format=r.format)),o}updateCell(e,t,s,o){var i;const n=this.getters.getCell(e.id,t,s),r="content"in o||"formula"in o,a=r?(null===(i=o.content)||void 0===i?void 0:i.replace(Ea,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==o.style?o.style||void 0:n?n.style:void 0;let c=("format"in o?o.format:n&&n.format)||D;if((r&&!a&&!o.formula||!r&&(!n||n.isEmpty()))&&!l&&!c)return void(n&&(this.history.update("cells",e.id,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e.id})));const h=(null==n?void 0:n.id)||this.uuidGenerator.uuidv4(),d=r,u={format:c,style:l},p=this.createCell(h,a,u,e.id);n&&!d&&p.isFormula()&&(p.assignValue(n.evaluated.value),n.evaluated.type===Fe.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const o=this.getters.tryGetSheet(e);if(!o)return 23;return eo(t,s,{top:0,left:0,bottom:o.rows.length-1,right:o.cols.length-1})?0:18}}ba.getters=["zoneToXC","getCells","getFormulaCellContent","inferFormulaFormat","getCellStyle","buildFormulaContent","getCellById"];class Sa extends ma{constructor(){super(...arguments),this.chartFigures={}}adaptRanges(e){for(let[t,s]of Object.entries(this.chartFigures))s&&(this.adaptDataSetRanges(s,t,e),this.adaptLabelRanges(s,t,e))}adaptDataSetRanges(e,t,s){for(let o of e.dataSets){if(o.labelCell){const i=s(o.labelCell);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",i.range)}}const i=s(o.dataRange);switch(i.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(i.range,i.range.sheetId)!==O)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"dataRange",i.range);else{const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const o=s(e.labelRange);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",o.range)}}}allowDispatch(e){switch(e.type){case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartExists),this.checkLabelRange);case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartDuplicate),this.checkLabelRange);default:return 0}}handle(e){var t,s;switch(e.type){case"CREATE_CHART":const o=e.position?e.position.x:0,i=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:o,y:i,height:335,width:536,tag:"chart"});break;case"UPDATE_CHART":this.updateChartDefinition(e.id,e.definition);break;case"DUPLICATE_SHEET":{const s=this.getters.getFigures(e.sheetId);for(const o of s)if("chart"===o.tag){const s=o.id.split("??").pop(),i=`${e.sheetIdTo}??${s}`,n={...gs(this.chartFigures[o.id]),id:i};n.sheetId=e.sheetIdTo,n.dataSets.forEach((t=>{var s;t.dataRange.sheetId===e.sheetId&&(t.dataRange.sheetId=e.sheetIdTo),(null===(s=t.labelCell)||void 0===s?void 0:s.sheetId)===e.sheetId&&(t.labelCell.sheetId=e.sheetIdTo)})),(null===(t=n.labelRange)||void 0===t?void 0:t.sheetId)===e.sheetId&&(n.labelRange.sheetId=e.sheetIdTo);const r={id:i,x:o.x,y:o.y,height:o.height,width:o.width,tag:"chart"};this.addChartFigure(e.sheetIdTo,n,r)}break}case"DELETE_FIGURE":this.history.update("chartFigures",e.id,void 0);break;case"DELETE_SHEET":for(let t of Object.keys(this.chartFigures))(null===(s=this.chartFigures[t])||void 0===s?void 0:s.sheetId)===e.sheetId&&this.history.update("chartFigures",t,void 0)}}getChartDefinition(e){return this.chartFigures[e]}getChartsIdBySheet(e){return Object.entries(this.chartFigures).filter((t=>t[1].sheetId===e)).map((e=>e[0]))}getChartDefinitionUI(e,t){const s=this.chartFigures[t];if(!s)return;const o=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:o,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===o.length)&&Boolean(s.dataSets[0].labelCell),background:s.background,verticalAxisPosition:s.verticalAxisPosition,legendPosition:s.legendPosition,stackedBar:s.stackedBar}}getChartDefinitionExcel(e,t){const s=this.chartFigures[t],o=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!o)return;const i=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...o,backgroundColor:s.background,dataSets:i}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let o=e.dataRange.zone;if(s){const{height:e,width:t}=oo(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i={...e.dataRange,zone:o};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(i,"forceSheetReference")}}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)if("chart"===e.tag){const s={...e.data};this.chartFigures[e.id]=this.createChartDefinition(s,t.id),delete e.data}}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionUI(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.figures=s}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionExcel(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.charts=s}}createChartDefinition(e,t){return{...e,dataSets:this.createDataSets(e.dataSets,t,e.dataSetsHaveTitle),labelRange:e.labelRange?this.getters.getRangeFromSheetXC(t,e.labelRange):void 0,sheetId:t}}updateChartDefinition(e,t){const s=this.chartFigures[e];if(!s)throw new Error(`There is no chart with the given id: ${e}`);if(void 0!==t.title&&this.history.update("chartFigures",e,"title",t.title),t.type&&this.history.update("chartFigures",e,"type",t.type),t.dataSets){const o=!!t.dataSetsHaveTitle,i=this.createDataSets(t.dataSets,s.sheetId,o);this.history.update("chartFigures",e,"dataSets",i)}if(void 0!==t.labelRange){const o=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",o)}t.background&&this.history.update("chartFigures",e,"background",t.background),t.verticalAxisPosition&&this.history.update("chartFigures",e,"verticalAxisPosition",t.verticalAxisPosition),t.legendPosition&&this.history.update("chartFigures",e,"legendPosition",t.legendPosition),void 0!==t.stackedBar&&this.history.update("chartFigures",e,"stackedBar",t.stackedBar)}createDataSets(e,t,s){const o=[];for(const i of e){const e=this.getters.getRangeFromSheetXC(t,i),{zone:n,sheetId:r,invalidSheetName:a}=e;if(!a)if(n.left!==n.right&&n.top!==n.bottom)for(let e=n.left;e<=n.right;e++){const t={left:e,right:e,top:n.top,bottom:n.bottom};o.push(this.createDataSet(r,t,s?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0))}else n.left===n.right&&n.top===n.bottom?s||o.push(this.createDataSet(r,n,void 0)):o.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return o}addChartFigure(e,t,s){this.dispatch("CREATE_FIGURE",{sheetId:e,figure:s}),this.history.update("chartFigures",s.id,t)}createDataSet(e,t,s){if(t.left!==t.right&&t.top!==t.bottom)throw new Error(`Zone should be a single column or row: ${js(t)}`);if(s){const o=js(t),i=js(s);return{labelCell:this.getters.getRangeFromSheetXC(e,i),dataRange:this.getters.getRangeFromSheetXC(e,o)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,js(t))}}checkEmptyDataset(e){return e.definition.dataSets&&0===e.definition.dataSets.length?27:0}checkDataset(e){if(!e.definition.dataSets)return 0;const t=void 0!==e.definition.dataSets.find((e=>!es.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!es.test(e.definition.labelRange||"")?29:0}checkChartDuplicate(e){for(const t of this.getters.getSheets())if(this.getters.getFigure(t.id,e.id))return 57;return 0}checkChartExists(e){return this.getters.getFigure(e.sheetId,e.id)?0:58}}function Ca(e){return""===e?NaN:Number(e)}Sa.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class wa extends ma{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){return"ADD_CONDITIONAL_FORMAT"===e.type?this.checkValidations(e,this.checkCFRule,this.checkEmptyRange):0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.target.map(js)};this.addConditionalFormatting(s,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e].map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const s=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{s.add(e)}))})),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const o=[];for(let i of this.cfRules[e])for(let e of i.ranges)eo(t,s,e.zone)&&o.push(i);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const s={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return s}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkEmptyRange(e){return e.target.length?0:21}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));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)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return s=>{if(t.includes(s.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(s.values[0])&&t.push(36),e>=2&&o(s.values[1])&&t.push(37),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 38;case"max":return 40;case"mid":return 39;case"upperInflectionPoint":return 41;case"lowerInflectionPoint":return 42}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Zr(e.value||"")}catch(e){switch(t){case"min":return 43;case"max":return 45;case"mid":return 44;case"upperInflectionPoint":return 46;case"lowerInflectionPoint":return 47}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?33:0}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Ca(t)>=Ca(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Ca(s)>=Ca(o)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Ca(s)>=Ca(o)?35:0}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}}wa.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class ya extends ma{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:s,...o}=e,i=o;this.updateFigure(s,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,o]of Object.entries(t))switch(s){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,s,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,s,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var s;return void 0===(null===(s=this.figures[e])||void 0===s?void 0:s[t])?55:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?56:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(_s)}getFigure(e,t){var s;return null===(s=this.figures[e])||void 0===s?void 0:s[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var s;return void 0!==(null===(s=this.figures[t])||void 0===s?void 0:s[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){this.export(e)}}ya.getters=["getFigures","getFigure","getFigureSheetId"];class Ia extends ma{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?0:this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;const s=this.getters.getSheet(e.sheetIdTo);for(const e of Object.values(t).filter(_s))this.addMerge(s,e.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(this.getters.getSheet(e.sheetId),t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.merges);for(const t of s)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(_s)}getMerge(e,t,s){var o;const i=this.mergeCellMap[e],n=i?t in i&&(null===(o=i[t])||void 0===o?void 0:o[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:o,top:i,bottom:n}=t;for(let t=i;t<=n;t++)for(let i=s;i<=o;i++)if(this.getMerge(e,i,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<o.rows.length;e++)if(this.isInSameMerge(o.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<=o.cols.length;e++)if(this.isInSameMerge(o.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:o,top:i,bottom:n}=t,r={left:s,right:o,top:i,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&Js(s,r)&&(r=Ks(s,r))}return Qs(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge(e,t,s),r=this.getMerge(e,o,i);return!(!n||!r)&&Qs(n,r)}isInMerge(e,t,s){var o;const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(null===(o=i[t])||void 0===o?void 0:o[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const o=this.getMerge(e,t,s).topLeft;return[o.col,o.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:o,left:i}=this.getMerge(e,t,s);return[i,o]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge(e,t.left,t.top);if(s)return Qs(t,s);const{width:o,height:i}=oo(t);return 1===o&&1===i}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell(e.id,n,t);if(s&&!s.isEmpty())return!0}return!1}getMergeById(e,t){var s;const o=null===(s=this.merges[e])||void 0===s?void 0:s[t];return void 0!==o?Ta(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){const s=this.getters.tryGetSheet(e);if(!s)return 0;return t.some((e=>this.isMergeDestructive(s,e)))?3:0}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&Js(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:o,content:i}=e;if(void 0===i)return 0;const[n,r]=this.getMainCell(o,t,s);return n===t&&r===s?0:4}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge(t,s,o);if(void 0===i||!Qs(e,i))return 5}return 0}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);if(is(s,i)===is(o,n))return;const r=this.getters.getCell(e.id,s,i);let a=this.nextId++;this.history.update("merges",e.id,a,this.getters.getRangeFromSheetXC(e.id,js({left:s,top:i,right:o,bottom:n})));let l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const o=this.getMerge(e.id,n,t);o&&l.add(o.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o=this.getMerge(e.id,s,t);o&&o.id===a||(this.history.update("mergeCellMap",e.id,s,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:t}))}this.history.update("merges",e.id,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge(e,s,o);if(void 0!==r&&Qs(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{width:t,height:i}=oo(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const[s,o]of no(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const 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){const s=this.getters.getSheet(e);for(let e of t)this.addMerge(s,Ws(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...xa(e))}}exportForExcel(e){this.export(e)}}function xa(e){return Object.entries(e).map((([e,t])=>t?Ta(parseInt(e,10),t):void 0)).filter(_s).map((e=>is(e.left,e.top)+":"+is(e.right,e.bottom)))}function Ta(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}Ia.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class Ra extends ma{constructor(){super(...arguments),this.sheetIds={},this.visibleSheets=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":const t=this.visibleSheets.findIndex((t=>t===e.sheetId));return"left"===e.direction&&0===t||"right"===e.direction&&t===this.visibleSheets.length-1?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.visibleSheets.length>1?0:9;case"REMOVE_COLUMNS_ROWS":const s=this.getSheet(e.sheetId);return("COL"===e.dimension?s.cols.length:s.rows.length)>e.elements.length?0:8;case"HIDE_COLUMNS_ROWS":{const t=this.sheets[e.sheetId],s="COL"===e.dimension?t.hiddenColsGroups:t.hiddenRowsGroups,o="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<o.length?0:51}default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIds",t.name,t.id);break;case"RESIZE_COLUMNS_ROWS":const s="COL"===e.dimension?"cols":"rows";for(let t of e.elements)this.setHeaderSize(this.getSheet(e.sheetId),s,t,e.size);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.direction);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],e.elements):this.removeRows(this.sheets[e.sheetId],e.elements);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","hide"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","hide");break;case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","show"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","show");break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e)}}import(e){for(let t of e.sheets)this.sheetIds[t.name]=t.id;for(let t of e.sheets){const e=t.name||r("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,cols:Ds(t.cols||{},s),rows:Ps(t.rows||{},o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(i.id),this.sheets[i.id]=i,this.updateHiddenElementsGroups(i.id,"cols"),this.updateHiddenElementsGroups(i.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(_s).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:Vs(s.rows,t),cols:Us(s.cols,t),merges:[],cells:{},conditionalFormats:[],figures:[],areGridLinesVisible:void 0===s.areGridLinesVisible||s.areGridLinesVisible}}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e,!0)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return no(t).map((([t,s])=>this.getCell(e,t,s)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const s=((t=e).startsWith("'")&&(t=t.slice(1,-1).replace(/''/g,"'")),t);for(const e in this.sheetIds)if(e.toUpperCase()===s.toUpperCase())return this.sheetIds[e]}var t}getSheets(){const{visibleSheets:e,sheets:t}=this;return e.map((e=>t[e])).filter(_s)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}tryGetCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getCol(e,t){const s=this.getSheet(e).cols[t];if(!s)throw new Error(`Col ${s} not found.`);return s}tryGetRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getRow(e,t){const s=this.getSheet(e).rows[t];if(!s)throw new Error(`Row ${s} not found.`);return s}getCell(e,t,s){var o;const i=this.tryGetSheet(e),n=null===(o=null==i?void 0:i.rows[s])||void 0===o?void 0:o.cells[t];if(void 0!==n)return this.getters.getCellById(n)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(_s).map((e=>this.getters.getCellById(e))).filter(_s)}getColsZone(e,t,s){return{top:0,bottom:this.getSheet(e).rows.length-1,left:t,right:s}}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).cols.length-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getHiddenColsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenColsGroups)||[]}getHiddenRowsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenRowsGroups)||[]}getNumberCols(e){return this.getSheet(e).cols.length}getNumberRows(e){return this.getSheet(e).rows.length}getNextSheetName(e="Sheet"){let t=1;const s=this.getSheets().map((e=>e.name));let o=`${e}${t}`;for(;s.includes(o);)o=`${e}${t}`,t++;return o}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,o){let i,n;const r=e[t],a=r[s],l=o-a.size;this.history.update("sheets",e.id,t,s,"size",o),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),i=a.end;for(let o=s+1;o<r.length;o++){const s=r[o];n=s.isHidden?i:i+s.size,this.history.update("sheets",e.id,t,o,"start",i),this.history.update("sheets",e.id,t,o,"end",n),i=n}}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){var o;const i=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[s].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,s,o,i){const n={id:e,name:t,cols:Fs(s),rows:$s(o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("visibleSheets",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.visibleSheets.slice(),o=s.findIndex((t=>t===e)),i=s.splice(o,1);s.splice(o+("left"===t?-1:1),0,i[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=s[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:$.test(o)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIds);o[t]=e.id,delete o[s],this.history.update("sheetIds",o)}duplicateSheet(e,t){const s=this.getSheet(e),o=this.getDuplicateSheetName(s.name),i=JSON.parse(JSON.stringify(s));i.id=t,i.name=o;for(let e=0;e<=i.cols.length;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,i.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[i.name]=i.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),o=a("Copy of %s",e);let i=o.toString();for(;s.includes(i);)i=`${o} (${t})`,t++;return i}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.visibleSheets.slice(),i=o.findIndex((t=>t===e.id));o.splice(i,1),this.history.update("visibleSheets",o);const n=Object.assign({},this.sheetIds);delete n[t],this.history.update("sheetIds",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let s of t)this.moveCellOnColumnsDeletion(e,s);this.updateColumnsStructureOnDeletion(e,t)}removeRows(e,t){t.sort(((e,t)=>t-e));for(let s of bs(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,o){this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"columns"),this.updateColumnsStructureOnAddition(e,t,o)}addRows(e,t,s,o){this.addEmptyRows(e,o),this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"rows"),this.updateRowsStructureOnAddition(e,t,o)}moveCellOnColumnsDeletion(e,t){for(let[s,o]of Object.entries(e.rows)){const i=parseInt(s,10);for(let s in o.cells){const n=parseInt(s,10),r=o.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:i}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:i}))}}}moveCellsOnAddition(e,t,s,o){const i=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==o||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===o||l>=t)&&i.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:a+("rows"===o?s:0)})}}for(let e of i.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const o=s-t+1;for(let[i,n]of Object.entries(e.rows)){const r=parseInt(i,10);if(r>=t&&r<=s)for(let t in n.cells){const s=parseInt(t,10);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:r})}if(r>s)for(let t in n.cells){const s=parseInt(t,10),i=n.cells[t];i&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:i,col:s,row:r-o})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let o=0,i=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?o:o+r;s.push({name:ss(i),size:r,start:o,end:l,isHidden:a}),o=l,i++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const o=[];let i=0,n=0;for(let r in e.cols){if(parseInt(r,10)===t){const{size:t}=e.cols[n];for(let e=0;e<s;e++)o.push({name:ss(n),size:t,start:i,end:i+t}),i+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?i:i+a;o.push({name:ss(n),size:a,start:i,end:c,isHidden:l}),i=c,n++}this.history.update("sheets",e.id,"cols",o),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let o=0,i=0;const n=t.rows.map((e=>e.cells));for(let r in t.rows){const a=t.rows[r],{size:l,isHidden:c}=a,h=c?o:o+l;parseInt(r,10)!==e&&(i++,s.push({start:o,end:h,size:l,cells:n.shift(),name:String(i),isHidden:c}),o=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const o=[];let i=0,n=0,r=0;const a=e.rows.map((e=>e.cells));for(let l in e.rows){const{size:c,isHidden:h}=e.rows[r],d=h?i:i+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,o.push({start:i,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),i=d}this.history.update("sheets",e.id,"rows",o),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,o=e.rows.slice();for(let e=0;e<t;e++)o.push({start:s,end:s,size:0,name:(o.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(os);return{rowNumber:Math.max(e.rowNumber,...new Set(t.map((([e,t])=>t+1)))),colNumber:Math.max(e.colNumber,...new Set(t.map((([e,t])=>e+1))))}}setElementsVisibility(e,t,s,o){let i=0;const n="hide"===o;for(let o=0;o<e[s].length;o++){const{size:r,isHidden:a}=e[s][o],l=t.includes(o)?n:a||!1,c=l?i:i+r;this.history.update("sheets",e.id,s,o,"start",i),this.history.update("sheets",e.id,s,o,"end",c),this.history.update("sheets",e.id,s,o,"isHidden",l),i=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const o="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",i=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const o=e[e.length-1];return o&&o[o.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,o,i)}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?23:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),!t.every(qs))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),o={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Qs(Ks(t=o,e),t);var t}))?0:18}return 0}}Ra.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","tryGetCol","getCol","tryGetRow","getRow","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const La=new Me;La.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const o=e.current.toString(),i=qr(e.current,null===(s=t.cell)||void 0===s?void 0:s.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var o,i;const n=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:null===(i=t.cell)||void 0===i?void 0:i.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case 0:i=0,n=-e.current;break;case 1:i=0,n=e.current;break;case 2:i=-e.current,n=0;break;case 3:i=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies,i,n,r),l=s.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const Ma=new Me;Ma.add("simple_value_copy",{condition:(e,t)=>{var s;return 1===t.length&&!e.isFormula()&&!(null===(s=e.format)||void 0===s?void 0:s.match(_))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===Fe.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_number",{condition:e=>e.evaluated.type===Fe.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],o=!1;for(let i of t)if(i===e&&(o=!0),(null==i?void 0:i.evaluated.type)===Fe.number)s.push(i.evaluated.value);else{if(o)return s;s=[]}return s}(e,t);let o=1;return 2==s.length?o=2*(s[1]-s[0]):s.length>2&&(o=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===Fe.number?e.evaluated.value:0}},sequence:40});const Aa=new Me,_a=(new Me).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],s=[...e.elements].sort(((e,t)=>e-t));for(let o of bs(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Pe.values())_a.contains(e)||_a.add(e,Oa);function Oa(e){return[e]}const Na=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function ka(e,t){return Object.assign({},Na(e),t)}class Fa extends Me{add(e,t){return this.content[e]=ka(e,t),this}addChild(e,t,s){const o=t.splice(0,1)[0];let i=this.content[o];if(!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t)if(i="function"==typeof i.children?void 0:i.children.find((t=>t.id===e)),!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);return i.children.push(ka(e,s)),this}getChildren(e,t){return"function"==typeof e.children?e.children(t).sort(((e,t)=>e.sequence-t.sequence)):e.children.sort(((e,t)=>e.sequence-t.sequence))}getName(e,t){return"function"==typeof e.name?e.name(t):e.name}getShortCut(e){return e.shortCut?e.shortCut:""}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const $a=[Fe.number,Fe.error,Fe.text,Fe.boolean];function Da(e,t){return{index:t,type:e?e.evaluated.type:Fe.empty,value:e?e.evaluated.value:""}}function Pa(e,t,s,o,i){let n=Ve.Success,r=o.right>o.left;if(e.getters.doesIntersectMerge(t,o)){let s;r=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){let o=e.getters.getMerge(t,n,i);o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){r=!0;break}}}const[l,c]=s;if(r)n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i});else{const s=e.getters.getContiguousZone(t,o);Qs(s,o)?n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i}):e.askConfirmation(a("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=s,n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}),(()=>{n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}))}n.isCancelledBecause(48)&&(e.dispatch("SET_SELECTION",{anchor:s,zones:[o],anchorZone:o}),e.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}function Ua(e,t){t.isSuccessful||(t.reasons.includes(19)&&e.notifyUser(a("This operation is not allowed with multiple selections.")),t.reasons.includes(2)&&e.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again.")))}function Va(e,t,s){const o=e.dispatch("PASTE",{target:t,pasteOption:s});Ua(e,o)}function Ba(e){const t=e.getters.getActiveCols();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.right-t.left+1}}function Ha(e){const t=e.getters.getActiveRows();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const Ga=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Wa=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},qa=async e=>{const t=e.getters.getClipboardContent();let s;try{s=await e.clipboard.readText()}catch(e){console.warn("The OS clipboard could not be read."),console.error(e)}const o=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:o,text:s}):Va(e,o)},ja=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Xa=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Ya=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),Ka=e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},Qa=e=>{let t=[...e.getters.getActiveRows()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Ja=e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Delete column %s",ss(t)):a("Delete columns %s - %s",ss(t),ss(s))},el=e=>{let t=[...e.getters.getActiveCols()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},tl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Ua(e,s)},sl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Ua(e,s)},ol=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Ua(e,s)},il=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Ua(e,s)},nl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:o,dimension:"ROW"})},rl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:o,dimension:"ROW"})},al=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:o})},ll=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:o})},cl=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},hl=e=>{e.openLinkEditor()},dl=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Pa(e,o,t,s[0],"ascending")},ul=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Pa(e,o,t,s[0],"descending")},pl=e=>1===e.getters.getSelectedZones().length,gl=new Fa;gl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa,isVisible:pl}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:pl}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:pl,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).add("add_row_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:nl,isVisible:pl}).add("add_column_before",{name:e=>{const t=Ba(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:al,isVisible:pl}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:pl,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:tl}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:sl}).add("delete_row",{name:Ka,sequence:110,action:Qa,isVisible:pl}).add("delete_column",{name:Ja,sequence:120,action:el,isVisible:pl}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:pl}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:ol}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:il}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Ya,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:hl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:cl,separator:!0});const fl=new Fa;fl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:pl,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).add("add_column_before",{name:e=>{const t=Ba(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:al}).add("add_column_after",{name:e=>{const t=Ba(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:ll}).add("delete_column",{name:Ja,sequence:90,action:el}).add("clear_column",{name:e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Clear column %s",ss(t)):a("Clear columns %s - %s",ss(t),ss(s))},sequence:100,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveCols()].map((s=>e.getters.getColsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.getters.getElementsFromSelection("COL");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide column %s",ss(s).toString()):o-s+1===t.length?a("Hide columns %s - %s",ss(s).toString(),ss(o).toString()):a("Hide columns")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenColsGroups(t.id).flat();return t.cols.length>s.length+e.getters.getElementsFromSelection("COL").length},separator:!0}).add("unhide_columns",{name:"Unhide columns",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:110,action:cl});const ml=new Fa;ml.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>ka(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${Ls}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const vl=new Fa;function El(e,t,s){const o=e.getters.getSheetName(t),i=a("Rename Sheet")+(s?" - "+s:"");e.editText(i,o,(s=>{if(null===s||s===o)return;""===s&&El(e,t,a("The sheet name cannot be empty."));const i=e.dispatch("RENAME_SHEET",{sheetId:t,name:s});i.isSuccessful||(i.reasons.includes(11)&&El(e,t,a("A sheet with the name %s already exists. Please select another name.",s)),i.reasons.includes(13)&&El(e,t,a("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",F.join(" "))))}))}vl.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:Wa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Ga}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:qa}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).add("add_row_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:nl}).add("add_row_after",{name:e=>{const t=Ha(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:rl}).add("delete_row",{name:Ka,sequence:70,action:Qa}).add("clear_row",{name:e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Clear row %s",(t+1).toString()):a("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},sequence:80,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveRows()].map((s=>e.getters.getRowsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.getters.getElementsFromSelection("ROW");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):o-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):a("Hide rows")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenRowsGroups(t.id).flat();return t.rows.length>s.length+e.getters.getElementsFromSelection("ROW").length},separator:!0}).add("unhide_rows",{name:"Unhide rows",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:90,action:cl});const bl=new Fa;bl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{e.dispatch("DELETE_SHEET",{sheetId:e.getters.getActiveSheetId()})}))}).add("duplicate",{name:a("Duplicate"),sequence:20,action:e=>{const t=e.getters.getActiveSheetId(),s=e.uuidGenerator.uuidv4();e.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:s})}}).add("rename",{name:a("Rename"),sequence:30,action:e=>El(e,e.getters.getActiveSheetId())}).add("move_right",{name:a("Move right"),sequence:40,isVisible:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getSheets();return s.findIndex((e=>e.id===t))!==s.length-1},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:a("Move left"),sequence:50,isVisible:e=>{const t=e.getters.getActiveSheetId();return 0!==e.getters.getSheets().findIndex((e=>e.id===t))},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"left"})});const Sl=new Fa;Sl.add("file",{name:a("File"),sequence:10}).add("edit",{name:a("Edit"),sequence:20}).add("view",{name:a("View"),sequence:30}).add("insert",{name:a("Insert"),sequence:40}).add("format",{name:a("Format"),sequence:50}).add("data",{name:a("Data"),sequence:60}).addChild("save",["file"],{name:a("Save"),shortCut:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:a("Undo"),shortCut:"Ctrl+Z",sequence:10,action:e=>e.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:a("Redo"),shortCut:"Ctrl+Y",sequence:20,action:e=>e.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:a("Copy"),shortCut:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Ga}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:Wa}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:qa}).addChild("paste_special",["edit"],{name:a("Paste special"),sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{name:a("Paste value only"),sequence:10,action:ja}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Xa}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:pl,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:dl}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:ul}).addChild("find_and_replace",["edit"],{name:a("Find and replace"),shortCut:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:a("Delete values"),sequence:70,action:Ya}).addChild("edit_delete_row",["edit"],{name:Ka,sequence:80,action:Qa}).addChild("edit_delete_column",["edit"],{name:Ja,sequence:90,action:el}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:ol}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:il}).addChild("edit_unhide_columns",["edit"],{name:a("Unhide all columns"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"COL",elements:Array.from(Array(t.cols.length).keys())})},isVisible:e=>e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:a("Unhide all rows"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"ROW",elements:Array.from(Array(t.rows.length).keys())})},isVisible:e=>e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:nl,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:rl,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Ba(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:al,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Ba(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:ll,isVisible:e=>0===e.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:a("Insert cells and shift down"),sequence:43,action:tl}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:sl,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const o=e.getters.getSelectedZone();let i=o;const n=e.uuidGenerator.uuidv4();let r;o.left!==o.right&&(i={...o,left:o.left+1});const a=[js(i)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.tryGetCol(l,o.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.tryGetRow(l,o.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=i.left;t<=i.right;t++){const s=e.getters.getCell(l,t,o.top);if(s&&s.evaluated.type!==Fe.number){h=!0;break}}o.left!==o.right&&(r=js({...o,right:o.left,top:h?o.top+1:o.top})),e.dispatch("CREATE_CHART",{sheetId:l,id:n,position:c,definition:{title:"",dataSets:a,labelRange:r,type:"bar",stackedBar:!1,dataSetsHaveTitle:h,background:g,verticalAxisPosition:"left",legendPosition:"top"}});const d=e.getters.getFigure(l,n);e.openSidePanel("ChartPanel",{figure:d})}}).addChild("insert_link",["insert"],{name:a("Link"),separator:!0,sequence:60,action:hl}).addChild("insert_sheet",["insert"],{name:a("New sheet"),sequence:70,action:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getVisibleSheets().findIndex((e=>e===t))+1,o=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:o,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("view_gridlines",["view"],{name:e=>e.getters.getGridLinesVisibility(e.getters.getActiveSheetId())?a("Hide gridlines"):a("Show gridlines"),action:e=>{const t=e.getters.getActiveSheetId();e.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.getters.getGridLinesVisibility(t)})},sequence:5,separator:!0}).addChild("view_formulas",["view"],{name:e=>e.getters.shouldShowFormulas()?a("Hide formulas"):a("Show formulas"),action:e=>e.dispatch("SET_FORMULA_VISIBILITY",{show:!e.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:10}).addChild("format_number",["format"],{name:a("Numbers"),sequence:10,separator:!0}).addChild("format_number_general",["format","format_number"],{name:a("General"),sequence:10,separator:!0,action:e=>za(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>za(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>za(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>za(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>za(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:a("Date time (9/26/2008 22:43:00)"),sequence:60,action:e=>za(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:a("Duration (27:51:38)"),sequence:70,separator:!0,action:e=>za(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Za(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Za(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Za(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Za(e,{strikethrough:!e.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:a("Font size"),sequence:60,separator:!0}).addChild("format_cf",["format"],{name:a("Conditional formatting"),sequence:70,action:cl,separator:!0});for(let e of cs)Sl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Za(t,{fontSize:e.pt})});const Cl=new class extends Me{addTransformation(e,t,s){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:wl,xml:yl}=t.tags,Il=[["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff"],["#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff"],["#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc"],["#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd"],["#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0"],["#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79"],["#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47"],["#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"]],xl=24*Math.max(...Il.map((e=>e.length)))+12;class Tl extends t.Component{constructor(){super(...arguments),this.COLORS=Il}onColorClick(e){const t=e.target.dataset.color;t&&this.props.onColorPicked(t)}}Tl.template=yl`
|
|
2
2
|
<div class="o-color-picker"
|
|
3
3
|
t-att-class="props.dropdownDirection || 'right'"
|
|
4
4
|
t-on-click="onColorClick">
|
|
@@ -1045,7 +1045,7 @@
|
|
|
1045
1045
|
}
|
|
1046
1046
|
}
|
|
1047
1047
|
}
|
|
1048
|
-
`;class Eh extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.state=t.useState(this.initialState())}get hasSearchResult(){return null!==this.env.getters.getCurrentSelectedMatchIndex()}setup(){uh((()=>this.focusInput())),ph((()=>this.env.dispatch("CLEAR_SEARCH")))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.getters.shouldShowFormulas(),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas?this.state.searchOptions.searchFormulas:this.state.replaceOptions.modifyFormulas,this.env.dispatch("REFRESH_SEARCH")}searchFormulas(){this.env.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas,this.updateSearch()}onSelectPreviousCell(){this.env.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.inDebounce),this.inDebounce=setTimeout((()=>this.updateSearch.call(this)),400)}replace(){this.env.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}replaceAll(){this.env.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}focusInput(){const e=this.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1},replaceOptions:{modifyFormulas:!1}}}}Eh.template=mh,Eh.style=vh;const bh=new Me;bh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:dh}),bh.add("ChartPanel",{title:a("Chart"),Body:Hc}),bh.add("FindAndReplace",{title:a("Find and Replace"),Body:Eh});const Sh=new Me;class Ch extends fa{constructor(e,t,s,o){super(t,s,o),this.getters=e,this.ui=o}drawGrid(e,t){}}Ch.layers=[];class wh{constructor(e,t,s){this.index=0,this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=La.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class yh extends Ch{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ms(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ms(e.row,0,this.getters.getSheet(t).rows.length),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:30;case"AUTOFILL_AUTO":const s=this.getters.getSelectedZone();return s.top===s.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone;switch(this.direction){case 1:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,o,t,e)}break;case 0:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,o,t,e)}break;case 2:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,o,e)}break;case 3:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,o,e)}}if(e){const e=Ks(this.getters.getSelectedZone(),this.autofillZone);this.autofillZone=void 0,this.lastCellSelected={},this.direction=void 0,this.tooltip=void 0,this.dispatch("SET_SELECTION",{zones:[e],anchor:[e.left,e.top],anchorZone:e})}}select(e,t){const s=this.getters.getSelectedZone();if(eo(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case 0:this.saveZone(t,s.top-1,s.left,s.right);break;case 1:this.saveZone(s.bottom+1,t,s.left,s.right);break;case 2:this.saveZone(s.top,s.bottom,e,s.left-1);break;case 3:this.saveZone(s.top,s.bottom,s.right+1,e)}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s-1,o)}if(o===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s+1,o)}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,s,o){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:s,content:a,style:l,border:c,format:h})}getRule(e,t){const s=Ma.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((s=>s.condition(e,t)));return s&&s.generateRule(e,t)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(let t of e){const[e,i]=os(t),n=this.getters.getCell(o,e,i);s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const{sheetId:o,col:n,row:r}=e,a=this.getters.getCellBorder(o,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new wh(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:0},down:{number:t-s.bottom,value:1},left:{number:s.left-e,value:2},right:{number:e-s.right,value:3}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autoFillMerge(e,t,s,o){const i=this.getters.getActiveSheet();if(this.getters.isInMerge(i.id,s,o)&&!this.getters.isInMerge(i.id,e,t)){const e=this.getters.getMerge(i.id,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:i.id,target:[e]})}const n=this.getters.getMerge(i.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:i.id,target:[{top:o,bottom:o+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:o}=e,[i,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=o,s.setLineDash([3]),s.strokeRect(i,n,r,a),s.setLineDash([]))}}yh.layers=[6],yh.getters=["getAutofillTooltip"],yh.modes=["normal"];class Ih extends Ch{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const[o,i]=eo(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||io(Ks(n,t))?[{position:[o,i],zone:n}]:this.sumDimensions(e,Ks(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.findSuitableZoneToSum(o,...this.getters.getMainCell(e,t,s));if(i)return this.getters.expandZone(e,i)}findSuitableZoneToSum(e,t,s){const o=this.getters.getCell(e.id,t,s-1),i=this.getters.getCell(e.id,t-1,s);if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getCellsInZone(e.id,t),i=Es(s,-1,-1),n=i.filter((e=>{var t;return o[e]&&!(null===(t=o[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=bs(i.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===Fe.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(_))}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){const s=new Set;return io(t)?(s.add(1===oo(t).width?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:[s,t],zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},no(s).map((t=>({position:t,zone:{...e,right:t[0],left:t[0]}})))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},no(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,o]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Ih.getters=["getAutomaticSums"],Ih.modes=["normal","headless"];class xh extends Ch{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"PASTE":return this.isPasteAllowed(this.state,e.target,!!e.force);case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}}return 0}handle(e){var t,s;switch(e.type){case"COPY":case"CUT":this.state=this.getClipboardState(e.target,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1;const i=this.state.cells.length,n=this.state.cells[0].length;this.paste(this.state,e.target,o),this.selectPastedZone(n,i,e.target),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!qs(t[0])){for(const[t,s]of no(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(s=this.state)||void 0===s?void 0:s.operation))return;for(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.pasteFromClipboard(e.target,e.text);break;case"ACTIVATE_PAINT_FORMAT":this.state=this.getClipboardState(e.target,"COPY"),this._isPaintingFormat=!0,this.status="visible";break;default:Ue(e)&&(this.status="invisible")}}getClipboardContent(){return this.state&&this.state.cells.length&&this.state.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheet();let o;return o="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let o,i;return"COL"===t?(o={...e,right:s.cols.length-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:s.rows.length-1},i={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[o],paste:[i]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:o}=e,[i,n]=this.getters.getMainCell(t,s,o);if(n===o&&i===s){const e=this.getters.getMerge(t,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:o,row:i}=e;const[n,r]=this.getters.getMainCell(s,o,i);if(n===o&&r===i){const e=this.getters.getMerge(s,o,i);if(!e)return;({sheetId:s,col:o,row:i}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],o=t.length,i=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/i)),c=Math.max(1,Math.floor((n.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*i,bottom:a-1+t*o});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.left))),o=new Set(e.map((e=>e.right))),i=new Set(e.map((e=>e.top))),n=new Set(e.map((e=>e.bottom))),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce(((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(Js(e[o],t))return e[o]=Ks(e[o],t),e;return e[s]=t,e}),[])}(e):[e[e.length-1]],a=r.map((e=>no(e))).flat(),l=[...new Set(a.map((e=>e[0])))].sort(((e,t)=>e-t)),c=[...new Set(a.map((e=>e[1])))].sort(((e,t)=>e-t)),h=[],d=[],u=this.getters.getActiveSheetId();for(let e of c){let t=[];for(let s of l){t.push({cell:this.getters.getCell(u,s,e),border:this.getters.getCellBorder(u,s,e)||void 0,position:{col:s,row:e,sheetId:u}});const o=this.getters.getMerge(u,s,e);o&&o.top===e&&o.left===s&&d.push(o)}h.push(t)}return{cells:h,operation:t,sheetId:u,zones:r,merges:d}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:o,top:i}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,o,i);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:i+e,col:o+t,content:s[e][t],sheetId:a.id});const l={left:o,top:i,right:o+n-1,bottom:i+r-1};this.dispatch("SET_SELECTION",{anchor:[o,i],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const o=this.getters.getActiveSheetId();if(!e)return 20;if(t.length>1&&(e.cells.length>1||e.cells[0].length>1))return 19;if(!s)for(let s of this.getPasteZones(t,e.cells))if(this.getters.doesIntersectMerge(o,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,t,i,s);else{const o=e.cells.length,i=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/i)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/o));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*i,n.top+r*o,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const o=s[0],i=o.left,n=o.top,r=Math.max(1,Math.floor((o.right+1-o.left)/e)),a=Math.max(1,Math.floor((o.bottom+1-o.top)/t));if(t>1||e>1){const s={left:i,top:n,right:i+r*e-1,bottom:n+a*t-1},[o,l]=this.getters.getSelection().anchor,c=ms(o,i,i+r*e-1),h=ms(l,n,n+a*t-1);this.dispatch("SET_SELECTION",{anchor:[c,h],zones:[s],anchorZone:s})}}clearClippedZones(e){for(const t of e.cells)for(const e of t)e.cell&&this.dispatch("CLEAR_CELL",e.position);this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o){const i=e.cells.length,n=e.cells[0].length,r="onlyValue"!==o&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,i,t,s);for(let l=0;l<i;l++){const i=e.cells[l];for(let c=0;c<n;c++){const n=i[c],h={col:t+c,row:s+l,sheetId:a.id};this.removeMergeIfTopLeft(h),this.pasteMergeIfExist(n.position,h),this.pasteCell(n,h,e.operation,e.zones,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,o,i){const{cols:n,rows:r,id:a}=e,l=s+i-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+o-n.length;c>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n.length-1,sheetId:a,quantity:c,position:"after"})}pasteCell(e,t,s,o,i){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==i&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===i)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===i){const s=qr(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:s})}let l=e.cell.content;if(e.cell.isFormula()){const t=r-e.position.col,i=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,i,o,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===i?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,o,i,n){if("CUT"===n){const n=[];for(const r of t.dependencies)this.isZoneOverlapClippedZone(i,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,o,e)):n.push(r);return this.getters.buildFormulaContent(e,t,n)}const r=this.getters.createAdaptedRanges(t.dependencies,s,o,e);return this.getters.buildFormulaContent(e,t,r)}isZoneOverlapClippedZone(e,t){return e.some((e=>Js(t,e)))}isColRowDirtyingClipboard(e,t){if(!this.state||!this.state.zones)return!1;for(let s of this.state.zones){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e;if("visible"===this.status&&this.state&&this.state.zones&&this.state.zones.length&&this.state.sheetId===this.getters.getActiveSheetId()){s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*o;for(const e of this.state.zones){const[o,i,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(o,i,n,r)}}}}xh.layers=[2],xh.getters=["getClipboardContent","isPaintingFormat"],xh.modes=["normal"];const Th=[{name:a("Sum"),types:[Fe.number],compute:e=>Bt.compute([e])},{name:a("Avg"),types:[Fe.number],compute:e=>go.compute([e])},{name:a("Min"),types:[Fe.number],compute:e=>_o.compute([e])},{name:a("Max"),types:[Fe.number],compute:e=>Ro.compute([e])},{name:a("Count"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>wo.compute([e])},{name:a("Count Numbers"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>Co.compute([e])}];var Rh;!function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Rh||(Rh={}));class Lh extends Ch{constructor(e,t,s,o){super(e,t,s,o),this.selection={zones:[{top:0,left:0,bottom:0,right:0}],anchor:[0,0],anchorZone:{top:0,left:0,bottom:0,right:0}},this.selectedFigureId=null,this.activeCol=0,this.activeRow=0,this.mode=Rh.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=o.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Qs(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:o,bottom:i}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=zs(n,"cols",Es(t,s+1)),a=zs(n,"rows",Es(o,i+1));if(0!==e.delta[0]&&void 0===a||0!==e.delta[1]&&void 0===r)return 17}break;case"MOVE_POSITION":{const{cols:t,rows:s}=this.getters.getActiveSheet();if(0!==e.deltaX&&s[this.activeRow].isHidden||0!==e.deltaY&&t[this.activeCol].isHidden)return 17;const{col:o,row:i}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(i<0||i>s.length-1||o<0||o>t.length-1)return 17;break}case"SELECT_COLUMN":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().cols.length)return 17;break}case"SELECT_ROW":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().rows.length)return 17;break}case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 23}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":case"CREATE_FIGURE":case"CREATE_CHART":case"UPDATE_FIGURE":case"EVALUATE_CELLS":case"DISABLE_SELECTION_INPUT":case"ENABLE_NEW_SELECTION_INPUT":case"RESIZE_VIEWPORT":break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;default:this.selectedFigureId=null}switch(e.type){case"START":const t=Hs(this.getters.getSheets()[0],0,0);this.activeCol=t[0],this.activeRow=t[1],this.dispatch("ACTIVATE_SHEET",{sheetIdTo:this.getters.getSheets()[0].id,sheetIdFrom:this.getters.getSheets()[0].id}),this.selectCell(...t);break;case"ACTIVATE_SHEET":this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={selection:JSON.parse(JSON.stringify(this.selection)),activeCol:this.activeCol,activeRow:this.activeRow},e.sheetIdTo in this.sheetsData?Object.assign(this,this.sheetsData[e.sheetIdTo]):this.selectCell(...Hs(this.getters.getSheet(e.sheetIdTo),0,0));break;case"SET_SELECTION":this.setSelection(e.anchor,e.zones,e.anchorZone,e.strict);break;case"START_SELECTION":this.mode=Rh.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Rh.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Rh.expanding;break;case"STOP_SELECTION":this.mode=Rh.idle;break;case"MOVE_POSITION":this.movePosition(e.deltaX,e.deltaY);break;case"SELECT_CELL":this.selectCell(e.col,e.row);break;case"SELECT_COLUMN":this.selectColumn(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ROW":this.selectRow(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ALL":this.selectAll();break;case"ALTER_SELECTION":e.delta&&this.moveSelection(e.delta[0],e.delta[1]),e.cell&&this.addCellToSelection(...e.cell);break;case"UNDO":case"REDO":case"DELETE_SHEET":if(!this.getters.tryGetSheet(this.getActiveSheetId())){const e=this.getters.getVisibleSheets();this.activeSheet=this.getters.getSheet(e[0]),this.selectCell(0,0)}this.ensureSelectionValidity();break;case"REMOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&("COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e));break;case"ADD_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onAddElements(e);break;case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"UPDATE_CHART":case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left")}}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getMainCell(e,this.activeCol,this.activeRow);return this.getters.getCell(e,t,s)}getActiveCols(){const e=new Set;for(let t of this.selection.zones)if(0===t.top&&t.bottom===this.getters.getActiveSheet().rows.length-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set;for(let t of this.selection.zones)if(0===t.left&&t.right===this.getters.getActiveSheet().cols.length-1)for(let s=t.top;s<=t.bottom;s++)e.add(s);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return this.selection.zones}getSelectedZone(){return this.selection.anchorZone}getSelection(){return this.selection}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return[this.activeCol,this.activeRow]}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?[t.activeCol,t.activeRow]:Hs(this.getters.getSheet(e),0,0)}}getStatisticFnResults(){const e=new Set(this.selection.zones.map((e=>this.getters.getCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>void 0!==e)));let t=new Set,s=[];for(let o of e)t.add(o.evaluated.type),s.push(o.evaluated.value);let o={};for(let e of Th){let i;e.types.some((e=>t.has(e)))&&(i=e.compute(s)),o[e.name]=i}return o}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Qs(t,e)))}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{offsetX:o,offsetY:i}=this.getters.getActiveSnappedViewport(),{width:n,height:r}=this.getters.getViewportDimensionWithHeaders();for(let e of s)e.x>=o+n||e.x+e.width<=o||e.y>=i+r||e.y+e.height<=i||t.push(e);return t}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},((t,s)=>e[o]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const o=this.getters.getActiveSheet().rows.length-1;let i={left:e,right:e,top:0,bottom:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().rows.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Ks(i,{left:e,right:e,top:l,bottom:o}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectRow(e,t,s){const o=this.getters.getActiveSheet().cols.length-1;let i={top:e,bottom:e,left:0,right:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().cols.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Ks(i,{left:l,right:o,top:t,bottom:t}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectAll(){const e={left:0,top:0,bottom:this.getters.getActiveSheet().rows.length-1,right:this.getters.getActiveSheet().cols.length-1};this.dispatch("SET_SELECTION",{zones:[e],anchor:[0,0],anchorZone:e})}selectCell(e,t){const s=this.getters.getActiveSheet();this.moveClient({sheetId:s.id,col:e,row:t});const o=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});let i;i=this.mode===Rh.expanding?ao([...this.selection.zones,o]):[o],this.selection=this.clipSelection(s.id,{anchor:[e,t],zones:i,anchorZone:o}),this.activeCol=this.selection.anchor[0],this.activeRow=this.selection.anchor[1]}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}getNextAvailablePosition(e,t){return{col:this.getNextAvailableCol(e,this.activeCol,this.activeRow),row:this.getNextAvailableRow(t,this.activeCol,this.activeRow)}}getNextAvailableCol(e,t,s){const{cols:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,t,n,(e=>this.getters.isInSameMerge(i,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,s,n,(e=>this.getters.isInSameMerge(i,t,s,t,e)))}getNextAvailableHeader(e,t,s,o,i){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=o;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;i(d);)d+=e;for(;null===(n=t[d])||void 0===n?void 0:n.isHidden;)d+=e}else if(null===(r=t[d])||void 0===r?void 0:r.isHidden)for(;null===(a=t[d])||void 0===a?void 0:a.isHidden;)d+=e;return d<0||d>t.length-1?t[s].isHidden?this.getNextAvailableHeader(-e,t,s,o,i):s:d}movePosition(e,t){const{col:s,row:o}=this.getNextAvailablePosition(e,t);this.selectCell(s,o)}setSelection(e,t,s,o=!1){this.selectCell(...e);const i=this.getters.getActiveSheetId();let n;t=ao(t),n=o?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(i,e))),anchorZone:this.getters.expandZone(i,s)},this.selection=this.clipSelection(i,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:o,top:i,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&zs(e,"cols",Es(s,o+1))||r,row:e.rows[a].isHidden&&zs(e,"rows",Es(i,n+1))||a}}moveSelection(e,t){const s=this.selection;let o=[];const[i,n]=s.anchor,{left:r,right:a,top:l,bottom:c}=s.anchorZone;let h=s.anchorZone;const d=this.getters.getActiveSheet(),u=e=>{const{left:t,right:s,top:o,bottom:i}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,o),bottom:Math.min(d.rows.length-1,i)}},{col:p,row:g}=this.getReferencePosition();let f=0;for(;null!==h;){if(f++,e<0){const t=this.getNextAvailableCol(e,a-(f-1),g);h=p<=a-f?u({top:l,left:r,bottom:c,right:t}):null}if(e>0){const t=this.getNextAvailableCol(e,r+(f-1),g);h=r+f<=p?u({top:l,left:t,bottom:c,right:a}):null}if(t<0){const e=this.getNextAvailableRow(t,p,c-(f-1));h=g<=c-f?u({top:l,left:r,bottom:e,right:a}):null}if(t>0){const e=this.getNextAvailableRow(t,p,l+(f-1));h=l+f<=g?u({top:e,left:r,bottom:c,right:a}):null}if(h=h?lo(h):h,h&&!Qs(h,s.anchorZone))return o=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h})}h=u(Ks({top:n,bottom:n,left:i,right:i},lo({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Qs(h,s.anchorZone)||(o=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[o,i]=s.anchor,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[o,i],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:o}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:o},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),o=s.cols.length-1,i=s.rows.length-1,n=t.zones.map((e=>({left:ms(e.left,0,o),right:ms(e.right,0,o),top:ms(e.top,0,i),bottom:ms(e.bottom,0,i)})));return{anchor:[ms(t.anchor[0],0,o),ms(t.anchor[1],0,i)],zones:n,anchorZone:{left:ms(t.anchorZone.left,0,o),right:ms(t.anchorZone.right,0,o),top:ms(t.anchorZone.top,0,i),bottom:ms(t.anchorZone.bottom,0,i)}}}onColumnsRemoved(e){const t=Ys(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Ys(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=Xs(this.getSelectedZone(),"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.setSelection([t.left,t.top],[t],t,!0)}updateSelectionZones(e){let t=[...this.selection.zones];const s=this.selection.anchorZone,o=t.findIndex((e=>Qs(e,s)));return o>=0&&(t[o]=e),t}activateNextSheet(e){const t=this.getters.getSheets().map((e=>e.id)),s=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const s="COL"===e.dimension,o=e.elements[0],i=e.elements[t-1],n=e.base<o,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?o+r:0,right:s?i+r:l.cols.length-1,top:s?0:o+a,bottom:s?l.rows.length-1:i+a}]}),this.dispatch("PASTE",{target:[{left:s?e.base:0,right:s?e.base+t-1:l.cols.length-1,top:s?0:e.base,bottom:s?l.rows.length-1:e.base+t-1}]});const c=n?e.elements.map((e=>e+t)):e.elements;let h=e.base;for(const t of c){const s="COL"===e.dimension?this.getters.getCol(e.sheetId,t).size:this.getters.getRow(e.sheetId,t).size;this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:s,elements:[h]}),h+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*o,s.globalCompositeOperation="multiply";for(const e of i){const[o,i,n,r]=this.getters.getRect(e,t);s.fillRect(o,i,n,r),s.strokeRect(o,i,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*o,c=this.getters.isInMerge(r,a,l)?this.getters.getMerge(r,a,l):{top:l,bottom:l,left:a,right:a};const[h,d,u,g]=this.getters.getRect(c,t);u>0&&g>0&&s.strokeRect(h,d,u,g)}}Lh.layers=[5],Lh.modes=["normal"],Lh.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const Mh=a("The cell you are trying to edit has been deleted.");class Ah extends Ch{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheet="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.multiSelectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),s=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(s.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection);break;case"STOP_EDITION":e.cancel?(this.cancelEdition(),this.resetContent()):this.stopEdition();break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0);break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEdition(),this.resetContent();break;case"SELECT_CELL":case"SET_SELECTION":case"MOVE_POSITION":switch(this.mode){case"editing":this.dispatch("STOP_EDITION");break;case"waitingForRangeSelection":this.insertSelectedRange();break;case"rangeSelected":switch(e.type){case"MOVE_POSITION":this.replaceAllSelectedRanges();break;case"SELECT_CELL":this.getters.getSelectionMode()===Rh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Rh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges():this.replaceSelectedRange()}}break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((t=>{let s=t.value;const{xc:o,sheetName:i}=ts(s),n=i||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Qs(this.getters.expandZone(r,Ws(o)),e.zone)&&this.getters.getSheetName(r)===n}));this.previousRef=t.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=t.start;break;case"CHANGE_HIGHLIGHT":const s=this.getZoneReference(e.zone,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheet)||"inactive"===this.mode||(this.cancelEdition(),this.resetContent(),this.ui.notifyUI({type:"NOTIFICATION",text:Mh}))}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheet}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"waitingForRangeSelection"===this.mode||"rangeSelected"===this.mode||"resettingPosition"===this.mode}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((s=>s.start<=e&&s.end>=t))}validateSelection(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e?0:31}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Mh});const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",e.elements);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Mh});const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",e.elements);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Xs({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}startComposerRangeSelection(){this.mode="resettingPosition",this.sheet===this.getters.getActiveSheetId()&&this.dispatch("SELECT_CELL",{col:this.col,row:this.row}),this.mode="waitingForRangeSelection",this.multiSelectionInitialStart=this.selectionStart}startEdition(e,t){const s=this.getters.getActiveCell();this.initialContent=(null==s?void 0:s.composerContent)||"",this.mode="editing";const[o,i]=this.getters.getPosition();this.col=o,this.row=i,this.sheet=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={}}stopEdition(){if("inactive"!==this.mode){this.cancelEdition();const e=this.getters.getActiveSheetId(),t=this.getters.getSheets().find((e=>e.id===this.sheet)).id,[s,o]=this.getters.getMainCell(t,this.col,this.row);let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const t=this.getters.getCell(e,s,o);if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,s=e-t;s>0&&(i+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(i=Ts(i,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:o,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:o});e!==this.sheet&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheet}),this.setContent("")}}cancelEdition(){this.mode="inactive"}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){e=e.replace(/[\r\n]/g,"");const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Gr(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUI({type:"NOTIFICATION",text:a("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=this.getZoneReference(this.getters.getSelectedZone());if("waitingForRangeSelection"===this.mode)return this.insertText(t,e),this.selectionInitialStart=e,void(this.mode="rangeSelected");this.insertText(","+t,e),this.selectionInitialStart=e+1}replaceSelectedRange(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.selectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone()))}replaceAllSelectedRanges(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.multiSelectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone())),this.selectionInitialStart=this.multiSelectionInitialStart}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const s=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${fs(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(s,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:o,end:o}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"REFERENCE"===e.type))){let o=s.value;const{xc:i,sheetName:n}=ts(o);if(es.test(i)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+i.replace(/\$/g,"");e.push(s);const o=this.colorIndexByRange[s];void 0!==o&&(t[s]=o)}}this.colorIndexByRange=t;let s=Object.values(t),o=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(o);)o++;s.push(o),this.colorIndexByRange[e]=o}return[e,jt[this.colorIndexByRange[e]%jt.length]]}))}canStartComposerRangeSelection(){if("editing"!==this.mode&&this.selectionStart===this.selectionEnd)return!1;if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(e){const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let s=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}s++,o=this.currentTokens[s]}return!0}return!1}}Ah.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],Ah.modes=["normal"];const _h=cr.mapping;class Oh extends Ch{constructor(e,t,s,o){super(e,t,s,o),this.isUpToDate=new Set,this.evalContext=o.evalContext,o.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch($e.has(e.type)&&this.isUpToDate.clear(),e.type){case"UPDATE_CELL":"content"in e&&this.isUpToDate.clear();break;case"ACTIVATE_SHEET":this.evaluate(e.sheetIdTo),this.isUpToDate.add(e.sheetIdTo);break;case"EVALUATE_CELLS":this.evaluate(e.sheetId),this.isUpToDate.add(e.sheetId);break;case"EVALUATE_ALL_SHEETS":this.evaluateAllSheets()}}finalize(){const e=this.getters.getActiveSheetId();this.isUpToDate.has(e)||(this.evaluate(e),this.isUpToDate.add(e))}evaluateFormula(e,t=this.getters.getActiveSheetId()){const s=Zr(e),o=this.getFormulaParameters((()=>{})),i=[];for(let e of s.dependencies)i.push(this.getters.getRangeFromSheetXC(t,e));return s.execute(i,t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(i),o={};for(let s of Object.values(t))i(s,e);function i(e,t){if(!e.isFormula())return;const i=e.id;if(i in o)null===o[i]&&e.assignError("#CYCLE",a("Circular reference"));else{o[i]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(i);return is(e.col,e.row)},e.assignValue(e.compiledFormula.execute(e.dependencies,t,...s)),Array.isArray(e.evaluated.value))throw new Error(a("This formula depends on invalid values"))}catch(t){!function(e,t){if(e instanceof Error||(e=new Error(e)),"#CYCLE"!==t.evaluated.value){t.assignValue("#ERROR");const o=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",o))}}(t,e)}o[i]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(_h),this.evalContext,{getters:this.getters}),s=this.getters;function o(t,s){if(e(t,s),t.evaluated.type===Fe.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function i(e){const i=e.sheetId;if(!qs(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:s.getNumberRows(i)-1,left:0,right:s.getNumberCols(i)-1},r=[],l=function(e,t){if(Js(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}(e.zone,n);if(!l)return r.push([]),r;for(let s=l.left;s<=l.right;s++){const i=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);i.push(r?o(r,e.sheetId):void 0)}r.push(i)}return r}return[function(e,i,n,r,l,c){const h=i[e];if(r)return t.getters.getRangeString(h,n);if(!qs(h.zone))throw new Error(a("Invalid reference"));if(h.zone.bottom!==h.zone.top||h.zone.left!==h.zone.right)throw new Error(c?a("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",l.toString(),c.toString()):a("Function %s expects its parameters to be single values or single cell references, not ranges.",l.toString()));if(h.invalidSheetName)throw new Error(a("Invalid sheet name: %s",h.invalidSheetName));return function(e){let t;if(!s.tryGetSheet(e.sheetId))throw new Error(a("Invalid sheet name"));return t=s.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?null:o(t,e.sheetId)}(h)},function(e,t,s){return i(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Oh.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Oh.modes=["normal"];const Nh=["rgb(31,119,180)","rgb(255,127,14)","rgb(174,199,232)","rgb(255,187,120)","rgb(44,160,44)","rgb(152,223,138)","rgb(214,39,40)","rgb(255,152,150)","rgb(148,103,189)","rgb(197,176,213)","rgb(140,86,75)","rgb(196,156,148)","rgb(227,119,194)","rgb(247,182,210)","rgb(127,127,127)","rgb(199,199,199)","rgb(188,189,34)","rgb(219,219,141)","rgb(23,190,207)","rgb(158,218,229)"];class kh{constructor(){this.graphColorIndex=0}next(){return Nh[this.graphColorIndex++%Nh.length]}}class Fh extends Ch{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if($e.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&"content"in e)for(let e of Object.keys(this.chartRuntime))this.outOfDate.add(e);switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":const t=this.getters.getChartDefinition(e.id);this.chartRuntime[e.id]=this.mapDefinitionToRuntime(t);break;case"DELETE_FIGURE":delete this.chartRuntime[e.id];break;case"REFRESH_CHART":this.evaluateUsedSheets([e.id]),this.outOfDate.add(e.id);break;case"ACTIVATE_SHEET":const s=this.getters.getChartsIdBySheet(e.sheetIdTo);this.evaluateUsedSheets(s);break;case"DELETE_SHEET":for(let e of Object.keys(this.chartRuntime))this.getters.getChartDefinition(e)||delete this.chartRuntime[e]}}getChartRuntime(e){if(this.outOfDate.has(e)||!(e in this.chartRuntime)){const t=this.getters.getChartDefinition(e);if(void 0===t)return;this.chartRuntime[e]=this.mapDefinitionToRuntime(t),this.outOfDate.delete(e)}return this.chartRuntime[e]}truncateLabel(e){return e?e.length>20?e.substring(0,20)+"…":e:""}getDefaultConfiguration(e,t){const s={};e.labelRange||1!==e.dataSets.length?s.position=e.legendPosition:s.display=!1;const o={type:e.type,options:{legend:s,responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:e.title}},data:{labels:t.map(this.truncateLabel),datasets:[]}};return"pie"!==e.type?(o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0)):o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}getSheetIdsUsedInChart(e){const t=new Set;for(let s of e.dataSets)t.add(s.dataRange.sheetId);return e.labelRange&&t.add(e.labelRange.sheetId),t}evaluateUsedSheets(e){const t=new Set;for(let s of e){const e=this.getters.getChartDefinition(s);(void 0!==e?this.getSheetIdsUsedInChart(e):[]).forEach((e=>{e!==this.getters.getActiveSheetId()&&t.add(e)}))}for(let e of t)this.dispatch("EVALUATE_CELLS",{sheetId:e})}mapDefinitionToRuntime(e){let t=[];if(e.labelRange)e.labelRange.invalidXc||e.labelRange.invalidSheetName||(t=this.getters.getRangeFormattedValues(e.labelRange));else if(1===e.dataSets.length)for(let s=0;s<this.getData(e.dataSets[0],e.sheetId).length;s++)t.push("");else if(e.dataSets[0]){t=Es(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),o=new kh,i=[];if("pie"===e.type){const t=Math.max(...e.dataSets.map((t=>this.getData(t,e.sheetId).length)));for(let e=0;e<=t;e++)i.push(o.next())}for(const[t,n]of Object.entries(e.dataSets)){let r;if(n.labelCell){const e=n.labelCell,s=e?this.getters.getCell(e.sheetId,e.zone.left,e.zone.top):void 0;r=s&&e?this.truncateLabel(s.formattedValue):r=`${Sc.Series} ${parseInt(t)+1}`}else r=r=`${Sc.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?o.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=i),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[js(e.labelCell.zone)]:[],s=to([js(e.dataRange.zone)],t)[0];if(void 0===s)return[];const o=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(o)}return[]}}Fh.getters=["getChartRuntime"],Fh.modes=["normal"];class $h extends Ch{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===Fe.error)return!1;const s=t.values.map(jr);switch(t.operator){case"IsEmpty":return!_s(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return _s(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(_s(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(_s(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return _s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(_s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return _s(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!_s(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return _s(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return _s(e)&&e.evaluated.value>=s[0];case"LessThan":return _s(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return _s(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!_s(e)&&""===s[0])&&(_s(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||_s(e)&&e.evaluated.value===s[0];default:console.warn(a("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch(e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const s=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of o)this.adaptRules(s,t,[is(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation);break;case"DUPLICATE_SHEET":case"CREATE_SHEET":case"DELETE_SHEET":case"ADD_CONDITIONAL_FORMAT":case"REMOVE_CONDITIONAL_FORMAT":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":case"UNDO":case"REDO":case"DELETE_CELL":case"INSERT_CELL":this.isStale=!0}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getConditionalStyle(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedStyles[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const s=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t))try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const n=Ws(i);for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[o.rule.type];let a=this.getters.getCell(t,r,i);n&&n(a,o.rule)&&(s[r]||(s[r]=[]),s[r][i]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[i])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,s){switch(t.type){case"value":return this.getters.evaluateFormula(`=${s}(${e})`);case"number":return Number(t.value);case"percentage":const o=this.getters.evaluateFormula(`=min(${e})`);return o+(this.getters.evaluateFormula(`=max(${e})`)-o)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===o||s>o)return;const i=Ws(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=i.top;e<=i.bottom;e++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getCell(n,l,e);if((null==i?void 0:i.evaluated.type)!==Fe.number)continue;const c=this.computeIcon(i.evaluated.value,o,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyColorScale(e,t){var s;const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===o||null===n||o>=n||i&&(o>=i||i>=n))return;const r=Ws(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&i?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),c.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getCell(a,t,e);if((null==r?void 0:r.evaluated.type)===Fe.number){const a=ms(r.evaluated.value,o,n);let h;h=2===c.length&&i?a<=i?this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(a,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(s=l[t])||void 0===s?void 0:s[e])||{},l[t][e].fillColor="#"+Xt(h)}}}computeColorDiffUnits(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}colorCell(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges),r=r.concat(s);const a=to(r,o);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(Ws),sheetId:e})}pasteCf(e,t,s){const o=is(t.col,t.row);for(let i of this.getters.getConditionalFormats(e.sheetId))for(let n of i.ranges)if(eo(e.col,e.row,Ws(n))){const n=i,r=[];"CUT"===s&&r.push(is(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,n,[o],r):(this.adaptRules(t.sheetId,n,[o],[]),this.adaptRules(e.sheetId,n,[],r))}}}$h.getters=["getConditionalStyle","getConditionalIcon"],$h.modes=["normal"];var Dh;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Dh||(Dh={}));class Ph extends Ch{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Dh.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Dh.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith,e.replaceOptions);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith,e.replaceOptions);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Dh.current)}updateRegex(){let e=ps(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),s=[];if(this.toSearch)for(const e of Object.values(t))if(e&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas&&e.isFormula()?e.content:String(e.evaluated.value))){const t=this.getters.getCellPosition(e.id),o={col:t.col,row:t.row,selected:!1};s.push(o)}return s.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let s;s=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,s=(s%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===s||(this.selectedMatchIndex=s,this.dispatch("SELECT_CELL",{col:t[s].col,row:t[s].row}));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1}}replace(e,t){if(this.replaceOptions=t,null===this.selectedMatchIndex||!this.currentSearchRegex)return;const s=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell(o,s.col,s.row),n=this.toReplace(i,o);if(i&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),o=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:o}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Dh.current)}else this.selectNextCell(Dh.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let o=0;o<s;o++)this.replace(e,t)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.replaceOptions.modifyFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t,viewport:s}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge(o,e.col,e.row),n=i?i.left:e.col,r=i?i.right:e.col,a=i?i.top:e.row,l=i?i.bottom:e.row,[c,h,d,u]=this.getters.getRect({top:a,left:n,right:r,bottom:l},s);d>0&&u>0&&(t.fillStyle="#8B008B33",t.fillRect(c,h,d,u),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(c,h,d,u)))}}}Ph.layers=[3],Ph.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Uh extends Ch{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const o=this.searchNumberFormat(e,t);if(void 0!==o){const i=this.changeDecimalFormat(o,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:i})}}searchNumberFormat(e,t){var s;for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){const o=this.getters.getCell(e,i,t);if((null==o?void 0:o.evaluated.type)===Fe.number&&!(null===(s=o.format)||void 0===s?void 0:s.match(_)))return o.format||this.setDefaultNumberFormat(o.evaluated.value)}}setDefaultNumberFormat(e){const t=e.toString().split(".");return 1===t.length?"0":"0."+Array(t[1].length+1).join("0")}changeDecimalFormat(e,t){const s=Math.sign(t),o=e.split(";");let i=[];for(let e of o){const t=e.indexOf("."),o=e.toUpperCase().indexOf("E");let n;const r=o>-1?e.slice(0,o):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<re?e.slice(0,l+1)+(0===a?".0":"0")+e.slice(l+1):e:a>0?(n=e.slice(0,l)+e.slice(l+1),1===a&&(n=n.slice(0,t)+n.slice(t+1))):n=e:n=e,i.push(n)}return i.join(";")}}Uh.modes=["normal"];class Vh extends Ch{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){if(0===e.length)return[];const t=this.getters.getActiveSheetId(),s=[];for(let[o,i]of e){const{xc:e,sheetName:n}=ts(o),r=n?this.getters.getSheetIdByName(n):t;if(r){let o=Ws(e);const{height:n,width:a}=oo(o);o=n*a==1?this.getters.expandZone(t,Ws(e)):o,s.push({zone:o,color:i,sheet:r})}}return s.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getSheet(e.sheet).rows.length&&e.zone.right<this.getters.getSheet(e.sheet).cols.length))}drawGrid(e){const{ctx:t,viewport:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Qs(t.zone,e.zone)&&t.sheet===i))===t))){const[o,i,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,a-2*n))}}}function Bh(e,t){let s=0,o=e.length-1;for(;s<=o;){const i=Math.floor((s+o)/2),n=e[i];if(t<n.start)o=i-1;else if(t>n.end)s=i+1;else{if(!n.isHidden)return i;s+=1}}return-1}Vh.modes=["normal"],Vh.layers=[1],Vh.getters=["getHighlights"];class Hh extends Ch{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<v)return-1;const o=(s||this.getters.getActiveSheet()).cols;return Bh(o,e-v+o[t].start+1)}getRowIndex(e,t,s){if(e<m)return-1;const o=(s||this.getters.getActiveSheet()).rows;return Bh(o,e-m+o[t].start+1)}getRect(e,t){const{left:s,top:o,right:i,bottom:n}=e,{offsetX:r,offsetY:a}=this.getShiftedViewport(t),{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-r,v),d=l[i].end-r-h,u=Math.max(c[o].start-a,m);return[h,u,d,c[n].end-a-u]}isVisibleInViewport(e,t,s){const{right:o,left:i,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=i&&e<=o}getEdgeScrollCol(e){let t=!1,s=0,o=0;const{width:i}=this.getters.getViewportDimensionWithHeaders(),{width:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<v&&r>0?(t=!0,s=-1,o=ls(v-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}getEdgeScrollRow(e){let t=!1,s=0,o=0;const{height:i}=this.getters.getViewportDimensionWithHeaders(),{height:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,o=ls(m-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(e),this.drawBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e);break;case 7:this.drawHeaders(e)}}drawBackground(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{width:i,height:n}=this.getters.getViewportDimensionWithHeaders(),{cols:r,rows:a,id:l}=this.getters.getActiveSheet();t.fillStyle="white",t.fillRect(0,0,i,n);const{right:c,left:h,top:d,bottom:u,offsetX:p,offsetY:g}=this.getShiftedViewport(o);if(!this.getters.getGridLinesVisibility(l))return;t.lineWidth=2*s,t.strokeStyle="#E2E3E3",t.beginPath();const f=Math.min(n,a[u].end-g);for(let e=h;e<=c;e++){if(r[e].isHidden)continue;const s=r[e].end-p;t.moveTo(s,0),t.lineTo(s,f)}const m=Math.min(i,r[c].end-p);for(let e=d;e<=u;e++){if(a[e].isHidden)continue;const s=a[e].end-g;t.moveTo(0,s),t.lineTo(m,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const o=.1*s;t.strokeStyle="#111";const i=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height),i&&t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:s}=e;for(let e of this.boxes){let t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o([e,o],i,n,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(i,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let o;t.textBaseline="middle";for(let e of this.boxes)if(e.content){const i=e.style||{},n=e.content.align||"left",r=i.italic?"italic ":"",a=i.bold?"bold":T,l=i.fontSize||R,c=hs[l],h=`${r}${a} ${c}px ${L}`;let d;h!==o&&(o=h,t.font=h),t.fillStyle=i.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*y:4):"right"===n?e.x+e.width-4:e.x+e.width/2,t.textAlign=n,e.clipRect&&(t.save(),t.beginPath(),t.rect(...e.clipRect),t.clip()),t.fillText(e.content.text,Math.round(d),Math.round(u)),(i.strikethrough||i.underline)&&("right"===n?d-=e.content.width:"center"===n&&(d-=e.content.width/2),i.strikethrough&&t.fillRect(d,u,e.content.width,2.6*s),i.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.content.width,1.3*s))),e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const s=e.image.image,o=e.image.size,i=(e.height-o)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(s,e.x+y,e.y+i,o,o),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{right:i,left:n,top:r,bottom:a,offsetX:l,offsetY:p}=this.getShiftedViewport(o),{width:g,height:f}=this.getters.getViewportDimensionWithHeaders(),E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${L}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333",t.fillRect(0,0,g,m),t.fillRect(0,0,v,f),t.fillStyle=h;for(let e of E){const s=Math.max(v,b[e.left].start-l),o=Math.max(v,b[e.right].end-l),i=Math.max(m,S[e.top].start-p),n=Math.max(m,S[e.bottom].end-p);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,o-s,m),t.fillStyle=w.has(e.top)?d:h,t.fillRect(0,i,v,n-i)}t.beginPath(),t.moveTo(v,0),t.lineTo(v,f),t.moveTo(0,m),t.lineTo(g,m),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=n;e<=i;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-l,13),t.moveTo(s.end-l,0),t.lineTo(s.end-l,m))}for(let e=r;e<=a;e++){const s=S[e];s.isHidden||(t.fillStyle=w.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-p),t.moveTo(0,s.end-p),t.lineTo(v,s.end-p))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);return o&&!o.isEmpty()||this.getters.isInMerge(s,e,t)}getShiftedViewport(e){return{...e,offsetX:e.offsetX-v,offsetY:e.offsetY-m}}findNextEmptyCol(e,t,s){let o=e;for(;o<t&&!this.hasContent(o+1,s);)o++;return o}findPreviousEmptyCol(e,t,s){let o=e;for(;o>t&&!this.hasContent(o-1,s);)o--;return o}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e);return t&&e.evaluated.type===Fe.number?"center"!==s?"left":s:s||e.defaultAlign}createBoxFromPosition(e,t,s,o,i,n){const{right:r,left:a,offsetX:l,offsetY:c}=this.getShiftedViewport(o),h=this.getters.getCol(e,t),d=this.getters.getRow(e,s),u=this.getters.getCell(e,t,s),p=this.getters.shouldShowFormulas(),g={x:h.start-l,y:d.start-c,width:i,height:n,border:this.getters.getCellBorder(e,t,s)||void 0,style:{...this.getters.getCellStyle(u),...this.getters.getConditionalStyle(t,s)}};if(!u)return g;const f=this.getters.getConditionalIcon(t,s),m=g.style.fontSize||R,v=hs[m],E=f?2*y+v:0;f&&(g.image={type:"icon",size:v,clipIcon:[g.x,g.y,Math.min(E,i),n],image:Xl[f].img});const b=this.getters.getCellText(u,p),S=this.getters.getTextWidth(u),C=E+S,w=this.computeCellAlignment(u,C>i);g.content={text:b,width:S,align:w},u.evaluated.type===Fe.error&&(g.error=u.evaluated.error);const I=C>i||hs[m]>n;if(f)g.clipRect=[g.x+E,g.y,Math.max(0,i-E),n];else if(I){let o,u;switch(this.getters.isInMerge(e,t,s)?(o=this.getters.getMerge(e,t,s).right,u=t):(o=this.findNextEmptyCol(t,r,s),u=this.findPreviousEmptyCol(t,a,s)),w){case"left":{const t=this.getters.getCol(e,o).end-h.start;(t<S||v>d.size)&&(g.clipRect=[h.start-l,d.start-c,t,n]);break}case"right":{const t=this.getters.getCol(e,u),s=h.end+i-h.size-t.start;(s<S||v>d.size)&&(g.clipRect=[t.start-l,d.start-c,s,n]);break}case"center":{const s=this.getters.getCol(e,u),i=this.getters.getCol(e,o).end-s.start;(i<S||u===t||o===t||v>d.size)&&(g.clipRect=[s.start-l,d.start-c,i,n]);break}}}return g}getGridBoxes(e){const t=[],{viewport:s}=e,{right:o,left:i,top:n,bottom:r}=this.getShiftedViewport(s),a=this.getters.getActiveSheetId();for(let e=n;e<=r;e++){const n=this.getters.getRow(a,e);if(!n.isHidden)for(let r=i;r<=o;r++){const o=this.getters.getCol(a,r);o.isHidden||(this.getters.isInMerge(a,r,e)||t.push(this.createBoxFromPosition(a,r,e,s,o.size,n.size)))}}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&Js(e,s)){const o=this.getters.getCol(a,e.right).end-this.getters.getCol(a,e.left).start,i=this.getters.getRow(a,e.bottom).end-this.getters.getRow(a,e.top).start,n=this.createBoxFromPosition(a,e.left,e.top,s,o,i),r=this.getters.getCellBorder(a,e.right,e.bottom);n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}}Hh.layers=[0,7],Hh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],Hh.modes=["normal"];const zh=new Bs;class Zh extends Ch{constructor(){super(...arguments),this.inputs={},this.activeSheets={},this.inputHasSingleRange={},this.focusedInputId=null,this.focusedRange=null,this.willAddNewRange=!1}allowDispatch(e){switch(e.type){case"FOCUS_RANGE":const t=this.getIndex(e.id,e.rangeId);if(this.focusedInputId===e.id&&this.focusedRange===t)return 24;break;case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange[e.id]&&1===this.inputs[e.id].length)return 25}return 0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id],delete this.activeSheets[e.id],delete this.inputHasSingleRange[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(e.id,this.getIndex(e.id,e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.id,e.rangeId);if(null!==t){const s=e.id;this.focusedInputId===s&&this.focusedRange===t||this.dispatch("FOCUS_RANGE",{id:s,rangeId:this.inputs[s][t].id});const o=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(e.id,this.inputs[e.id].length,[""]),this.focusLast(e.id);break;case"REMOVE_RANGE":const t=this.getIndex(e.id,e.rangeId);null!==t&&this.removeRange(e.id,t);break;case"SELECT_CELL":case"SET_SELECTION":if(!this.focusedInputId)break;const s=this.getSelectionInputValue(this.focusedInputId),o=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(js).filter((e=>!s.includes(e))),i=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(o.map((e=>n===i?e:`${fs(r)}!${e}`)));break;case"PREPARE_SELECTION_EXPANSION":{const[e,t]=[this.focusedInputId,this.focusedRange];null===e||null===t||this.inputHasSingleRange[e]||(this.willAddNewRange=""!==this.inputs[e][t].xc.trim());break}}}getSelectionInput(e){return this.inputs[e]?this.inputs[e].map(((t,s)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.focusedRange&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.focusedRange===s}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=ts(e);return null!==t.match(es)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getSelectionInputValue(e){return this.cleanInputs(this.inputs[e].map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].map((e=>this.inputToHighlights(this.focusedInputId,e))).flat():[]}initInput(e,t,s=!1){this.inputs[e]=[],this.insertNewRange(e,0,t),this.activeSheets[e]=this.getters.getActiveSheetId(),this.inputHasSingleRange[e]=s,0===this.inputs[e].length&&this.dispatch("ADD_EMPTY_RANGE",{id:e})}focus(e,t){this.focusedInputId=e,this.focusedRange=t}focusLast(e){this.focus(e,this.inputs[e].length-1)}unfocus(){this.focusedInputId=null,this.focusedRange=null}add(e){if(null===this.focusedInputId||null===this.focusedRange||this.getters.isSelectingForComposer()||0===e.length)return;if(this.getters.getSelectionMode()===Rh.expanding&&this.willAddNewRange){const t=this.focusedInputId;this.insertNewRange(t,this.inputs[t].length,e),this.focusLast(this.focusedInputId),this.willAddNewRange=!1}else this.setRange(this.focusedInputId,this.focusedRange,e)}setContent(e,t,s){this.inputs[e][t]={...this.inputs[e][t],id:zh.uuidv4(),xc:s}}insertNewRange(e,t,s){this.inputs[e].splice(t,0,...s.map(((t,s)=>({xc:t,id:(this.inputs[e].length+s+1).toString(),color:Kt()}))))}setRange(e,t,s){const[,...o]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,o),o.length&&this.focus(e,t+o.length)}removeRange(e,t){this.inputs[e].splice(t,1),this.focusedInputId===e&&null!==this.focusedRange&&this.focusLast(e)}inputToHighlights(e,{xc:t,color:s}){const o=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===o.length)return[];const[i,...n]=o,r=[[i,s||Kt()]];for(const e of n)r.push([e,Kt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=ts(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Zh.modes=["normal"],Zh.layers=[1],Zh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Gh{constructor(){this.bus=new o.core.EventBus}on(e,t,s){this.bus.on(e,t,s)}trigger(e,t){this.bus.trigger(e,t)}off(e,t){this.bus.off(e,t)}clear(){this.bus.clear()}}function Wh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<=r&&e[o]>=r&&n--;if(!(i>n))return{...e,[t]:i,[o]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom",l="before"===o?e[a]>r:e[a]>=r;return e[t]<=r&&l?ro(e,n,"RESIZE",i):r<e[t]?ro(e,n,"MOVE",i):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function qh(e,t){const s=e.definition;let o,i;return s.labelRange&&(o=Wh(Ws(s.labelRange),t)),s.dataSets&&(i=s.dataSets.map(Ws).map((e=>Wh(e,t))).filter(_s).map(js)),{...e,definition:{...s,dataSets:i,labelRange:o?js(o):void 0}}}Cl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qh),Cl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qh),Cl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Cl.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var s;if(e.name===t.name)return{...e,name:(null===(s=e.name)||void 0===s?void 0:s.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Cl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)for(const e of t.target)Js(o,e)||s.push({...o});if(s.length)return{...e,target:s};return}));const jh=[{match:function(e){return"sheetId"in e},fn:function(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if(e.sheetId===s)return"IGNORE_COMMAND";if("CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId)return e;return"SKIP_TRANSFORMATION"}},{match:function(e){return"target"in e},fn:function(e,t){const s=[];for(const o of e.target){const e=Wh(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"col"in e&&"row"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&eo(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const s="ADD_COLUMNS_ROWS"===e.type,o=s?"base":"elements";let i=s?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(i=i.map((e=>{if(t.elements.includes(e))return;const s=t.elements.sort(((e,t)=>t-e));for(let t of s)e>t&&e--;return e})).filter(_s)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;i=i.map((s=>s>e?s+t.quantity:s))}if(i.length){let t=i;return s&&(t=i[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Xh(e,t){const s=Cl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:o}of jh)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Yh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Xh(t,e))).filter(_s);return s}class Kh{constructor(e,t,s,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Qh extends Error{}class Jh extends Gh{constructor(e,t,s=N){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Bs,this.debouncedMove=o.utils.debounce(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const s=new Kh(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(s.id,s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0,this.on("unexpected-revision-id",this,(({revisionId:e})=>{throw new Error(`The spreadsheet could not be loaded. Revision ${e} is corrupted.`)}));for(const t of e)this.onMessageReceived(t);this.off("unexpected-revision-id",this),this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Qh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(_s))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const s=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==s?void 0:s.col)===e.col&&s.row===e.row&&s.sheetId===e.sheetId)return;const o=s?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){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":if(e.serverRevisionId!==this.serverRevisionId)return void this.trigger("unexpected-revision-id",{revisionId:e.serverRevisionId});const{clientId:t,commands:s}=e,o=new Kh(e.nextRevisionId,t,s);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Yh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Kh(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");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;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({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.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const ed=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class td extends Ch{constructor(){super(...arguments),this.availableColors=new Set(ed),this.colors={}}isPositionValid(e){const t=this.getters.getSheet(e.sheetId);return e.row<t.rows.length&&e.col<t.cols.length}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(ed));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof Qh)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())if(s.id!==this.getters.getClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)){const e=s.position;this.colors[s.id]||(this.colors[s.id]=this.chooseNewColor());const o=this.colors[s.id];t.push({...s,position:e,color:o})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),[l,c,h,d]=this.getters.getRect(a,t);if(h<=0||d<=0)continue;const u=e.color,p=`${u}10`;s.fillStyle=p,s.lineWidth=4*o,s.strokeStyle=u,s.globalCompositeOperation="multiply",s.fillRect(l,c,h,d),s.globalCompositeOperation="source-over",s.strokeRect(l,c,h,d),s.font=`bold ${R+1}px ${L}`}}}td.getters=["getClientsToDisplay"],td.layers=[5],td.modes=["normal"];class sd extends Ch{allowDispatch(e){if("SORT_CELLS"===e.type){if(!eo(e.col,e.row,e.zone))throw new Error(a("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection)}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let s=t.top;s<=t.bottom;s++)for(let o=t.left;o<=t.right;o++)if(!this.getters.isInMerge(e,o,s))return 48;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const s=this.getters.getMerges(e).filter((e=>Js(e,t))),o=oo(s[0]);let[i,n]=[o.width,o.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n}))?0:48}expand(e,t){const{left:s,right:o,top:i,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,o),top:Math.max(0,i),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),o=e.id;let i,n=[];if(this.getters.doesIntersectMerge(o,s)){const{left:e,right:t,top:r,bottom:a}=s;for(let s=e;s<=t;s++)for(let e=r;e<=a;e++){const[t,r]=this.getters.getMainCell(o,s,e);i=this.getters.getCell(o,t,r),n.push((null==i?void 0:i.formattedValue)||"")}}else n=this.getters.getCellsInZone(o,s).map((e=>(null==e?void 0:e.formattedValue)||""));return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:o,bottom:i,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,o>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o-1,bottom:o-1}),s&&(l=!1,o--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:o-1,bottom:i+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:o-1,bottom:i+1}),s&&(l=!1,r++)),i<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i+1,bottom:i+1}),s&&(l=!1,i++));return{left:n,right:r,top:o,bottom:i}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||Fe.empty))));return t[0][0]===Fe.empty&&(t=t.slice(1)),!t.some((e=>e[0]===Fe.empty))&&!!t.some((e=>e[1]!==Fe.empty&&e[0]!==e[1]))}sortZone(e,t,s,o){const[i,n]=this.mainCellsSteps(e,s);let r=this.getters.getMainCell(e,t.col,t.row)[0],a=Object.assign({},s),l=this.mainCells(e,s);this.hasHeader(l)&&(a.top+=n),l=this.mainCells(e,a);const c=function(e,t){const s=e.map(Da),o=s.filter((e=>e.type===Fe.empty)),i=s.filter((e=>e.type!==Fe.empty)),n="descending"===t?-1:1;return i.sort(((e,t)=>{let s=$a.indexOf(e.type)-$a.indexOf(t.type);return 0===s&&(s=e.type===Fe.text||e.type===Fe.error?e.value.localeCompare(t.value):e.value-t.value),n*s})).concat(o)}(l[r-a.left],o),h=c.map((e=>e.index)),[d,u]=[l.length,l[0].length];for(let t=0;t<d;t++)for(let s=0;s<u;s++){let o=l[t][h[s]],r=a.left+t*i,c=a.top+s*n,d={sheetId:e,col:r,row:c,content:"",value:""};if(o){let t=o.content;if(o.isFormula()){const s=c-this.getters.getCellPosition(o.id).row,i=this.getters.createAdaptedRanges(o.dependencies,0,s,e);t=this.getters.buildFormulaContent(e,o,i)}d.style=o.style,d.content=t,d.format=o.format,d.value=o.evaluated.value}this.dispatch("UPDATE_CELL",d)}}mainCellsSteps(e,t){const s=this.getters.getMerge(e,t.left,t.top);return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=Es(t.left,t.right+1,s),r=Es(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push(this.getters.getCell(e,t,o))}return i}}sd.getters=["getContiguousZone"];class od extends Ch{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}od.modes=["normal"],od.getters=["shouldShowFormulas"];class id extends Ch{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s+6,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows){const s=this.getRowMaxHeight(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:s+6,sheetId:e.sheetId})}}}getCellWidth(e){let t=this.getTextWidth(e);const s=this.getters.getCellPosition(e.id);return this.getters.getConditionalIcon(s.col,s.row)&&(t+=function(e,t){const s=t.fontSize||R;return hs[s]+2*y}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return vs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||R;return hs[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===Fe.error)?e.content:e.formattedValue}getColMaxWidth(e,t){const s=this.getters.getColCells(e,t).map((e=>this.getCellWidth(e)));return Math.max(0,...s)}getRowMaxHeight(e,t){const s=this.getters.getSheet(e),o=Object.values(s.rows[t].cells).filter(_s).map((e=>this.getters.getCellById(e))).map((e=>this.getCellHeight(e)));return Math.max(0,...o)}}id.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class nd extends Ch{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.viewportWidth=1e3,this.viewportHeight=1e3}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkOffsetValidity(e.offsetX,e.offsetY);case"RESIZE_VIEWPORT":return e.width<0||e.height<0?54:0;default:return 0}}handle(e){switch(e.type){case"UNDO":case"REDO":this.cleanViewports(),this.resetViewports();break;case"RESIZE_VIEWPORT":this.cleanViewports(),this.resizeViewport(e.height,e.width);break;case"SET_VIEWPORT_OFFSET":this.setViewportOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getActiveTopRow(),s=this.clipOffsetY(t.start+this.viewportHeight);this.shiftVertically(s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getActiveTopRow(),t=this.clipOffsetY(e.end-this.viewportHeight);this.shiftVertically(t);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportOffsetX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportOffsetY(e.sheetId,this.getViewport(e.sheetId));break;case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportZoneX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportZoneY(e.sheetId,this.getViewport(e.sheetId));break;case"ACTIVATE_SHEET":this.refreshViewport(e.sheetIdTo);break;case"SELECT_CELL":case"MOVE_POSITION":this.refreshViewport(this.getters.getActiveSheetId())}}finalize(){this.updateSnap&&(this.snapViewportToCell(this.getters.getActiveSheetId()),this.updateSnap=!1)}getViewportDimensionWithHeaders(){return{width:this.viewportWidth+v,height:this.viewportHeight+m}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getMaxViewportSize(e){const t=Zs(e,"cols"),s=Zs(e,"rows"),o=e.cols.find((e=>e.end>t.end-this.viewportWidth))||e.cols[e.cols.length-1],i=e.rows.find((e=>e.end>s.end-this.viewportHeight))||e.rows[e.rows.length-1];return{width:t.end+Math.max(b,Math.min(o.size,this.viewportWidth-t.size)),height:s.end+Math.max(S+5,Math.min(i.size,this.viewportHeight-s.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getMaxViewportSize(e);return{maxOffsetX:Math.max(0,t-this.viewportWidth+1),maxOffsetY:Math.max(0,s-this.viewportHeight+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumViewportOffset(s);return e<0||t<0||t>i||e>o?53:0}getSnappedViewport(e){return this.snapViewportToCell(e),this.snappedViewports[e]}getViewport(e){return this.viewports[e]?this.viewports[e]:this.generateViewportState(e)}cleanViewports(){const e=this.getters.getVisibleSheets();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetViewports(){for(let[e,t]of Object.entries(this.viewports))this.adjustViewportOffsetX(e,t),this.adjustViewportOffsetY(e,t),this.adjustViewportsPosition(e)}adjustViewportOffsetX(e,t){const{offsetX:s}=t,{width:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportWidth+s>o){const e=this.viewportWidth+s-o;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportHeight+s>o){const e=this.viewportHeight+s-o;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.viewportHeight=e,this.viewportWidth=t,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.adjustViewportOffsetX(e,this.viewports[e]),this.adjustViewportOffsetY(e,this.viewports[e])}setViewportOffset(e,t){const s=this.getters.getActiveSheetId();this.getActiveViewport(),this.viewports[s].offsetX=e,this.viewports[s].offsetY=t,this.adjustViewportZone(s,this.viewports[s])}clipOffsetY(e){const{height:t}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),s=t-this.viewportHeight;return e=Math.min(e,s),e=Math.max(e,0)}generateViewportState(e){return this.viewports[e]={left:0,right:0,top:0,bottom:0,offsetX:0,offsetY:0},this.viewports[e]}refreshViewport(e){const t=this.getViewport(e);this.adjustViewportZone(e,t),this.adjustViewportsPosition(e)}adjustViewportZone(e,t){this.adjustViewportZoneX(e,t),this.adjustViewportZoneY(e,t)}adjustViewportZoneX(e,t){const s=this.getters.getSheet(e),o=s.cols;t.left=this.getters.getColIndex(t.offsetX+v,0,s);const i=this.viewportWidth+t.offsetX;t.right=o.length-1;for(let e=t.left;e<o.length;e++)if(i<o[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),o=s.rows;t.top=this.getters.getRowIndex(t.offsetY+m,0,s);const i=this.viewportHeight+t.offsetY;t.bottom=o.length-1;for(let e=t.top;e<o.length;e++)if(i<o[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:o,rows:i}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=Hs(s,...this.getters.getMainCell(e,t[0],t[1]));for(;o[r].end>n.offsetX+this.viewportWidth&&n.offsetX<o[r].start;)n.offsetX=o[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=o.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=o[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;i[a].end>n.offsetY+this.viewportHeight&&n.offsetY<i[a].start;)n.offsetY=i[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=i.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=i[n.top-1-t].start,this.adjustViewportZoneY(e,n)}const{top:l,left:c}=this.viewports[e];l===n.top&&c===n.left||(this.viewports[e]=n),this.updateSnap=!1}snapViewportToCell(e){const{cols:t,rows:s}=this.getters.getSheet(e),o=this.getViewport(e),i=Object.assign({},o);this.adjustViewportOffsetX(e,i),this.adjustViewportOffsetY(e,i),i.offsetX=t[i.left].start,i.offsetY=s[i.top].start,this.adjustViewportZone(e,i),this.snappedViewports[e]=i}shiftVertically(e){const{top:t,offsetX:s}=this.getActiveSnappedViewport();this.setViewportOffset(s,e);const{anchor:o}=this.getters.getSelection(),i=this.getActiveSnappedViewport().top-t;this.dispatch("SELECT_CELL",{col:o[0],row:o[1]+i})}getActiveTopRow(){const{top:e}=this.getActiveSnappedViewport(),t=this.getters.getActiveSheet();return this.getters.getRow(t.id,e)}}nd.getters=["getActiveViewport","getActiveSnappedViewport","getViewportDimensionWithHeaders","getMaxViewportSize","getMaximumViewportOffset"],nd.modes=["normal"];const rd=(new Me).add("sheet",Ra).add("cell",ba).add("merge",Ia).add("borders",va).add("conditional formatting",wa).add("figures",ya).add("chart",Sa),ad=(new Me).add("selection",Lh).add("ui_sheet",id).add("ui_options",od).add("evaluation",Oh).add("evaluation_cf",$h).add("evaluation_chart",Fh).add("clipboard",xh).add("edition",Ah).add("highlight",Vh).add("selectionInput",Zh).add("viewport",nd).add("grid renderer",Hh).add("autofill",yh).add("find_and_replace",Ph).add("sort",sd).add("automatic_sum",Ih).add("format",Uh).add("selection_multiuser",td);class ld{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class cd extends o.core.EventBus{constructor(){super(...arguments),this.registry=new Me}add(e,t){this.registry.add(e,t);const s=o.utils.debounce((()=>this.trigger("data-loaded",{id:e})),0);return t.on("data-loaded",this,(()=>s())),t.loadMetadata(),this}get(e){return this.registry.get(e)}getAll(){return this.registry.getAll()}remove(e){this.get(e).off("data-loaded",this),this.registry.remove(e)}async waitForReady(){const e=[];for(const t of this.getAll())e.push(t.get());return Promise.all(e)}}class hd extends o.core.EventBus{async loadMetadata(){this.metadataPromise||(this.metadataPromise=this._fetchMetadata().then((e=>(this.metadata=e,e)))),await this.metadataPromise}async get(e){return e&&e.forceFetch&&(this.data=void 0,this.dataPromise=void 0),await this.loadMetadata(),this.dataPromise||(this.dataPromise=this._fetch(e).then((e=>(this.data=e,this.lastUpdate=Date.now(),this.trigger("data-loaded"),e)))),this.dataPromise}getSync(){return this.data}getMetadataSync(){return this.metadata}getLastUpdate(){return this.lastUpdate}}function dd(e){return _a.get(e.type)(e)}function ud(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class pd{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map((e=>e.transformed(s)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new pd(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class gd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new fd(this.id,ks((()=>e(this.data))))}}class fd{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new fd(this.id,this.lazyData.map(e))}}class md{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new md(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new md(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new md(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class vd{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new md(Ss(this._execution(e),this._execution(e)))}revertedExecution(e){return new md(Ss(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const o=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex((t=>t===e));this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Ed{constructor(e,t,s,o,i){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=o,this.buildTransformation=i,this.HEAD_BRANCH=new pd(this.buildTransformation),this.tree=new vd(i,this.HEAD_BRANCH);const n=new gd(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const s=new gd(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new gd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function bd(e,t,s){return new Ed(e,(e=>{const o=e.commands.slice(),{changes:i}=t((()=>{for(const e of o)s(e)}));e.setChanges(i)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Sd(t.changes[e],"before")}}([e])),(e=>new Kh(e,"empty",[],[])),{with:e=>t=>new Kh(t.id,t.clientId,Yh(t.commands,e.commands)),without:e=>t=>new Kh(t.id,t.clientId,Yh(t.commands,e.commands.map(dd).flat()))})}function Sd(e,t){let s=e.root,o=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===s[o]){const i=e.path[t+1];s[o]=ud(i)}s=s[o]}void 0===e[t]?delete s[o]:s[o]=e[t]}class Cd extends o.core.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(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}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class wd{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return 0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const i=bs(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of i){const i=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=i&&i<=n.zone[s]){const e=Math.min(n.zone[s],l)-i+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=i&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(O);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-i))}else i<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-i+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>t.sheetId!==e.sheetId?{changeType:"NONE"}:{changeType:"REMOVE",range:t={...this.buildInvalidRange(O),invalidSheetName:this.getters.getSheetName(e.sheetId)}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const s={...t,zone:{...t.zone}};return s.invalidSheetName=void 0,s.sheetId=e.sheetId,{changeType:"CHANGE",range:s}}return{changeType:"NONE"}}))}}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||qs(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,o){return{...e,zone:ro(e.zone,t,s,o)}}executeOnAllRanges(e,t){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t)}addRangeProvider(e){this.providers.push(e)}orderZone(e,t){if(e.right<e.left){let s=e.right;e.right=e.left,e.left=s;let o=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=o}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let o=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=o}}createAdaptedRanges(e,t,s,o){return e.map((e=>qs(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:o,zone:{left:e.zone.left+(e.parts[0].colFixed?0:t),right:e.zone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.zone.top+(e.parts[0].rowFixed?0:s),bottom:e.zone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)}},this.orderZone(e.zone,e.parts),e):e))}getRangeFromSheetXC(e,t){let s,o,i,n=t,r=!1;if(!es.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=ts(t)),s?(o=this.getters.getSheetIdByName(s),r=!0,o||(i=s)):i=s);const a=Gs(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:o||e,zone:a,parts:l,invalidSheetName:i,prefixSheet:r}}getRangeString(e,t){if(!e)return O;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return O;if(e.zone.left<0||e.zone.top<0)return O;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,o="";if(s&&(o=e.invalidSheetName?e.invalidSheetName:fs(this.getters.getSheetName(e.sheetId))),s&&!o)return O;let i=Array(9);return i[0]=e.parts&&e.parts[0].colFixed?"$":"",i[1]=ss(e.zone.left),i[2]=e.parts&&e.parts[0].rowFixed?"$":"",i[3]=String(e.zone.top+1),e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i[4]=":",i[5]=e.parts[1].colFixed?"$":"",i[6]=ss(e.zone.right),i[7]=e.parts[1].rowFixed?"$":"",i[8]=String(e.zone.bottom+1)),`${s?o+"!":""}${i.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}wd.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class yd{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop(),[s,...o]=e;let i=s,n=o[o.length-1];for(let e=0;e<=o.length-2;e++){const t=o[e];if(void 0===i[t]){const s=o[e+1];i[t]=ud(s)}i=i[t]}i[n]!==t&&(this.changes.push({root:s,path:o,before:i[n],after:t}),void 0===t?delete i[n]:i[n]=t)}}const Id={General:0,0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},xd={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Td={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"},Rd="http://schemas.openxmlformats.org/drawingml/2006/main",Ld="http://schemas.openxmlformats.org/drawingml/2006/chart",Md={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+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"},Ad="http://schemas.openxmlformats.org/officeDocument/2006/relationships",_d=.75,Od=.1425,Nd=164,kd={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}]},Fd=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","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","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","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","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"];function $d(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Dd(e){return Math.round(_d*e*window.devicePixelRatio*100)/100}function Pd(e){return Math.round(Od*e*100)/100}function Ud(e,t){let s={};e.style&&(s=t.styles[e.style]);const o=e.format?t.formats[e.format]:void 0;let i={};e.border&&(i=t.borders[e.border]);const n={font:{size:(null==s?void 0:s.fontSize)||R,color:(null==s?void 0:s.textColor)?s.textColor:"000000",family:2,name:"Arial"},fill:(null==s?void 0:s.fillColor)?{fgColor:s.fillColor}:{reservedAttribute:"none"},numFmt:o,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return n.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,n.font.underline=!!(null==s?void 0:s.underline)||void 0,n.font.bold=!!(null==s?void 0:s.bold)||void 0,n.font.italic=!!(null==s?void 0:s.italic)||void 0,n}function Vd(e,t){const{id:s}=Hd(t.font,e.fonts),{id:o}=Hd(t.fill,e.fills),{id:i}=Hd(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=Id[e];if(!s){const{id:o}=Hd(e,t);s=o+Nd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:o,borderId:i,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=Hd(r,e.styles);return a}function Bd(e,t,s){let o,i=e.find((e=>e.path===t));return i?(o=`rId${(i.rels.length+1).toString()}`,i.rels.push({...s,id:o})):(o="rId1",e.push({path:t,rels:[{...s,id:o}]})),o}function Hd(e,t){for(let[s,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(s,10),list:t};let s=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===s&&(t.push(e),s=t.length-1),{id:s,list:t}}const zd=[];function Zd(e){const t=zd.findIndex((t=>t===e));return-1===t?(zd.push(e),zd.length):t+1}function Gd(e){return Math.round(914400*e/96)}class Wd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function qd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function jd(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'")}function Xd(e){return new Wd(e.map((([e,t])=>`${e}="${jd(t)}"`)).join(" "))}function Yd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,o=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(o-3,0),Math.min(o+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Kd(e,t){return Jd`
|
|
1048
|
+
`;class Eh extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.state=t.useState(this.initialState())}get hasSearchResult(){return null!==this.env.getters.getCurrentSelectedMatchIndex()}setup(){uh((()=>this.focusInput())),ph((()=>this.env.dispatch("CLEAR_SEARCH")))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.getters.shouldShowFormulas(),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas?this.state.searchOptions.searchFormulas:this.state.replaceOptions.modifyFormulas,this.env.dispatch("REFRESH_SEARCH")}searchFormulas(){this.env.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas,this.updateSearch()}onSelectPreviousCell(){this.env.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.inDebounce),this.inDebounce=setTimeout((()=>this.updateSearch.call(this)),400)}replace(){this.env.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}replaceAll(){this.env.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}focusInput(){const e=this.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1},replaceOptions:{modifyFormulas:!1}}}}Eh.template=mh,Eh.style=vh;const bh=new Me;bh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:dh}),bh.add("ChartPanel",{title:a("Chart"),Body:Hc}),bh.add("FindAndReplace",{title:a("Find and Replace"),Body:Eh});const Sh=new Me;class Ch extends fa{constructor(e,t,s,o){super(t,s,o),this.getters=e,this.ui=o}drawGrid(e,t){}}Ch.layers=[];class wh{constructor(e,t,s){this.index=0,this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=La.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class yh extends Ch{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ms(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ms(e.row,0,this.getters.getSheet(t).rows.length),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:30;case"AUTOFILL_AUTO":const s=this.getters.getSelectedZone();return s.top===s.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone;switch(this.direction){case 1:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,o,t,e)}break;case 0:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,o,t,e)}break;case 2:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,o,e)}break;case 3:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,o,e)}}if(e){const e=Ks(this.getters.getSelectedZone(),this.autofillZone);this.autofillZone=void 0,this.lastCellSelected={},this.direction=void 0,this.tooltip=void 0,this.dispatch("SET_SELECTION",{zones:[e],anchor:[e.left,e.top],anchorZone:e})}}select(e,t){const s=this.getters.getSelectedZone();if(eo(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case 0:this.saveZone(t,s.top-1,s.left,s.right);break;case 1:this.saveZone(s.bottom+1,t,s.left,s.right);break;case 2:this.saveZone(s.top,s.bottom,e,s.left-1);break;case 3:this.saveZone(s.top,s.bottom,s.right+1,e)}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s-1,o)}if(o===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s+1,o)}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,s,o){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:s,content:a,style:l,border:c,format:h})}getRule(e,t){const s=Ma.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((s=>s.condition(e,t)));return s&&s.generateRule(e,t)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(let t of e){const[e,i]=os(t),n=this.getters.getCell(o,e,i);s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const{sheetId:o,col:n,row:r}=e,a=this.getters.getCellBorder(o,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new wh(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:0},down:{number:t-s.bottom,value:1},left:{number:s.left-e,value:2},right:{number:e-s.right,value:3}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autoFillMerge(e,t,s,o){const i=this.getters.getActiveSheet();if(this.getters.isInMerge(i.id,s,o)&&!this.getters.isInMerge(i.id,e,t)){const e=this.getters.getMerge(i.id,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:i.id,target:[e]})}const n=this.getters.getMerge(i.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:i.id,target:[{top:o,bottom:o+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:o}=e,[i,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=o,s.setLineDash([3]),s.strokeRect(i,n,r,a),s.setLineDash([]))}}yh.layers=[6],yh.getters=["getAutofillTooltip"],yh.modes=["normal"];class Ih extends Ch{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const[o,i]=eo(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||io(Ks(n,t))?[{position:[o,i],zone:n}]:this.sumDimensions(e,Ks(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.findSuitableZoneToSum(o,...this.getters.getMainCell(e,t,s));if(i)return this.getters.expandZone(e,i)}findSuitableZoneToSum(e,t,s){const o=this.getters.getCell(e.id,t,s-1),i=this.getters.getCell(e.id,t-1,s);if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getCellsInZone(e.id,t),i=Es(s,-1,-1),n=i.filter((e=>{var t;return o[e]&&!(null===(t=o[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=bs(i.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===Fe.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(_))}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){const s=new Set;return io(t)?(s.add(1===oo(t).width?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:[s,t],zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},no(s).map((t=>({position:t,zone:{...e,right:t[0],left:t[0]}})))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},no(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,o]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Ih.getters=["getAutomaticSums"],Ih.modes=["normal","headless"];class xh extends Ch{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"PASTE":return this.isPasteAllowed(this.state,e.target,!!e.force);case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}}return 0}handle(e){var t,s;switch(e.type){case"COPY":case"CUT":this.state=this.getClipboardState(e.target,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1;const i=this.state.cells.length,n=this.state.cells[0].length;this.paste(this.state,e.target,o),this.selectPastedZone(n,i,e.target),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!qs(t[0])){for(const[t,s]of no(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(s=this.state)||void 0===s?void 0:s.operation))return;for(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.pasteFromClipboard(e.target,e.text);break;case"ACTIVATE_PAINT_FORMAT":this.state=this.getClipboardState(e.target,"COPY"),this._isPaintingFormat=!0,this.status="visible";break;default:Ue(e)&&(this.status="invisible")}}getClipboardContent(){return this.state&&this.state.cells.length&&this.state.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheet();let o;return o="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let o,i;return"COL"===t?(o={...e,right:s.cols.length-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:s.rows.length-1},i={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[o],paste:[i]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:o}=e,[i,n]=this.getters.getMainCell(t,s,o);if(n===o&&i===s){const e=this.getters.getMerge(t,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:o,row:i}=e;const[n,r]=this.getters.getMainCell(s,o,i);if(n===o&&r===i){const e=this.getters.getMerge(s,o,i);if(!e)return;({sheetId:s,col:o,row:i}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],o=t.length,i=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/i)),c=Math.max(1,Math.floor((n.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*i,bottom:a-1+t*o});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.left))),o=new Set(e.map((e=>e.right))),i=new Set(e.map((e=>e.top))),n=new Set(e.map((e=>e.bottom))),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce(((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(Js(e[o],t))return e[o]=Ks(e[o],t),e;return e[s]=t,e}),[])}(e):[e[e.length-1]],a=r.map((e=>no(e))).flat(),l=[...new Set(a.map((e=>e[0])))].sort(((e,t)=>e-t)),c=[...new Set(a.map((e=>e[1])))].sort(((e,t)=>e-t)),h=[],d=[],u=this.getters.getActiveSheetId();for(let e of c){let t=[];for(let s of l){t.push({cell:this.getters.getCell(u,s,e),border:this.getters.getCellBorder(u,s,e)||void 0,position:{col:s,row:e,sheetId:u}});const o=this.getters.getMerge(u,s,e);o&&o.top===e&&o.left===s&&d.push(o)}h.push(t)}return{cells:h,operation:t,sheetId:u,zones:r,merges:d}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:o,top:i}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,o,i);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:i+e,col:o+t,content:s[e][t],sheetId:a.id});const l={left:o,top:i,right:o+n-1,bottom:i+r-1};this.dispatch("SET_SELECTION",{anchor:[o,i],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const o=this.getters.getActiveSheetId();if(!e)return 20;if(t.length>1&&(e.cells.length>1||e.cells[0].length>1))return 19;if(!s)for(let s of this.getPasteZones(t,e.cells))if(this.getters.doesIntersectMerge(o,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,t,i,s);else{const o=e.cells.length,i=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/i)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/o));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*i,n.top+r*o,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const o=s[0],i=o.left,n=o.top,r=Math.max(1,Math.floor((o.right+1-o.left)/e)),a=Math.max(1,Math.floor((o.bottom+1-o.top)/t));if(t>1||e>1){const s={left:i,top:n,right:i+r*e-1,bottom:n+a*t-1},[o,l]=this.getters.getSelection().anchor,c=ms(o,i,i+r*e-1),h=ms(l,n,n+a*t-1);this.dispatch("SET_SELECTION",{anchor:[c,h],zones:[s],anchorZone:s})}}clearClippedZones(e){for(const t of e.cells)for(const e of t)e.cell&&this.dispatch("CLEAR_CELL",e.position);this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o){const i=e.cells.length,n=e.cells[0].length,r="onlyValue"!==o&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,i,t,s);for(let l=0;l<i;l++){const i=e.cells[l];for(let c=0;c<n;c++){const n=i[c],h={col:t+c,row:s+l,sheetId:a.id};this.removeMergeIfTopLeft(h),this.pasteMergeIfExist(n.position,h),this.pasteCell(n,h,e.operation,e.zones,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,o,i){const{cols:n,rows:r,id:a}=e,l=s+i-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+o-n.length;c>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n.length-1,sheetId:a,quantity:c,position:"after"})}pasteCell(e,t,s,o,i){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==i&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===i)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===i){const s=qr(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:s})}let l=e.cell.content;if(e.cell.isFormula()){const t=r-e.position.col,i=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,i,o,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===i?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,o,i,n){if("CUT"===n){const n=[];for(const r of t.dependencies)this.isZoneOverlapClippedZone(i,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,o,e)):n.push(r);return this.getters.buildFormulaContent(e,t,n)}const r=this.getters.createAdaptedRanges(t.dependencies,s,o,e);return this.getters.buildFormulaContent(e,t,r)}isZoneOverlapClippedZone(e,t){return e.some((e=>Js(t,e)))}isColRowDirtyingClipboard(e,t){if(!this.state||!this.state.zones)return!1;for(let s of this.state.zones){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e;if("visible"===this.status&&this.state&&this.state.zones&&this.state.zones.length&&this.state.sheetId===this.getters.getActiveSheetId()){s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*o;for(const e of this.state.zones){const[o,i,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(o,i,n,r)}}}}xh.layers=[2],xh.getters=["getClipboardContent","isPaintingFormat"],xh.modes=["normal"];const Th=[{name:a("Sum"),types:[Fe.number],compute:e=>Bt.compute([e])},{name:a("Avg"),types:[Fe.number],compute:e=>go.compute([e])},{name:a("Min"),types:[Fe.number],compute:e=>_o.compute([e])},{name:a("Max"),types:[Fe.number],compute:e=>Ro.compute([e])},{name:a("Count"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>wo.compute([e])},{name:a("Count Numbers"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>Co.compute([e])}];var Rh;!function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Rh||(Rh={}));class Lh extends Ch{constructor(e,t,s,o){super(e,t,s,o),this.selection={zones:[{top:0,left:0,bottom:0,right:0}],anchor:[0,0],anchorZone:{top:0,left:0,bottom:0,right:0}},this.selectedFigureId=null,this.activeCol=0,this.activeRow=0,this.mode=Rh.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=o.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Qs(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:o,bottom:i}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=zs(n,"cols",Es(t,s+1)),a=zs(n,"rows",Es(o,i+1));if(0!==e.delta[0]&&void 0===a||0!==e.delta[1]&&void 0===r)return 17}break;case"MOVE_POSITION":{const{cols:t,rows:s}=this.getters.getActiveSheet();if(0!==e.deltaX&&s[this.activeRow].isHidden||0!==e.deltaY&&t[this.activeCol].isHidden)return 17;const{col:o,row:i}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(i<0||i>s.length-1||o<0||o>t.length-1)return 17;break}case"SELECT_COLUMN":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().cols.length)return 17;break}case"SELECT_ROW":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().rows.length)return 17;break}case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 23}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":case"CREATE_FIGURE":case"CREATE_CHART":case"UPDATE_FIGURE":case"EVALUATE_CELLS":case"DISABLE_SELECTION_INPUT":case"ENABLE_NEW_SELECTION_INPUT":case"RESIZE_VIEWPORT":break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;default:this.selectedFigureId=null}switch(e.type){case"START":const t=Hs(this.getters.getSheets()[0],0,0);this.activeCol=t[0],this.activeRow=t[1],this.dispatch("ACTIVATE_SHEET",{sheetIdTo:this.getters.getSheets()[0].id,sheetIdFrom:this.getters.getSheets()[0].id}),this.selectCell(...t);break;case"ACTIVATE_SHEET":this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={selection:JSON.parse(JSON.stringify(this.selection)),activeCol:this.activeCol,activeRow:this.activeRow},e.sheetIdTo in this.sheetsData?Object.assign(this,this.sheetsData[e.sheetIdTo]):this.selectCell(...Hs(this.getters.getSheet(e.sheetIdTo),0,0));break;case"SET_SELECTION":this.setSelection(e.anchor,e.zones,e.anchorZone,e.strict);break;case"START_SELECTION":this.mode=Rh.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Rh.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Rh.expanding;break;case"STOP_SELECTION":this.mode=Rh.idle;break;case"MOVE_POSITION":this.movePosition(e.deltaX,e.deltaY);break;case"SELECT_CELL":this.selectCell(e.col,e.row);break;case"SELECT_COLUMN":this.selectColumn(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ROW":this.selectRow(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ALL":this.selectAll();break;case"ALTER_SELECTION":e.delta&&this.moveSelection(e.delta[0],e.delta[1]),e.cell&&this.addCellToSelection(...e.cell);break;case"UNDO":case"REDO":case"DELETE_SHEET":if(!this.getters.tryGetSheet(this.getActiveSheetId())){const e=this.getters.getVisibleSheets();this.activeSheet=this.getters.getSheet(e[0]),this.selectCell(0,0)}this.ensureSelectionValidity();break;case"REMOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&("COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e));break;case"ADD_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onAddElements(e);break;case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"UPDATE_CHART":case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left")}}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getMainCell(e,this.activeCol,this.activeRow);return this.getters.getCell(e,t,s)}getActiveCols(){const e=new Set;for(let t of this.selection.zones)if(0===t.top&&t.bottom===this.getters.getActiveSheet().rows.length-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set;for(let t of this.selection.zones)if(0===t.left&&t.right===this.getters.getActiveSheet().cols.length-1)for(let s=t.top;s<=t.bottom;s++)e.add(s);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return this.selection.zones}getSelectedZone(){return this.selection.anchorZone}getSelection(){return this.selection}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return[this.activeCol,this.activeRow]}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?[t.activeCol,t.activeRow]:Hs(this.getters.getSheet(e),0,0)}}getStatisticFnResults(){const e=new Set(this.selection.zones.map((e=>this.getters.getCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>void 0!==e)));let t=new Set,s=[];for(let o of e)t.add(o.evaluated.type),s.push(o.evaluated.value);let o={};for(let e of Th){let i;e.types.some((e=>t.has(e)))&&(i=e.compute(s)),o[e.name]=i}return o}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Qs(t,e)))}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{offsetX:o,offsetY:i}=this.getters.getActiveSnappedViewport(),{width:n,height:r}=this.getters.getViewportDimensionWithHeaders();for(let e of s)e.x>=o+n||e.x+e.width<=o||e.y>=i+r||e.y+e.height<=i||t.push(e);return t}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},((t,s)=>e[o]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const o=this.getters.getActiveSheet().rows.length-1;let i={left:e,right:e,top:0,bottom:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().rows.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Ks(i,{left:e,right:e,top:l,bottom:o}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectRow(e,t,s){const o=this.getters.getActiveSheet().cols.length-1;let i={top:e,bottom:e,left:0,right:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().cols.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Ks(i,{left:l,right:o,top:t,bottom:t}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectAll(){const e={left:0,top:0,bottom:this.getters.getActiveSheet().rows.length-1,right:this.getters.getActiveSheet().cols.length-1};this.dispatch("SET_SELECTION",{zones:[e],anchor:[0,0],anchorZone:e})}selectCell(e,t){const s=this.getters.getActiveSheet();this.moveClient({sheetId:s.id,col:e,row:t});const o=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});let i;i=this.mode===Rh.expanding?ao([...this.selection.zones,o]):[o],this.selection=this.clipSelection(s.id,{anchor:[e,t],zones:i,anchorZone:o}),this.activeCol=this.selection.anchor[0],this.activeRow=this.selection.anchor[1]}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}getNextAvailablePosition(e,t){return{col:this.getNextAvailableCol(e,this.activeCol,this.activeRow),row:this.getNextAvailableRow(t,this.activeCol,this.activeRow)}}getNextAvailableCol(e,t,s){const{cols:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,t,n,(e=>this.getters.isInSameMerge(i,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,s,n,(e=>this.getters.isInSameMerge(i,t,s,t,e)))}getNextAvailableHeader(e,t,s,o,i){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=o;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;i(d);)d+=e;for(;null===(n=t[d])||void 0===n?void 0:n.isHidden;)d+=e}else if(null===(r=t[d])||void 0===r?void 0:r.isHidden)for(;null===(a=t[d])||void 0===a?void 0:a.isHidden;)d+=e;return d<0||d>t.length-1?t[s].isHidden?this.getNextAvailableHeader(-e,t,s,o,i):s:d}movePosition(e,t){const{col:s,row:o}=this.getNextAvailablePosition(e,t);this.selectCell(s,o)}setSelection(e,t,s,o=!1){this.selectCell(...e);const i=this.getters.getActiveSheetId();let n;t=ao(t),n=o?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(i,e))),anchorZone:this.getters.expandZone(i,s)},this.selection=this.clipSelection(i,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:o,top:i,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&zs(e,"cols",Es(s,o+1))||r,row:e.rows[a].isHidden&&zs(e,"rows",Es(i,n+1))||a}}moveSelection(e,t){const s=this.selection;let o=[];const[i,n]=s.anchor,{left:r,right:a,top:l,bottom:c}=s.anchorZone;let h=s.anchorZone;const d=this.getters.getActiveSheet(),u=e=>{const{left:t,right:s,top:o,bottom:i}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,o),bottom:Math.min(d.rows.length-1,i)}},{col:p,row:g}=this.getReferencePosition();let f=0;for(;null!==h;){if(f++,e<0){const t=this.getNextAvailableCol(e,a-(f-1),g);h=p<=a-f?u({top:l,left:r,bottom:c,right:t}):null}if(e>0){const t=this.getNextAvailableCol(e,r+(f-1),g);h=r+f<=p?u({top:l,left:t,bottom:c,right:a}):null}if(t<0){const e=this.getNextAvailableRow(t,p,c-(f-1));h=g<=c-f?u({top:l,left:r,bottom:e,right:a}):null}if(t>0){const e=this.getNextAvailableRow(t,p,l+(f-1));h=l+f<=g?u({top:e,left:r,bottom:c,right:a}):null}if(h=h?lo(h):h,h&&!Qs(h,s.anchorZone))return o=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h})}h=u(Ks({top:n,bottom:n,left:i,right:i},lo({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Qs(h,s.anchorZone)||(o=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[o,i]=s.anchor,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[o,i],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:o}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:o},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),o=s.cols.length-1,i=s.rows.length-1,n=t.zones.map((e=>({left:ms(e.left,0,o),right:ms(e.right,0,o),top:ms(e.top,0,i),bottom:ms(e.bottom,0,i)})));return{anchor:[ms(t.anchor[0],0,o),ms(t.anchor[1],0,i)],zones:n,anchorZone:{left:ms(t.anchorZone.left,0,o),right:ms(t.anchorZone.right,0,o),top:ms(t.anchorZone.top,0,i),bottom:ms(t.anchorZone.bottom,0,i)}}}onColumnsRemoved(e){const t=Ys(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Ys(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=Xs(this.getSelectedZone(),"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.setSelection([t.left,t.top],[t],t,!0)}updateSelectionZones(e){let t=[...this.selection.zones];const s=this.selection.anchorZone,o=t.findIndex((e=>Qs(e,s)));return o>=0&&(t[o]=e),t}activateNextSheet(e){const t=this.getters.getSheets().map((e=>e.id)),s=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const s="COL"===e.dimension,o=e.elements[0],i=e.elements[t-1],n=e.base<o,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?o+r:0,right:s?i+r:l.cols.length-1,top:s?0:o+a,bottom:s?l.rows.length-1:i+a}]}),this.dispatch("PASTE",{target:[{left:s?e.base:0,right:s?e.base+t-1:l.cols.length-1,top:s?0:e.base,bottom:s?l.rows.length-1:e.base+t-1}]});const c=n?e.elements.map((e=>e+t)):e.elements;let h=e.base;for(const t of c){const s="COL"===e.dimension?this.getters.getCol(e.sheetId,t).size:this.getters.getRow(e.sheetId,t).size;this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:s,elements:[h]}),h+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*o,s.globalCompositeOperation="multiply";for(const e of i){const[o,i,n,r]=this.getters.getRect(e,t);s.fillRect(o,i,n,r),s.strokeRect(o,i,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*o,c=this.getters.isInMerge(r,a,l)?this.getters.getMerge(r,a,l):{top:l,bottom:l,left:a,right:a};const[h,d,u,g]=this.getters.getRect(c,t);u>0&&g>0&&s.strokeRect(h,d,u,g)}}Lh.layers=[5],Lh.modes=["normal"],Lh.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const Mh=a("The cell you are trying to edit has been deleted.");class Ah extends Ch{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheet="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.multiSelectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),s=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(s.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection);break;case"STOP_EDITION":e.cancel?(this.cancelEdition(),this.resetContent()):this.stopEdition();break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0);break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEdition(),this.resetContent();break;case"SELECT_CELL":case"SET_SELECTION":case"MOVE_POSITION":switch(this.mode){case"editing":this.dispatch("STOP_EDITION");break;case"waitingForRangeSelection":this.insertSelectedRange();break;case"rangeSelected":switch(e.type){case"MOVE_POSITION":this.replaceAllSelectedRanges();break;case"SELECT_CELL":this.getters.getSelectionMode()===Rh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Rh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges():this.replaceSelectedRange()}}break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((t=>{let s=t.value;const{xc:o,sheetName:i}=ts(s),n=i||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Qs(this.getters.expandZone(r,Ws(o)),e.zone)&&this.getters.getSheetName(r)===n}));this.previousRef=t.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=t.start;break;case"CHANGE_HIGHLIGHT":const s=this.getZoneReference(e.zone,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheet)||"inactive"===this.mode||(this.cancelEdition(),this.resetContent(),this.ui.notifyUI({type:"NOTIFICATION",text:Mh}))}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheet}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"waitingForRangeSelection"===this.mode||"rangeSelected"===this.mode||"resettingPosition"===this.mode}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((s=>s.start<=e&&s.end>=t))}validateSelection(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e?0:31}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Mh});const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",e.elements);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Mh});const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",e.elements);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Xs({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}startComposerRangeSelection(){this.mode="resettingPosition",this.sheet===this.getters.getActiveSheetId()&&this.dispatch("SELECT_CELL",{col:this.col,row:this.row}),this.mode="waitingForRangeSelection",this.multiSelectionInitialStart=this.selectionStart}startEdition(e,t){const s=this.getters.getActiveCell();this.initialContent=(null==s?void 0:s.composerContent)||"",this.mode="editing";const[o,i]=this.getters.getPosition();this.col=o,this.row=i,this.sheet=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={}}stopEdition(){if("inactive"!==this.mode){this.cancelEdition();const e=this.getters.getActiveSheetId(),t=this.getters.getSheets().find((e=>e.id===this.sheet)).id,[s,o]=this.getters.getMainCell(t,this.col,this.row);let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const t=this.getters.getCell(e,s,o);if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,s=e-t;s>0&&(i+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(i=Ts(i,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:o,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:o});e!==this.sheet&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheet}),this.setContent("")}}cancelEdition(){this.mode="inactive"}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){e=e.replace(/[\r\n]/g,"");const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Gr(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUI({type:"NOTIFICATION",text:a("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=this.getZoneReference(this.getters.getSelectedZone());if("waitingForRangeSelection"===this.mode)return this.insertText(t,e),this.selectionInitialStart=e,void(this.mode="rangeSelected");this.insertText(","+t,e),this.selectionInitialStart=e+1}replaceSelectedRange(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.selectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone()))}replaceAllSelectedRanges(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.multiSelectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone())),this.selectionInitialStart=this.multiSelectionInitialStart}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const s=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${fs(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(s,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:o,end:o}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"REFERENCE"===e.type))){let o=s.value;const{xc:i,sheetName:n}=ts(o);if(es.test(i)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+i.replace(/\$/g,"");e.push(s);const o=this.colorIndexByRange[s];void 0!==o&&(t[s]=o)}}this.colorIndexByRange=t;let s=Object.values(t),o=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(o);)o++;s.push(o),this.colorIndexByRange[e]=o}return[e,jt[this.colorIndexByRange[e]%jt.length]]}))}canStartComposerRangeSelection(){if("editing"!==this.mode&&this.selectionStart===this.selectionEnd)return!1;if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(e){const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let s=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}s++,o=this.currentTokens[s]}return!0}return!1}}Ah.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],Ah.modes=["normal"];const _h=cr.mapping;class Oh extends Ch{constructor(e,t,s,o){super(e,t,s,o),this.isUpToDate=new Set,this.evalContext=o.evalContext,o.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch($e.has(e.type)&&this.isUpToDate.clear(),e.type){case"UPDATE_CELL":"content"in e&&this.isUpToDate.clear();break;case"ACTIVATE_SHEET":this.evaluate(e.sheetIdTo),this.isUpToDate.add(e.sheetIdTo);break;case"EVALUATE_CELLS":this.evaluate(e.sheetId),this.isUpToDate.add(e.sheetId);break;case"EVALUATE_ALL_SHEETS":this.evaluateAllSheets()}}finalize(){const e=this.getters.getActiveSheetId();this.isUpToDate.has(e)||(this.evaluate(e),this.isUpToDate.add(e))}evaluateFormula(e,t=this.getters.getActiveSheetId()){const s=Zr(e),o=this.getFormulaParameters((()=>{})),i=[];for(let e of s.dependencies)i.push(this.getters.getRangeFromSheetXC(t,e));return s.execute(i,t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(i),o={};for(let s of Object.values(t))i(s,e);function i(e,t){if(!e.isFormula())return;const i=e.id;if(i in o)null===o[i]&&e.assignError("#CYCLE",a("Circular reference"));else{o[i]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(i);return is(e.col,e.row)},e.assignValue(e.compiledFormula.execute(e.dependencies,t,...s)),Array.isArray(e.evaluated.value))throw new Error(a("This formula depends on invalid values"))}catch(t){!function(e,t){if(e instanceof Error||(e=new Error(e)),"#CYCLE"!==t.evaluated.value){t.assignValue("#ERROR");const o=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",o))}}(t,e)}o[i]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(_h),this.evalContext,{getters:this.getters}),s=this.getters;function o(t,s){if(e(t,s),t.evaluated.type===Fe.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function i(e){const i=e.sheetId;if(!qs(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:s.getNumberRows(i)-1,left:0,right:s.getNumberCols(i)-1},r=[],l=function(e,t){if(Js(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}(e.zone,n);if(!l)return r.push([]),r;for(let s=l.left;s<=l.right;s++){const i=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);i.push(r?o(r,e.sheetId):void 0)}r.push(i)}return r}return[function(e,i,n,r,l,c){const h=i[e];if(r)return t.getters.getRangeString(h,n);if(!qs(h.zone))throw new Error(a("Invalid reference"));if(h.zone.bottom!==h.zone.top||h.zone.left!==h.zone.right)throw new Error(c?a("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",l.toString(),c.toString()):a("Function %s expects its parameters to be single values or single cell references, not ranges.",l.toString()));if(h.invalidSheetName)throw new Error(a("Invalid sheet name: %s",h.invalidSheetName));return function(e){let t;if(!s.tryGetSheet(e.sheetId))throw new Error(a("Invalid sheet name"));return t=s.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?null:o(t,e.sheetId)}(h)},function(e,t,s){return i(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Oh.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Oh.modes=["normal"];const Nh=["rgb(31,119,180)","rgb(255,127,14)","rgb(174,199,232)","rgb(255,187,120)","rgb(44,160,44)","rgb(152,223,138)","rgb(214,39,40)","rgb(255,152,150)","rgb(148,103,189)","rgb(197,176,213)","rgb(140,86,75)","rgb(196,156,148)","rgb(227,119,194)","rgb(247,182,210)","rgb(127,127,127)","rgb(199,199,199)","rgb(188,189,34)","rgb(219,219,141)","rgb(23,190,207)","rgb(158,218,229)"];class kh{constructor(){this.graphColorIndex=0}next(){return Nh[this.graphColorIndex++%Nh.length]}}class Fh extends Ch{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if($e.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&"content"in e)for(let e of Object.keys(this.chartRuntime))this.outOfDate.add(e);switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":const t=this.getters.getChartDefinition(e.id);this.chartRuntime[e.id]=this.mapDefinitionToRuntime(t);break;case"DELETE_FIGURE":delete this.chartRuntime[e.id];break;case"REFRESH_CHART":this.evaluateUsedSheets([e.id]),this.outOfDate.add(e.id);break;case"ACTIVATE_SHEET":const s=this.getters.getChartsIdBySheet(e.sheetIdTo);this.evaluateUsedSheets(s);break;case"DELETE_SHEET":for(let e of Object.keys(this.chartRuntime))this.getters.getChartDefinition(e)||delete this.chartRuntime[e]}}getChartRuntime(e){if(this.outOfDate.has(e)||!(e in this.chartRuntime)){const t=this.getters.getChartDefinition(e);if(void 0===t)return;this.chartRuntime[e]=this.mapDefinitionToRuntime(t),this.outOfDate.delete(e)}return this.chartRuntime[e]}truncateLabel(e){return e?e.length>20?e.substring(0,20)+"…":e:""}getDefaultConfiguration(e,t){const s={};e.labelRange||1!==e.dataSets.length?s.position=e.legendPosition:s.display=!1;const o={type:e.type,options:{legend:s,responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:e.title}},data:{labels:t.map(this.truncateLabel),datasets:[]}};return"pie"!==e.type?(o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0)):o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}getSheetIdsUsedInChart(e){const t=new Set;for(let s of e.dataSets)t.add(s.dataRange.sheetId);return e.labelRange&&t.add(e.labelRange.sheetId),t}evaluateUsedSheets(e){const t=new Set;for(let s of e){const e=this.getters.getChartDefinition(s);(void 0!==e?this.getSheetIdsUsedInChart(e):[]).forEach((e=>{e!==this.getters.getActiveSheetId()&&t.add(e)}))}for(let e of t)this.dispatch("EVALUATE_CELLS",{sheetId:e})}mapDefinitionToRuntime(e){let t=[];if(e.labelRange)e.labelRange.invalidXc||e.labelRange.invalidSheetName||(t=this.getters.getRangeFormattedValues(e.labelRange));else if(1===e.dataSets.length)for(let s=0;s<this.getData(e.dataSets[0],e.sheetId).length;s++)t.push("");else if(e.dataSets[0]){t=Es(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),o=new kh,i=[];if("pie"===e.type){const t=Math.max(...e.dataSets.map((t=>this.getData(t,e.sheetId).length)));for(let e=0;e<=t;e++)i.push(o.next())}for(const[t,n]of Object.entries(e.dataSets)){let r;if(n.labelCell){const e=n.labelCell,s=e?this.getters.getCell(e.sheetId,e.zone.left,e.zone.top):void 0;r=s&&e?this.truncateLabel(s.formattedValue):r=`${Sc.Series} ${parseInt(t)+1}`}else r=r=`${Sc.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?o.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=i),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[js(e.labelCell.zone)]:[],s=to([js(e.dataRange.zone)],t)[0];if(void 0===s)return[];const o=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(o)}return[]}}Fh.getters=["getChartRuntime"],Fh.modes=["normal"];class $h extends Ch{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===Fe.error)return!1;const s=t.values.map(jr);switch(t.operator){case"IsEmpty":return!_s(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return _s(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(_s(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(_s(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return _s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(_s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return _s(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!_s(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return _s(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return _s(e)&&e.evaluated.value>=s[0];case"LessThan":return _s(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return _s(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!_s(e)&&""===s[0])&&(_s(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||_s(e)&&e.evaluated.value===s[0];default:console.warn(a("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch(e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const s=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of o)this.adaptRules(s,t,[is(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation);break;case"DUPLICATE_SHEET":case"CREATE_SHEET":case"DELETE_SHEET":case"ADD_CONDITIONAL_FORMAT":case"REMOVE_CONDITIONAL_FORMAT":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":case"UNDO":case"REDO":case"DELETE_CELL":case"INSERT_CELL":this.isStale=!0}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getConditionalStyle(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedStyles[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const s=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t))try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const n=Ws(i);for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[o.rule.type];let a=this.getters.getCell(t,r,i);n&&n(a,o.rule)&&(s[r]||(s[r]=[]),s[r][i]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[i])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,s){switch(t.type){case"value":return this.getters.evaluateFormula(`=${s}(${e})`);case"number":return Number(t.value);case"percentage":const o=this.getters.evaluateFormula(`=min(${e})`);return o+(this.getters.evaluateFormula(`=max(${e})`)-o)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===o||s>o)return;const i=Ws(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=i.top;e<=i.bottom;e++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getCell(n,l,e);if((null==i?void 0:i.evaluated.type)!==Fe.number)continue;const c=this.computeIcon(i.evaluated.value,o,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyColorScale(e,t){var s;const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===o||null===n||o>=n||i&&(o>=i||i>=n))return;const r=Ws(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&i?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),c.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getCell(a,t,e);if((null==r?void 0:r.evaluated.type)===Fe.number){const a=ms(r.evaluated.value,o,n);let h;h=2===c.length&&i?a<=i?this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(a,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(s=l[t])||void 0===s?void 0:s[e])||{},l[t][e].fillColor="#"+Xt(h)}}}computeColorDiffUnits(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}colorCell(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges),r=r.concat(s);const a=to(r,o);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(Ws),sheetId:e})}pasteCf(e,t,s){const o=is(t.col,t.row);for(let i of this.getters.getConditionalFormats(e.sheetId))for(let n of i.ranges)if(eo(e.col,e.row,Ws(n))){const n=i,r=[];"CUT"===s&&r.push(is(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,n,[o],r):(this.adaptRules(t.sheetId,n,[o],[]),this.adaptRules(e.sheetId,n,[],r))}}}$h.getters=["getConditionalStyle","getConditionalIcon"],$h.modes=["normal"];var Dh;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Dh||(Dh={}));class Ph extends Ch{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Dh.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Dh.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith,e.replaceOptions);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith,e.replaceOptions);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Dh.current)}updateRegex(){let e=ps(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),s=[];if(this.toSearch)for(const e of Object.values(t))if(e&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas&&e.isFormula()?e.content:String(e.evaluated.value))){const t=this.getters.getCellPosition(e.id),o={col:t.col,row:t.row,selected:!1};s.push(o)}return s.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let s;s=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,s=(s%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===s||(this.selectedMatchIndex=s,this.dispatch("SELECT_CELL",{col:t[s].col,row:t[s].row}));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1}}replace(e,t){if(this.replaceOptions=t,null===this.selectedMatchIndex||!this.currentSearchRegex)return;const s=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell(o,s.col,s.row),n=this.toReplace(i,o);if(i&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),o=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:o}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Dh.current)}else this.selectNextCell(Dh.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let o=0;o<s;o++)this.replace(e,t)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.replaceOptions.modifyFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t,viewport:s}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge(o,e.col,e.row),n=i?i.left:e.col,r=i?i.right:e.col,a=i?i.top:e.row,l=i?i.bottom:e.row,[c,h,d,u]=this.getters.getRect({top:a,left:n,right:r,bottom:l},s);d>0&&u>0&&(t.fillStyle="#8B008B33",t.fillRect(c,h,d,u),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(c,h,d,u)))}}}Ph.layers=[3],Ph.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Uh extends Ch{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const o=this.searchNumberFormat(e,t);if(void 0!==o){const i=this.changeDecimalFormat(o,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:i})}}searchNumberFormat(e,t){var s;for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){const o=this.getters.getCell(e,i,t);if((null==o?void 0:o.evaluated.type)===Fe.number&&!(null===(s=o.format)||void 0===s?void 0:s.match(_)))return o.format||this.setDefaultNumberFormat(o.evaluated.value)}}setDefaultNumberFormat(e){const t=e.toString().split(".");return 1===t.length?"0":"0."+Array(t[1].length+1).join("0")}changeDecimalFormat(e,t){const s=Math.sign(t),o=e.split(";");let i=[];for(let e of o){const t=e.indexOf("."),o=e.toUpperCase().indexOf("E");let n;const r=o>-1?e.slice(0,o):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<re?e.slice(0,l+1)+(0===a?".0":"0")+e.slice(l+1):e:a>0?(n=e.slice(0,l)+e.slice(l+1),1===a&&(n=n.slice(0,t)+n.slice(t+1))):n=e:n=e,i.push(n)}return i.join(";")}}Uh.modes=["normal"];class Vh extends Ch{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){if(0===e.length)return[];const t=this.getters.getActiveSheetId(),s=[];for(let[o,i]of e){const{xc:e,sheetName:n}=ts(o),r=n?this.getters.getSheetIdByName(n):t;if(r){let o=Ws(e);const{height:n,width:a}=oo(o);o=n*a==1?this.getters.expandZone(t,Ws(e)):o,s.push({zone:o,color:i,sheet:r})}}return s.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getSheet(e.sheet).rows.length&&e.zone.right<this.getters.getSheet(e.sheet).cols.length))}drawGrid(e){const{ctx:t,viewport:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Qs(t.zone,e.zone)&&t.sheet===i))===t))){const[o,i,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,a-2*n))}}}function Bh(e,t){let s=0,o=e.length-1;for(;s<=o;){const i=Math.floor((s+o)/2),n=e[i];if(t<n.start)o=i-1;else if(t>n.end)s=i+1;else{if(!n.isHidden)return i;s+=1}}return-1}Vh.modes=["normal"],Vh.layers=[1],Vh.getters=["getHighlights"];class Hh extends Ch{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<v)return-1;const o=(s||this.getters.getActiveSheet()).cols;return Bh(o,e-v+o[t].start+1)}getRowIndex(e,t,s){if(e<m)return-1;const o=(s||this.getters.getActiveSheet()).rows;return Bh(o,e-m+o[t].start+1)}getRect(e,t){const{left:s,top:o,right:i,bottom:n}=e,{offsetX:r,offsetY:a}=this.getShiftedViewport(t),{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-r,v),d=l[i].end-r-h,u=Math.max(c[o].start-a,m);return[h,u,d,c[n].end-a-u]}isVisibleInViewport(e,t,s){const{right:o,left:i,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=i&&e<=o}getEdgeScrollCol(e){let t=!1,s=0,o=0;const{width:i}=this.getters.getViewportDimensionWithHeaders(),{width:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<v&&r>0?(t=!0,s=-1,o=ls(v-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}getEdgeScrollRow(e){let t=!1,s=0,o=0;const{height:i}=this.getters.getViewportDimensionWithHeaders(),{height:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,o=ls(m-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(e),this.drawBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e);break;case 7:this.drawHeaders(e)}}drawBackground(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{width:i,height:n}=this.getters.getViewportDimensionWithHeaders(),{cols:r,rows:a,id:l}=this.getters.getActiveSheet();t.fillStyle="white",t.fillRect(0,0,i,n);const{right:c,left:h,top:d,bottom:u,offsetX:p,offsetY:g}=this.getShiftedViewport(o);if(!this.getters.getGridLinesVisibility(l))return;t.lineWidth=2*s,t.strokeStyle="#E2E3E3",t.beginPath();const f=Math.min(n,a[u].end-g);for(let e=h;e<=c;e++){if(r[e].isHidden)continue;const s=r[e].end-p;t.moveTo(s,0),t.lineTo(s,f)}const m=Math.min(i,r[c].end-p);for(let e=d;e<=u;e++){if(a[e].isHidden)continue;const s=a[e].end-g;t.moveTo(0,s),t.lineTo(m,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const o=.1*s;t.strokeStyle="#111";const i=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height),i&&t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:s}=e;for(let e of this.boxes){let t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o([e,o],i,n,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(i,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let o;t.textBaseline="middle";for(let e of this.boxes)if(e.content){const i=e.style||{},n=e.content.align||"left",r=i.italic?"italic ":"",a=i.bold?"bold":T,l=i.fontSize||R,c=hs[l],h=`${r}${a} ${c}px ${L}`;let d;h!==o&&(o=h,t.font=h),t.fillStyle=i.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*y:4):"right"===n?e.x+e.width-4:e.x+e.width/2,t.textAlign=n,e.clipRect&&(t.save(),t.beginPath(),t.rect(...e.clipRect),t.clip()),t.fillText(e.content.text,Math.round(d),Math.round(u)),(i.strikethrough||i.underline)&&("right"===n?d-=e.content.width:"center"===n&&(d-=e.content.width/2),i.strikethrough&&t.fillRect(d,u,e.content.width,2.6*s),i.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.content.width,1.3*s))),e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const s=e.image.image,o=e.image.size,i=(e.height-o)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(s,e.x+y,e.y+i,o,o),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{right:i,left:n,top:r,bottom:a,offsetX:l,offsetY:p}=this.getShiftedViewport(o),{width:g,height:f}=this.getters.getViewportDimensionWithHeaders(),E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${L}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333",t.fillRect(0,0,g,m),t.fillRect(0,0,v,f),t.fillStyle=h;for(let e of E){const s=Math.max(v,b[e.left].start-l),o=Math.max(v,b[e.right].end-l),i=Math.max(m,S[e.top].start-p),n=Math.max(m,S[e.bottom].end-p);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,o-s,m),t.fillStyle=w.has(e.top)?d:h,t.fillRect(0,i,v,n-i)}t.beginPath(),t.moveTo(v,0),t.lineTo(v,f),t.moveTo(0,m),t.lineTo(g,m),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=n;e<=i;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-l,13),t.moveTo(s.end-l,0),t.lineTo(s.end-l,m))}for(let e=r;e<=a;e++){const s=S[e];s.isHidden||(t.fillStyle=w.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-p),t.moveTo(0,s.end-p),t.lineTo(v,s.end-p))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);return o&&!o.isEmpty()||this.getters.isInMerge(s,e,t)}getShiftedViewport(e){return{...e,offsetX:e.offsetX-v,offsetY:e.offsetY-m}}findNextEmptyCol(e,t,s){let o=e;for(;o<t&&!this.hasContent(o+1,s);)o++;return o}findPreviousEmptyCol(e,t,s){let o=e;for(;o>t&&!this.hasContent(o-1,s);)o--;return o}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e);return t&&e.evaluated.type===Fe.number?"center"!==s?"left":s:s||e.defaultAlign}createBoxFromPosition(e,t,s,o,i,n){const{right:r,left:a,offsetX:l,offsetY:c}=this.getShiftedViewport(o),h=this.getters.getCol(e,t),d=this.getters.getRow(e,s),u=this.getters.getCell(e,t,s),p=this.getters.shouldShowFormulas(),g={x:h.start-l,y:d.start-c,width:i,height:n,border:this.getters.getCellBorder(e,t,s)||void 0,style:{...this.getters.getCellStyle(u),...this.getters.getConditionalStyle(t,s)}};if(!u)return g;const f=this.getters.getConditionalIcon(t,s),m=g.style.fontSize||R,v=hs[m],E=f?2*y+v:0;f&&(g.image={type:"icon",size:v,clipIcon:[g.x,g.y,Math.min(E,i),n],image:Xl[f].img});const b=this.getters.getCellText(u,p),S=this.getters.getTextWidth(u),C=E+S,w=this.computeCellAlignment(u,C>i);g.content={text:b,width:S,align:w},u.evaluated.type===Fe.error&&(g.error=u.evaluated.error);const I=C>i||hs[m]>n;if(f)g.clipRect=[g.x+E,g.y,Math.max(0,i-E),n];else if(I){let o,u;switch(this.getters.isInMerge(e,t,s)?(o=this.getters.getMerge(e,t,s).right,u=t):(o=this.findNextEmptyCol(t,r,s),u=this.findPreviousEmptyCol(t,a,s)),w){case"left":{const t=this.getters.getCol(e,o).end-h.start;(t<S||v>d.size)&&(g.clipRect=[h.start-l,d.start-c,t,n]);break}case"right":{const t=this.getters.getCol(e,u),s=h.end+i-h.size-t.start;(s<S||v>d.size)&&(g.clipRect=[t.start-l,d.start-c,s,n]);break}case"center":{const s=this.getters.getCol(e,u),i=this.getters.getCol(e,o).end-s.start;(i<S||u===t||o===t||v>d.size)&&(g.clipRect=[s.start-l,d.start-c,i,n]);break}}}return g}getGridBoxes(e){const t=[],{viewport:s}=e,{right:o,left:i,top:n,bottom:r}=this.getShiftedViewport(s),a=this.getters.getActiveSheetId();for(let e=n;e<=r;e++){const n=this.getters.getRow(a,e);if(!n.isHidden)for(let r=i;r<=o;r++){const o=this.getters.getCol(a,r);o.isHidden||(this.getters.isInMerge(a,r,e)||t.push(this.createBoxFromPosition(a,r,e,s,o.size,n.size)))}}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&Js(e,s)){const o=this.getters.getCol(a,e.right).end-this.getters.getCol(a,e.left).start,i=this.getters.getRow(a,e.bottom).end-this.getters.getRow(a,e.top).start,n=this.createBoxFromPosition(a,e.left,e.top,s,o,i),r=this.getters.getCellBorder(a,e.right,e.bottom);n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}}Hh.layers=[0,7],Hh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],Hh.modes=["normal"];const zh=new Bs;class Zh extends Ch{constructor(){super(...arguments),this.inputs={},this.activeSheets={},this.inputHasSingleRange={},this.focusedInputId=null,this.focusedRange=null,this.willAddNewRange=!1}allowDispatch(e){switch(e.type){case"FOCUS_RANGE":const t=this.getIndex(e.id,e.rangeId);if(this.focusedInputId===e.id&&this.focusedRange===t)return 24;break;case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange[e.id]&&1===this.inputs[e.id].length)return 25}return 0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id],delete this.activeSheets[e.id],delete this.inputHasSingleRange[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(e.id,this.getIndex(e.id,e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.id,e.rangeId);if(null!==t){const s=e.id;this.focusedInputId===s&&this.focusedRange===t||this.dispatch("FOCUS_RANGE",{id:s,rangeId:this.inputs[s][t].id});const o=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(e.id,this.inputs[e.id].length,[""]),this.focusLast(e.id);break;case"REMOVE_RANGE":const t=this.getIndex(e.id,e.rangeId);null!==t&&this.removeRange(e.id,t);break;case"SELECT_CELL":case"SET_SELECTION":if(!this.focusedInputId)break;const s=this.getSelectionInputValue(this.focusedInputId),o=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(js).filter((e=>!s.includes(e))),i=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(o.map((e=>n===i?e:`${fs(r)}!${e}`)));break;case"PREPARE_SELECTION_EXPANSION":{const[e,t]=[this.focusedInputId,this.focusedRange];null===e||null===t||this.inputHasSingleRange[e]||(this.willAddNewRange=""!==this.inputs[e][t].xc.trim());break}}}getSelectionInput(e){return this.inputs[e]?this.inputs[e].map(((t,s)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.focusedRange&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.focusedRange===s}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=ts(e);return null!==t.match(es)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getSelectionInputValue(e){return this.cleanInputs(this.inputs[e].map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].map((e=>this.inputToHighlights(this.focusedInputId,e))).flat():[]}initInput(e,t,s=!1){this.inputs[e]=[],this.insertNewRange(e,0,t),this.activeSheets[e]=this.getters.getActiveSheetId(),this.inputHasSingleRange[e]=s,0===this.inputs[e].length&&this.dispatch("ADD_EMPTY_RANGE",{id:e})}focus(e,t){this.focusedInputId=e,this.focusedRange=t}focusLast(e){this.focus(e,this.inputs[e].length-1)}unfocus(){this.focusedInputId=null,this.focusedRange=null}add(e){if(null===this.focusedInputId||null===this.focusedRange||this.getters.isSelectingForComposer()||0===e.length)return;if(this.getters.getSelectionMode()===Rh.expanding&&this.willAddNewRange){const t=this.focusedInputId;this.insertNewRange(t,this.inputs[t].length,e),this.focusLast(this.focusedInputId),this.willAddNewRange=!1}else this.setRange(this.focusedInputId,this.focusedRange,e)}setContent(e,t,s){this.inputs[e][t]={...this.inputs[e][t],id:zh.uuidv4(),xc:s}}insertNewRange(e,t,s){this.inputs[e].splice(t,0,...s.map(((t,s)=>({xc:t,id:(this.inputs[e].length+s+1).toString(),color:Kt()}))))}setRange(e,t,s){const[,...o]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,o),o.length&&this.focus(e,t+o.length)}removeRange(e,t){this.inputs[e].splice(t,1),this.focusedInputId===e&&null!==this.focusedRange&&this.focusLast(e)}inputToHighlights(e,{xc:t,color:s}){const o=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===o.length)return[];const[i,...n]=o,r=[[i,s||Kt()]];for(const e of n)r.push([e,Kt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=ts(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Zh.modes=["normal"],Zh.layers=[1],Zh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Gh{constructor(){this.bus=new o.core.EventBus}on(e,t,s){this.bus.on(e,t,s)}trigger(e,t){this.bus.trigger(e,t)}off(e,t){this.bus.off(e,t)}clear(){this.bus.clear()}}function Wh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<=r&&e[o]>=r&&n--;if(!(i>n))return{...e,[t]:i,[o]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom",l="before"===o?e[a]>r:e[a]>=r;return e[t]<=r&&l?ro(e,n,"RESIZE",i):r<e[t]?ro(e,n,"MOVE",i):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function qh(e,t){const s=e.definition;let o,i;return s.labelRange&&(o=Wh(Ws(s.labelRange),t)),s.dataSets&&(i=s.dataSets.map(Ws).map((e=>Wh(e,t))).filter(_s).map(js)),{...e,definition:{...s,dataSets:i,labelRange:o?js(o):void 0}}}Cl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qh),Cl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qh),Cl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Cl.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var s;if(e.name===t.name)return{...e,name:(null===(s=e.name)||void 0===s?void 0:s.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Cl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)for(const e of t.target)Js(o,e)||s.push({...o});if(s.length)return{...e,target:s};return}));const jh=[{match:function(e){return"sheetId"in e},fn:function(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if(e.sheetId===s)return"IGNORE_COMMAND";if("CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId)return e;return"SKIP_TRANSFORMATION"}},{match:function(e){return"target"in e},fn:function(e,t){const s=[];for(const o of e.target){const e=Wh(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"col"in e&&"row"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&eo(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const s="ADD_COLUMNS_ROWS"===e.type,o=s?"base":"elements";let i=s?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(i=i.map((e=>{if(t.elements.includes(e))return;const s=t.elements.sort(((e,t)=>t-e));for(let t of s)e>t&&e--;return e})).filter(_s)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;i=i.map((s=>s>e?s+t.quantity:s))}if(i.length){let t=i;return s&&(t=i[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Xh(e,t){const s=Cl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:o}of jh)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Yh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Xh(t,e))).filter(_s);return s}class Kh{constructor(e,t,s,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Qh extends Error{}class Jh extends Gh{constructor(e,t,s=N){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Bs,this.debouncedMove=o.utils.debounce(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const s=new Kh(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(s.id,s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Qh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(_s))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const s=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==s?void 0:s.col)===e.col&&s.row===e.row&&s.sheetId===e.sheetId)return;const o=s?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{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":const{clientId:t,commands:s}=e,o=new Kh(e.nextRevisionId,t,s);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Yh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Kh(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");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;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({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.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const ed=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class td extends Ch{constructor(){super(...arguments),this.availableColors=new Set(ed),this.colors={}}isPositionValid(e){const t=this.getters.getSheet(e.sheetId);return e.row<t.rows.length&&e.col<t.cols.length}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(ed));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof Qh)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())if(s.id!==this.getters.getClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)){const e=s.position;this.colors[s.id]||(this.colors[s.id]=this.chooseNewColor());const o=this.colors[s.id];t.push({...s,position:e,color:o})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),[l,c,h,d]=this.getters.getRect(a,t);if(h<=0||d<=0)continue;const u=e.color,p=`${u}10`;s.fillStyle=p,s.lineWidth=4*o,s.strokeStyle=u,s.globalCompositeOperation="multiply",s.fillRect(l,c,h,d),s.globalCompositeOperation="source-over",s.strokeRect(l,c,h,d),s.font=`bold ${R+1}px ${L}`}}}td.getters=["getClientsToDisplay"],td.layers=[5],td.modes=["normal"];class sd extends Ch{allowDispatch(e){if("SORT_CELLS"===e.type){if(!eo(e.col,e.row,e.zone))throw new Error(a("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection)}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let s=t.top;s<=t.bottom;s++)for(let o=t.left;o<=t.right;o++)if(!this.getters.isInMerge(e,o,s))return 48;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const s=this.getters.getMerges(e).filter((e=>Js(e,t))),o=oo(s[0]);let[i,n]=[o.width,o.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n}))?0:48}expand(e,t){const{left:s,right:o,top:i,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,o),top:Math.max(0,i),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),o=e.id;let i,n=[];if(this.getters.doesIntersectMerge(o,s)){const{left:e,right:t,top:r,bottom:a}=s;for(let s=e;s<=t;s++)for(let e=r;e<=a;e++){const[t,r]=this.getters.getMainCell(o,s,e);i=this.getters.getCell(o,t,r),n.push((null==i?void 0:i.formattedValue)||"")}}else n=this.getters.getCellsInZone(o,s).map((e=>(null==e?void 0:e.formattedValue)||""));return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:o,bottom:i,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,o>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o-1,bottom:o-1}),s&&(l=!1,o--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:o-1,bottom:i+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:o-1,bottom:i+1}),s&&(l=!1,r++)),i<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i+1,bottom:i+1}),s&&(l=!1,i++));return{left:n,right:r,top:o,bottom:i}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||Fe.empty))));return t[0][0]===Fe.empty&&(t=t.slice(1)),!t.some((e=>e[0]===Fe.empty))&&!!t.some((e=>e[1]!==Fe.empty&&e[0]!==e[1]))}sortZone(e,t,s,o){const[i,n]=this.mainCellsSteps(e,s);let r=this.getters.getMainCell(e,t.col,t.row)[0],a=Object.assign({},s),l=this.mainCells(e,s);this.hasHeader(l)&&(a.top+=n),l=this.mainCells(e,a);const c=function(e,t){const s=e.map(Da),o=s.filter((e=>e.type===Fe.empty)),i=s.filter((e=>e.type!==Fe.empty)),n="descending"===t?-1:1;return i.sort(((e,t)=>{let s=$a.indexOf(e.type)-$a.indexOf(t.type);return 0===s&&(s=e.type===Fe.text||e.type===Fe.error?e.value.localeCompare(t.value):e.value-t.value),n*s})).concat(o)}(l[r-a.left],o),h=c.map((e=>e.index)),[d,u]=[l.length,l[0].length];for(let t=0;t<d;t++)for(let s=0;s<u;s++){let o=l[t][h[s]],r=a.left+t*i,c=a.top+s*n,d={sheetId:e,col:r,row:c,content:"",value:""};if(o){let t=o.content;if(o.isFormula()){const s=c-this.getters.getCellPosition(o.id).row,i=this.getters.createAdaptedRanges(o.dependencies,0,s,e);t=this.getters.buildFormulaContent(e,o,i)}d.style=o.style,d.content=t,d.format=o.format,d.value=o.evaluated.value}this.dispatch("UPDATE_CELL",d)}}mainCellsSteps(e,t){const s=this.getters.getMerge(e,t.left,t.top);return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=Es(t.left,t.right+1,s),r=Es(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push(this.getters.getCell(e,t,o))}return i}}sd.getters=["getContiguousZone"];class od extends Ch{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}od.modes=["normal"],od.getters=["shouldShowFormulas"];class id extends Ch{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s+6,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows){const s=this.getRowMaxHeight(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:s+6,sheetId:e.sheetId})}}}getCellWidth(e){let t=this.getTextWidth(e);const s=this.getters.getCellPosition(e.id);return this.getters.getConditionalIcon(s.col,s.row)&&(t+=function(e,t){const s=t.fontSize||R;return hs[s]+2*y}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return vs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||R;return hs[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===Fe.error)?e.content:e.formattedValue}getColMaxWidth(e,t){const s=this.getters.getColCells(e,t).map((e=>this.getCellWidth(e)));return Math.max(0,...s)}getRowMaxHeight(e,t){const s=this.getters.getSheet(e),o=Object.values(s.rows[t].cells).filter(_s).map((e=>this.getters.getCellById(e))).map((e=>this.getCellHeight(e)));return Math.max(0,...o)}}id.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class nd extends Ch{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.viewportWidth=1e3,this.viewportHeight=1e3}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkOffsetValidity(e.offsetX,e.offsetY);case"RESIZE_VIEWPORT":return e.width<0||e.height<0?54:0;default:return 0}}handle(e){switch(e.type){case"UNDO":case"REDO":this.cleanViewports(),this.resetViewports();break;case"RESIZE_VIEWPORT":this.cleanViewports(),this.resizeViewport(e.height,e.width);break;case"SET_VIEWPORT_OFFSET":this.setViewportOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getActiveTopRow(),s=this.clipOffsetY(t.start+this.viewportHeight);this.shiftVertically(s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getActiveTopRow(),t=this.clipOffsetY(e.end-this.viewportHeight);this.shiftVertically(t);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportOffsetX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportOffsetY(e.sheetId,this.getViewport(e.sheetId));break;case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportZoneX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportZoneY(e.sheetId,this.getViewport(e.sheetId));break;case"ACTIVATE_SHEET":this.refreshViewport(e.sheetIdTo);break;case"SELECT_CELL":case"MOVE_POSITION":this.refreshViewport(this.getters.getActiveSheetId())}}finalize(){this.updateSnap&&(this.snapViewportToCell(this.getters.getActiveSheetId()),this.updateSnap=!1)}getViewportDimensionWithHeaders(){return{width:this.viewportWidth+v,height:this.viewportHeight+m}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getMaxViewportSize(e){const t=Zs(e,"cols"),s=Zs(e,"rows"),o=e.cols.find((e=>e.end>t.end-this.viewportWidth))||e.cols[e.cols.length-1],i=e.rows.find((e=>e.end>s.end-this.viewportHeight))||e.rows[e.rows.length-1];return{width:t.end+Math.max(b,Math.min(o.size,this.viewportWidth-t.size)),height:s.end+Math.max(S+5,Math.min(i.size,this.viewportHeight-s.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getMaxViewportSize(e);return{maxOffsetX:Math.max(0,t-this.viewportWidth+1),maxOffsetY:Math.max(0,s-this.viewportHeight+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumViewportOffset(s);return e<0||t<0||t>i||e>o?53:0}getSnappedViewport(e){return this.snapViewportToCell(e),this.snappedViewports[e]}getViewport(e){return this.viewports[e]?this.viewports[e]:this.generateViewportState(e)}cleanViewports(){const e=this.getters.getVisibleSheets();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetViewports(){for(let[e,t]of Object.entries(this.viewports))this.adjustViewportOffsetX(e,t),this.adjustViewportOffsetY(e,t),this.adjustViewportsPosition(e)}adjustViewportOffsetX(e,t){const{offsetX:s}=t,{width:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportWidth+s>o){const e=this.viewportWidth+s-o;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportHeight+s>o){const e=this.viewportHeight+s-o;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.viewportHeight=e,this.viewportWidth=t,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.adjustViewportOffsetX(e,this.viewports[e]),this.adjustViewportOffsetY(e,this.viewports[e])}setViewportOffset(e,t){const s=this.getters.getActiveSheetId();this.getActiveViewport(),this.viewports[s].offsetX=e,this.viewports[s].offsetY=t,this.adjustViewportZone(s,this.viewports[s])}clipOffsetY(e){const{height:t}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),s=t-this.viewportHeight;return e=Math.min(e,s),e=Math.max(e,0)}generateViewportState(e){return this.viewports[e]={left:0,right:0,top:0,bottom:0,offsetX:0,offsetY:0},this.viewports[e]}refreshViewport(e){const t=this.getViewport(e);this.adjustViewportZone(e,t),this.adjustViewportsPosition(e)}adjustViewportZone(e,t){this.adjustViewportZoneX(e,t),this.adjustViewportZoneY(e,t)}adjustViewportZoneX(e,t){const s=this.getters.getSheet(e),o=s.cols;t.left=this.getters.getColIndex(t.offsetX+v,0,s);const i=this.viewportWidth+t.offsetX;t.right=o.length-1;for(let e=t.left;e<o.length;e++)if(i<o[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),o=s.rows;t.top=this.getters.getRowIndex(t.offsetY+m,0,s);const i=this.viewportHeight+t.offsetY;t.bottom=o.length-1;for(let e=t.top;e<o.length;e++)if(i<o[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:o,rows:i}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=Hs(s,...this.getters.getMainCell(e,t[0],t[1]));for(;o[r].end>n.offsetX+this.viewportWidth&&n.offsetX<o[r].start;)n.offsetX=o[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=o.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=o[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;i[a].end>n.offsetY+this.viewportHeight&&n.offsetY<i[a].start;)n.offsetY=i[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=i.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=i[n.top-1-t].start,this.adjustViewportZoneY(e,n)}const{top:l,left:c}=this.viewports[e];l===n.top&&c===n.left||(this.viewports[e]=n),this.updateSnap=!1}snapViewportToCell(e){const{cols:t,rows:s}=this.getters.getSheet(e),o=this.getViewport(e),i=Object.assign({},o);this.adjustViewportOffsetX(e,i),this.adjustViewportOffsetY(e,i),i.offsetX=t[i.left].start,i.offsetY=s[i.top].start,this.adjustViewportZone(e,i),this.snappedViewports[e]=i}shiftVertically(e){const{top:t,offsetX:s}=this.getActiveSnappedViewport();this.setViewportOffset(s,e);const{anchor:o}=this.getters.getSelection(),i=this.getActiveSnappedViewport().top-t;this.dispatch("SELECT_CELL",{col:o[0],row:o[1]+i})}getActiveTopRow(){const{top:e}=this.getActiveSnappedViewport(),t=this.getters.getActiveSheet();return this.getters.getRow(t.id,e)}}nd.getters=["getActiveViewport","getActiveSnappedViewport","getViewportDimensionWithHeaders","getMaxViewportSize","getMaximumViewportOffset"],nd.modes=["normal"];const rd=(new Me).add("sheet",Ra).add("cell",ba).add("merge",Ia).add("borders",va).add("conditional formatting",wa).add("figures",ya).add("chart",Sa),ad=(new Me).add("selection",Lh).add("ui_sheet",id).add("ui_options",od).add("evaluation",Oh).add("evaluation_cf",$h).add("evaluation_chart",Fh).add("clipboard",xh).add("edition",Ah).add("highlight",Vh).add("selectionInput",Zh).add("viewport",nd).add("grid renderer",Hh).add("autofill",yh).add("find_and_replace",Ph).add("sort",sd).add("automatic_sum",Ih).add("format",Uh).add("selection_multiuser",td);class ld{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class cd extends o.core.EventBus{constructor(){super(...arguments),this.registry=new Me}add(e,t){this.registry.add(e,t);const s=o.utils.debounce((()=>this.trigger("data-loaded",{id:e})),0);return t.on("data-loaded",this,(()=>s())),t.loadMetadata(),this}get(e){return this.registry.get(e)}getAll(){return this.registry.getAll()}remove(e){this.get(e).off("data-loaded",this),this.registry.remove(e)}async waitForReady(){const e=[];for(const t of this.getAll())e.push(t.get());return Promise.all(e)}}class hd extends o.core.EventBus{async loadMetadata(){this.metadataPromise||(this.metadataPromise=this._fetchMetadata().then((e=>(this.metadata=e,e)))),await this.metadataPromise}async get(e){return e&&e.forceFetch&&(this.data=void 0,this.dataPromise=void 0),await this.loadMetadata(),this.dataPromise||(this.dataPromise=this._fetch(e).then((e=>(this.data=e,this.lastUpdate=Date.now(),this.trigger("data-loaded"),e)))),this.dataPromise}getSync(){return this.data}getMetadataSync(){return this.metadata}getLastUpdate(){return this.lastUpdate}}function dd(e){return _a.get(e.type)(e)}function ud(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class pd{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map((e=>e.transformed(s)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new pd(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class gd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new fd(this.id,ks((()=>e(this.data))))}}class fd{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new fd(this.id,this.lazyData.map(e))}}class md{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new md(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new md(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new md(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class vd{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new md(Ss(this._execution(e),this._execution(e)))}revertedExecution(e){return new md(Ss(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const o=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex((t=>t===e));this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Ed{constructor(e,t,s,o,i){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=o,this.buildTransformation=i,this.HEAD_BRANCH=new pd(this.buildTransformation),this.tree=new vd(i,this.HEAD_BRANCH);const n=new gd(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const s=new gd(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new gd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function bd(e,t,s){return new Ed(e,(e=>{const o=e.commands.slice(),{changes:i}=t((()=>{for(const e of o)s(e)}));e.setChanges(i)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Sd(t.changes[e],"before")}}([e])),(e=>new Kh(e,"empty",[],[])),{with:e=>t=>new Kh(t.id,t.clientId,Yh(t.commands,e.commands)),without:e=>t=>new Kh(t.id,t.clientId,Yh(t.commands,e.commands.map(dd).flat()))})}function Sd(e,t){let s=e.root,o=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===s[o]){const i=e.path[t+1];s[o]=ud(i)}s=s[o]}void 0===e[t]?delete s[o]:s[o]=e[t]}class Cd extends o.core.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(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}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class wd{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return 0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const i=bs(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of i){const i=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=i&&i<=n.zone[s]){const e=Math.min(n.zone[s],l)-i+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=i&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(O);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-i))}else i<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-i+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>t.sheetId!==e.sheetId?{changeType:"NONE"}:{changeType:"REMOVE",range:t={...this.buildInvalidRange(O),invalidSheetName:this.getters.getSheetName(e.sheetId)}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const s={...t,zone:{...t.zone}};return s.invalidSheetName=void 0,s.sheetId=e.sheetId,{changeType:"CHANGE",range:s}}return{changeType:"NONE"}}))}}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||qs(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,o){return{...e,zone:ro(e.zone,t,s,o)}}executeOnAllRanges(e,t){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t)}addRangeProvider(e){this.providers.push(e)}orderZone(e,t){if(e.right<e.left){let s=e.right;e.right=e.left,e.left=s;let o=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=o}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let o=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=o}}createAdaptedRanges(e,t,s,o){return e.map((e=>qs(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:o,zone:{left:e.zone.left+(e.parts[0].colFixed?0:t),right:e.zone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.zone.top+(e.parts[0].rowFixed?0:s),bottom:e.zone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)}},this.orderZone(e.zone,e.parts),e):e))}getRangeFromSheetXC(e,t){let s,o,i,n=t,r=!1;if(!es.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=ts(t)),s?(o=this.getters.getSheetIdByName(s),r=!0,o||(i=s)):i=s);const a=Gs(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:o||e,zone:a,parts:l,invalidSheetName:i,prefixSheet:r}}getRangeString(e,t){if(!e)return O;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return O;if(e.zone.left<0||e.zone.top<0)return O;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,o="";if(s&&(o=e.invalidSheetName?e.invalidSheetName:fs(this.getters.getSheetName(e.sheetId))),s&&!o)return O;let i=Array(9);return i[0]=e.parts&&e.parts[0].colFixed?"$":"",i[1]=ss(e.zone.left),i[2]=e.parts&&e.parts[0].rowFixed?"$":"",i[3]=String(e.zone.top+1),e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i[4]=":",i[5]=e.parts[1].colFixed?"$":"",i[6]=ss(e.zone.right),i[7]=e.parts[1].rowFixed?"$":"",i[8]=String(e.zone.bottom+1)),`${s?o+"!":""}${i.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}wd.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class yd{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop(),[s,...o]=e;let i=s,n=o[o.length-1];for(let e=0;e<=o.length-2;e++){const t=o[e];if(void 0===i[t]){const s=o[e+1];i[t]=ud(s)}i=i[t]}i[n]!==t&&(this.changes.push({root:s,path:o,before:i[n],after:t}),void 0===t?delete i[n]:i[n]=t)}}const Id={General:0,0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},xd={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Td={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"},Rd="http://schemas.openxmlformats.org/drawingml/2006/main",Ld="http://schemas.openxmlformats.org/drawingml/2006/chart",Md={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+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"},Ad="http://schemas.openxmlformats.org/officeDocument/2006/relationships",_d=.75,Od=.1425,Nd=164,kd={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}]},Fd=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","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","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","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","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"];function $d(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Dd(e){return Math.round(_d*e*window.devicePixelRatio*100)/100}function Pd(e){return Math.round(Od*e*100)/100}function Ud(e,t){let s={};e.style&&(s=t.styles[e.style]);const o=e.format?t.formats[e.format]:void 0;let i={};e.border&&(i=t.borders[e.border]);const n={font:{size:(null==s?void 0:s.fontSize)||R,color:(null==s?void 0:s.textColor)?s.textColor:"000000",family:2,name:"Arial"},fill:(null==s?void 0:s.fillColor)?{fgColor:s.fillColor}:{reservedAttribute:"none"},numFmt:o,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return n.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,n.font.underline=!!(null==s?void 0:s.underline)||void 0,n.font.bold=!!(null==s?void 0:s.bold)||void 0,n.font.italic=!!(null==s?void 0:s.italic)||void 0,n}function Vd(e,t){const{id:s}=Hd(t.font,e.fonts),{id:o}=Hd(t.fill,e.fills),{id:i}=Hd(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=Id[e];if(!s){const{id:o}=Hd(e,t);s=o+Nd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:o,borderId:i,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=Hd(r,e.styles);return a}function Bd(e,t,s){let o,i=e.find((e=>e.path===t));return i?(o=`rId${(i.rels.length+1).toString()}`,i.rels.push({...s,id:o})):(o="rId1",e.push({path:t,rels:[{...s,id:o}]})),o}function Hd(e,t){for(let[s,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(s,10),list:t};let s=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===s&&(t.push(e),s=t.length-1),{id:s,list:t}}const zd=[];function Zd(e){const t=zd.findIndex((t=>t===e));return-1===t?(zd.push(e),zd.length):t+1}function Gd(e){return Math.round(914400*e/96)}class Wd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function qd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function jd(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'")}function Xd(e){return new Wd(e.map((([e,t])=>`${e}="${jd(t)}"`)).join(" "))}function Yd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,o=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(o-3,0),Math.min(o+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Kd(e,t){return Jd`
|
|
1049
1049
|
<Override ContentType="${t}" PartName="${e}" />
|
|
1050
1050
|
`}function Qd(e){return new Wd(e.join("\n"))}function Jd(e,...t){let s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof Wd?t[o]:jd(t[o]);s.push(i+e[o+1])}return new Wd(s.join(""))}const eu=17781237,tu=88853993;function su(e){const t=[["xmlns:r",Ad],["xmlns:a",Rd],["xmlns:c",Ld]],s=ou({backgroundColor:Qt(e.data.backgroundColor),line:{color:"000000"}});let o=Jd``;e.data.title&&(o=Jd`
|
|
1051
1051
|
<c:title>
|
|
@@ -1243,7 +1243,7 @@
|
|
|
1243
1243
|
${n}
|
|
1244
1244
|
</f>
|
|
1245
1245
|
${s}
|
|
1246
|
-
`,{attrs:o,node:i}}{const t=e.value
|
|
1246
|
+
`,{attrs:o,node:i}}{const t=e.value,s=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return o.push(["t",s]),i=Jd`<v>${t}</v>`,{attrs:o,node:i}}}function uu(e,t){let s=e;const o=[];if(["TRUE","FALSE"].includes(s.trim()))s="TRUE"===s?"1":"0",o.push(["t","b"]);else if(!ee(s)){const{id:i}=Hd(e,t);s=i.toString(),o.push(["t","s"])}return{attrs:o,node:Jd`<v>${s}</v>`}}function pu(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Or(e)}catch(t){return e}return t=kr(t,"STRING",gu),t=kr(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),s=e.args,o=kd[t];if(o){const i=cr.content[t].args.filter((e=>!e.optional)),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=o[t-n];s.push({type:e.type,value:e.value})}}return{...e,args:s}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:Fd.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?Fr(t):e}function gu(e){const t=e.value.replace(new RegExp('"',"g"),""),s=W(t);if(s){let o=[];return(t.match(z)||t.match(Z))&&o.push("yyyy-mm-dd"),t.match(G)&&o.push("hh:mm:ss"),{...e,value:X({value:s.value,format:o.join(" ")})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function fu(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(mu(o,o.rule,e));break;case"ColorScaleRule":s.push(vu(o,o.rule));break;case"IconSetRule":s.push(Eu(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function mu(e,t,s){const o=bu(e),i=$d(t.operator);o.push(...function(e){const t=$d(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",i]);const n=function(e,t){const s=e[0].split(":")[0],o=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${s})))`];case"NotContains":return[`ISERROR(SEARCH("${o[0]}",${s}))`];case"BeginsWith":return[`LEFT(${s},LEN("${o[0]}"))="${o[0]}"`];case"EndsWith":return[`RIGHT(${s},LEN("${o[0]}"))="${o[0]}"`];case"IsEmpty":return[`LEN(TRIM(${s}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${s}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[o[0]];case"Between":case"NotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>Jd`<formula>${e}</formula>`)),r={font:{color:t.style.textColor,bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:t.style.fillColor});const{id:a}=Hd(r,s);return o.push(["dxfId",a]),Jd`
|
|
1247
1247
|
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
1248
1248
|
<cfRule ${Xd(o)}>
|
|
1249
1249
|
${Qd(n)}
|
|
@@ -3087,4 +3087,4 @@
|
|
|
3087
3087
|
height: ${15}px;
|
|
3088
3088
|
vertical-align: sub;
|
|
3089
3089
|
}
|
|
3090
|
-
`;class Wf extends t.Component{constructor(e,s={}){super(e,s),this.model=new Nu(this.props.data,{evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},Pf({openSidePanel:(e,t={})=>this.openSidePanel(e,t),toggleSidePanel:(e,t={})=>this.toggleSidePanel(e,t),dispatch:this.model.dispatch,getters:this.model.getters,uuidGenerator:this.model.uuidGenerator,_t:Wf._t,clipboard:navigator.clipboard,export:this.model.exportData.bind(this.model),waitForIdle:this.model.waitForIdle.bind(this.model),exportXLSX:this.model.exportXLSX.bind(this.model),openLinkEditor:()=>this.openLinkEditor()}),this.activateFirstSheet()}setup(){Df(window,"resize",this.render),Df(document.body,"keyup",this.onKeyup.bind(this)),Df(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),Uf((()=>this.initiateModelEvents())),Vf((()=>this.leaveCollaborativeSession())),Bf((e=>this.checkReadonly(e)))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}initiateModelEvents(){this.model.on("update",this,this.render),this.model.on("notify-ui",this,this.onNotifyUI),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}onNotifyUI(e){if("NOTIFICATION"===e.type)this.env.notifyUser(e.text)}checkReadonly(e){this.props.isReadonly!==e.isReadonly&&this.model.updateReadOnly(e.isReadonly)}leaveCollaborativeSession(){this.model.off("update",this),this.model.leaveSession()}activateFirstSheet(){const e=this.model.getters.getActiveSheetId(),[t]=this.model.getters.getSheets();t.id!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:t.id})}destroy(){this.model.destroy(),super.destroy()}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}openLinkEditor(){this.linkEditor.isOpen=!0}closeLinkEditor(){this.linkEditor.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Rh.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Rh.idle?"PREPARE_SELECTION_EXPANSION":"START_SELECTION_EXPANSION");let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}}Wf.template=Zf,Wf.style=Gf,Wf.components={TopBar:$f,Grid:wf,BottomBar:ip,SidePanel:Mf,LinkEditor:ef},Wf._t=e=>e;const qf={},jf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:m,HEADER_WIDTH:v,TOPBAR_HEIGHT:E,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:b,DEFAULT_CELL_HEIGHT:S,SCROLLBAR_WIDTH:C},Xf={autofillModifiersRegistry:La,autofillRulesRegistry:Ma,cellMenuRegistry:gl,colMenuRegistry:fl,linkMenuRegistry:ml,functionRegistry:cr,uiPluginRegistry:ad,corePluginRegistry:rd,rowMenuRegistry:vl,sidePanelRegistry:bh,sheetMenuRegistry:bl,topbarMenuRegistry:Sl,topbarComponentRegistry:Sh,otRegistry:Cl,inverseCommandRegistry:_a,cellRegistry:Wr},Yf={LinkCell:ta},Kf={args:Oe,toBoolean:fe,toNumber:de,toString:pe,toXC:is,toZone:Ws,toCartesian:os,numberToLetters:ss,createFullMenuItem:ka,UuidGenerator:Bs,formatDecimal:ae,computeTextWidth:vs,isMarkdownLink:xs,parseMarkdownLink:Rs,markdownLink:Ts,createEmptyWorkbookData:ga};e.CorePlugin=ma,e.DATETIME_FORMAT=_,e.DataSource=hd,e.DispatchResult=Ve,e.Model=Nu,e.Registry=Me,e.Revision=Kh,e.SPREADSHEET_DIMENSIONS=jf,e.Spreadsheet=Wf,e.UIPlugin=Ch,e.__DEBUG__=Os,e.__info__=qf,e.astToFormula=Fr,e.cellTypes=Yf,e.compile=Zr,e.convertAstNodes=kr,e.coreTypes=Pe,e.functionCache=zr,e.helpers=Kf,e.invalidateEvaluationCommands=$e,e.parse=Or,e.readonlyAllowedCommands=De,e.registries=Xf,e.setTranslationMethod=function(e){i=e},Object.defineProperty(e,"__esModule",{value:!0}),qf.version="15.2.
|
|
3090
|
+
`;class Wf extends t.Component{constructor(e,s={}){super(e,s),this.model=new Nu(this.props.data,{evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},Pf({openSidePanel:(e,t={})=>this.openSidePanel(e,t),toggleSidePanel:(e,t={})=>this.toggleSidePanel(e,t),dispatch:this.model.dispatch,getters:this.model.getters,uuidGenerator:this.model.uuidGenerator,_t:Wf._t,clipboard:navigator.clipboard,export:this.model.exportData.bind(this.model),waitForIdle:this.model.waitForIdle.bind(this.model),exportXLSX:this.model.exportXLSX.bind(this.model),openLinkEditor:()=>this.openLinkEditor()}),this.activateFirstSheet()}setup(){Df(window,"resize",this.render),Df(document.body,"keyup",this.onKeyup.bind(this)),Df(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),Uf((()=>this.initiateModelEvents())),Vf((()=>this.leaveCollaborativeSession())),Bf((e=>this.checkReadonly(e)))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}initiateModelEvents(){this.model.on("update",this,this.render),this.model.on("notify-ui",this,this.onNotifyUI),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}onNotifyUI(e){if("NOTIFICATION"===e.type)this.env.notifyUser(e.text)}checkReadonly(e){this.props.isReadonly!==e.isReadonly&&this.model.updateReadOnly(e.isReadonly)}leaveCollaborativeSession(){this.model.off("update",this),this.model.leaveSession()}activateFirstSheet(){const e=this.model.getters.getActiveSheetId(),[t]=this.model.getters.getSheets();t.id!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:t.id})}destroy(){this.model.destroy(),super.destroy()}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}openLinkEditor(){this.linkEditor.isOpen=!0}closeLinkEditor(){this.linkEditor.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Rh.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Rh.idle?"PREPARE_SELECTION_EXPANSION":"START_SELECTION_EXPANSION");let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}}Wf.template=Zf,Wf.style=Gf,Wf.components={TopBar:$f,Grid:wf,BottomBar:ip,SidePanel:Mf,LinkEditor:ef},Wf._t=e=>e;const qf={},jf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:m,HEADER_WIDTH:v,TOPBAR_HEIGHT:E,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:b,DEFAULT_CELL_HEIGHT:S,SCROLLBAR_WIDTH:C},Xf={autofillModifiersRegistry:La,autofillRulesRegistry:Ma,cellMenuRegistry:gl,colMenuRegistry:fl,linkMenuRegistry:ml,functionRegistry:cr,uiPluginRegistry:ad,corePluginRegistry:rd,rowMenuRegistry:vl,sidePanelRegistry:bh,sheetMenuRegistry:bl,topbarMenuRegistry:Sl,topbarComponentRegistry:Sh,otRegistry:Cl,inverseCommandRegistry:_a,cellRegistry:Wr},Yf={LinkCell:ta},Kf={args:Oe,toBoolean:fe,toNumber:de,toString:pe,toXC:is,toZone:Ws,toCartesian:os,numberToLetters:ss,createFullMenuItem:ka,UuidGenerator:Bs,formatDecimal:ae,computeTextWidth:vs,isMarkdownLink:xs,parseMarkdownLink:Rs,markdownLink:Ts,createEmptyWorkbookData:ga};e.CorePlugin=ma,e.DATETIME_FORMAT=_,e.DataSource=hd,e.DispatchResult=Ve,e.Model=Nu,e.Registry=Me,e.Revision=Kh,e.SPREADSHEET_DIMENSIONS=jf,e.Spreadsheet=Wf,e.UIPlugin=Ch,e.__DEBUG__=Os,e.__info__=qf,e.astToFormula=Fr,e.cellTypes=Yf,e.compile=Zr,e.convertAstNodes=kr,e.coreTypes=Pe,e.functionCache=zr,e.helpers=Kf,e.invalidateEvaluationCommands=$e,e.parse=Or,e.readonlyAllowedCommands=De,e.registries=Xf,e.setTranslationMethod=function(e){i=e},Object.defineProperty(e,"__esModule",{value:!0}),qf.version="15.2.7",qf.date="2023-05-12T10:54:29.220Z",qf.hash="d33fde8"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|